How to convert matroska MKV to AVI on Linux ?

Today, I discover that my M3100 player doesn’t know how to play Mastroka files. Mastroka files are really kool since the subtitles are embeded in .. but that’s it, my player refuse to play open it.

This stuff can be repack in a AVI (xivd..) file with some open source tools. Here, a little script to do the hard stuff ;)

You can find the script here : http://svn.pythonfr.org/public/pythonfr/utils/video/mkv2avi.py

#!/usr/bin/python
# Little script to depack Matroska file, and repack them
# in a AVI + subtitle format.

import sys
import os

def message(msg):
    print "=" * 78
    print "= %s" % msg
    print "=" * 78

def usage():
    print "Mastroka repacker script"
    print "  Usage: "+sys.argv[0]+ " filename"

if __name__ == "__main__":
    if len(sys.argv) < 2:
       usage()
    else:
       filename = sys.argv[1]
       basename = filename[:-4]
       message("Unpacking file: %s" % filename)
       os.system("mkvextract tracks %s 1:temp_video.avi 2:temp_audio.ogg 3:%s.srt" % (filename,basename) )

       message("Repacking file: %s.avi" % basename)
       os.system("ffmpeg -i temp_audio.ogg  -i temp_video.avi  -vcodec copy  %s.avi" % (basename) )

       message("Cleaning files")
       os.system("rm temp_video.avi temp_audio.ogg")

/Enjoy Video



Related Posts

44 thoughts on “How to convert matroska MKV to AVI on Linux ?

  1. i have a problem with this…
    built on Jan 28 2007 22:48:38, gcc: 4.1.2 20070106 (prerelease) (Ubuntu 4.1.1-21ubuntu7)
    temp_audio.ogg: could not find codec parameters
    Cleaning files
    root@desktop:/Potter
    When it finish remove the file .ogg and .avi
    Please.
    what i need?

  2. Tried the script but then fell foul with the ffmpeg params.

    After checking out the ffmpeg site I found the latest version as of 8/1/2008 supports .mkv:

    ffmpeg -i cobra.mkv -target vcd cobra.avi

  3. I’m new to this so I’m a bit confused. I tried this on a 1.1GB 720p x264 encoding and wound up with a 26MB audio file with no video. The sound quality was seriously degraded as well. I commented out the temp_video.avi file, which looks to be about the right size, but I couldn’t find anything that could play it.

    What am I missing here?

    Thanks,
    Keith

  4. Keith, check the mkv contains a ogg file. It’s perhaps something else. (try the file command)

  5. Thanks for your reply “jkx”.

    “file *” returns the following:

    keithh@pvr [106]: file *
    temp_audio.ogg: ATSC A/52 aka AC-3 aka Dolby Digital stream, 48 kHz,, complete main (CM) 3 front/2 rear, LFE on,, 384 kbit/s reserved Dolby Surround mode
    temp_video.avi: JVT NAL sequence, H.264 video @ L 51
    XXXXX.hdtv.x264-bia.avi: RIFF (little-endian) data, AVI, 0 x 0, >30 fps,
    XXXXX.hdtv.x264-bia.mkv: Matroska data

    It managed to extract a decent sized ogg file but the file command gives no indication of whether or not it is an ogg file. It probably isn’t since it’s video. Am I barking up the wrong tree here? Was your script only intended to extract the audio?

    keithh@pvr [105]: wc -c *
    139198464 temp_audio.ogg
    1012791223 temp_video.avi
    25978426 XXXXX.hdtv.x264-bia.avi
    1153155923 XXXXX.hdtv.x264-bia.mkv
    2331132311 total

    I mispoke when I said I commented out the temp_video.avi file. I meant to say that I commented out the *removal* of that file in your script.

    It looks like the tools are willing to do what I need. Perhaps I need some different options. Any more suggestions that you might have would be very welcome.

    Thanks again,
    Keith

  6. Hum, take care the ogg file is a 5.2 stream. I’m quite sure you need to resample (or tweak) ffmpeg to handle this.

  7. No, the quality remains the same. In fact, it’s only a repack, not a real convert

  8. Hi i got an error when i tried this script,
    I put this script into a file called mkvtoavi and made it executeable
    then in bash#

    ./mkvtoavi
    File “./mkvtoavi”, line 9
    print “=” * 78
    ^
    IndentationError: expected an indented block

    And i am not really good with scriptprogramming. but it seems it’s something thats missing :( please reply to my email as soon as you can :)

  9. Ok, figured out an answer to my own question, and got it down to one line with no intermediate files. Your modified .py script becomes:

    #!/usr/bin/python
    # Little script to depack Matroska file, and repack them
    # in a AVI + subtitle format.

    import sys
    import os

    def message(msg):
    print “=” * 78
    print “= %s” % msg
    print “=” * 78

    def usage():
    print “Mastroka repacker script”
    print ” Usage: “+sys.argv[0]+ ” filename”

    if __name__ == “__main__”:
    if len(sys.argv) < 2:
    usage()
    else:
    filename = sys.argv[1]
    basename = filename[:-4]
    message(“Converting file: %s” % filename)
    os.system(“mencoder %s -ovc lavc -oac lavc -o %s.avi” % (filename,basename) )

  10. To Yoshii, this script needs you to tab in some things to work…

    #!/usr/bin/python
    # Little script to depack Matroska file, and repack them
    # in a AVI + subtitle format.

    import sys
    import os

    def message(msg):
    TAB—>print “=” * 78
    TAB—>print “= %s” % msg
    TAB—>print “=” * 78

    def usage():
    TAB—>print “Mastroka repacker script”
    TAB—>print ” Usage: “+sys.argv[0]+ ” filename”

    if __name__ == “__main__”:
    TAB—>if len(sys.argv) TAB—>usage()
    TAB—>else:
    TAB—>TAB—>filename = sys.argv[1]
    TAB—>TAB—>basename = filename[:-4]

    message(“Unpacking file: %s” % filename)
    os.system(“mkvextract tracks %s 1:temp_video.avi 2:temp_audio.ogg 3:%s.srt” % (filename,basename) )

    message(“Repacking file: %s.avi” % basename)
    os.system(“ffmpeg -i temp_audio.ogg -i temp_video.avi -vcodec copy %s.avi” % (basename) )

    message(“Cleaning files”)
    os.system(“rm temp_video.avi temp_audio.ogg”)

  11. To import the sub you can use Avidemux. I used this software a couple of times without issue.

  12. ::SIGH::

    I realize that people tend to “think” in their favorite language, but isn’t using python for this sort of like swatting a fly with a sledgehammer?

    #!/bin/bash
    [[ -z "$1" ]] && echo “usage: $0 filename” && exit
    mencoder $1 -ovc lavc -oac lavc -o `basename $1 .${1#*.}`.avi

  13. Martin: that also re-encodes the streams, better use copy. Also, basename matches first ‘.’, which means that foo.bar.mkv becomes foo.avi..

    Maybe use best of both approaches, and modify the original to just have:

    message(“Converting %s to %s.avi” % (filename, basename))
    os.system(“mencoder %s -ovc copy -oac copy -o %s.avi” % (filename, basename) )

  14. mencoder has long been the most flexible OSS tool for producing and repacking AVI’s … ffmpeg is more useful at low level stuff where you need to re-encode.

    using -ovc copy is both better and much faster, as it avoids re-encoding the video …. also mencoder’s default settings for video encoding are designed around non-HD quality and internet streaming, and you’ll end up having to dink around. I’m sticking with -oac lavc and leaving it to re-encode to the default non-Dolby “DVD style” audio (2 x 48kHz) since I don’t have surround sound set up yet and the file sizes are about 10% smaller.

    My goal is to get stuff to play on the Sony PS3 which has become our DVD player – it happily plays files from CD-R and DVD-R (and presumably BD-RE though the blanks are kind pricey :-) and it will play AVI’s in HDTV formats, but it does not (as of the latest PS3 OS build) speak Matroska and likely never will (Sony being pro-proprietary)

  15. This is very helpful, thanks!

    I am able to use mencoder to convert mkv file to avi but it does not have audio. I read some sites online. They are saying it is because multple audio. I wonder if anyone has solution for it?

    Thanks in advance!

  16. I did this manually. However, I have missed something (the python script only gave errors)

    $ mkvextract tracks down-ltroi-720p.mkv 1:temp_video.avi 2:temp_audio.ogg 3:down-ltroi-720p.srt
    $ mkdir temp
    $ cd temp
    $ mkvextract tracks ../down-ltroi-720p.mkv 1:temp_video.avi 2:temp_audio.ogg 3:down-ltroi-720p.srt
    Extracting track 1 with the CodecID ‘V_MPEG4/ISO/AVC’ to the file ‘temp_video.avi’. Container format: AVC/h.264 elementary stream
    Extracting track 2 with the CodecID ‘A_DTS’ to the file ‘temp_audio.ogg’. Container format: Digital Theater System (DTS)
    Extracting track 3 with the CodecID ‘S_TEXT/UTF8′ to the file ‘down-ltroi-720p.srt’. Container format: SRT text subtitles
    progress: 100%

    $ ffmpeg -i temp_audio.ogg -i temp_video.avi -vcodec copy temp_video.avi
    FFmpeg version SVN-rUNKNOWN, Copyright (c) 2000-2007 Fabrice Bellard, et al.
    configuration: –enable-gpl –enable-pp –enable-swscaler –enable-pthreads –enable-libvorbis –enable-libtheora –enable-libogg –enable-libgsm –enable-dc1394 –disable-debug –enable-libmp3lame –enable-libfaadbin –enable-libfaad –enable-libfaac –enable-xvid –enable-x264 –enable-liba52 –enable-amr_nb –enable-amr_wb –enable-shared –prefix=/usr
    libavutil version: 1d.49.3.0
    libavcodec version: 1d.51.38.0
    libavformat version: 1d.51.10.0
    built on Mar 17 2009 21:37:49, gcc: 4.2.4 (Ubuntu 4.2.4-1ubuntu3)
    [mp3 @ 0xb7ec6110]Could not find codec parameters (Audio: mp2, 112 kb/s)
    temp_audio.ogg: could not find codec parameters

  17. Sweet script, once I got the tabs sorted out it worked great! I’ve got 6 seasons of Ranma 1/2 to convert with this now!!! Thanks for the handy script.

  18. Hi, I took note of the comments re using mencoder above and updated the script so it works with quirky filenames (spaces, brackets etc).

    After the else statement in the original script, change everything to:

    filename = os.path.normpath('"'+sys.argv[1]+'"')
    basename = filename[:-5]

    message("Converting %s to %s.avi\"" % (filename, basename))
    os.system("mencoder %s -quiet -ovc copy -oac copy -o %s.avi\"" % (filename, basename))

    Mencoder doesn’t like files with spaces in it. The filename needs to be passed to it within quotes, hence all the weird wrangling with quotes in the above.

  19. Hi All! A newbie to linux here does anyone have the complete script/command they can post for me? I don’t understand most of what your talking about here. I am trying to convert .mkv file to .avi as the mkv’s will not play correctly on my system/PII450/100 256mb ram/ 15gb hdd-5gb free. thanks in advance, james

  20. I had the same performance problem on my Asus eee

    On my Ubuntu 9.xx, I use the command:

    ffmpeg -i infilename.m4v -target vcd outmoviefilename.avi

    Do NOT use any filenames with “strange” characters like & or space for in and out files to simplify the syntax

    Good luck

    /F

  21. I had some issues with script too and this is the FFMPEG command line I ended up with: (1.1G mkv)

    ffmpeg -i temp_audio.ac3 -i temp_video.h264 -b 2000 -r 25 -g 12 -qmin 3 -qmax 13 -s 1280×720 -vcodec libxvid -pass 1 -acodec ac3 -ab 224000 -ar 44100 -ac 1 -aspect 16:9 f.avi

    NOTE:

    I renamed the audio to use .ac3 (clearer)
    and te video to use .h264 (clearer)

    Do not use the ‘f.avi’ if you paste it into the script, use the %s as is.

    used mkvinfo to get aspect ratios and audio codec info.

  22. None of these work for me, they all fail in one way or another.

    @brahmix
    this returns an error “SyntaxError: Non-ASCII character ‘\xc3′ in file ./mkv2avi on line 31, but no encoding declared”

    this command doesn’t work either

    ffmpeg -i infilename.m4v ntsc-target vcd outmoviefilename.avi

    I get

    “Unable to find a suitable output format for ‘ntsc-target’” as the final error, but it required me to add ntsc prefix for -target.

    anyone have any ideas?

  23. For the \xc3 issue you need to remove

    ‘-s 1280×720′

    For the original script I was getting the following error

    mp2 @ 0x8cf19f0]encoding 6 channel(s) is not allowed in mp2
    Error while opening codec for output stream #0.1 – maybe incorrect parameters such as bit_rate, rate, width or height

    Anyone know how to fix that?

  24. replace all instances of %s with ‘%s’ to fix the “weird filename” problem
    for example, this line

    os.system(“mkvextract tracks %s 1:temp_video.avi 2:temp_audio.ogg 3:%s.srt” % (filename,basename) )

    should be

    os.system(“mkvextract tracks ‘%s’ 1:temp_video.avi 2:temp_audio.ogg 3:’%s’.srt” % (filename,basename) )

  25. Dave, I had the same problem using “-oac copy”. Changed it to “-oac mp3lame” making the whole line look like this:

    mencoder [filename].mkv -ovc xvid -xvidencopts fixed_quant=4 -vf harddup -oac mp3lame -o [filename].avi

    I guess the recoding does the trick.

  26. Hi. Thanks a lot for your script!!

    It dumps an error:

    [snip]
    FFmpeg version SVN-r0.5.1-4:0.5.1-1ubuntu1, Copyright (c) 2000-2009 Fabrice Bellard, et al.
    configuration: –extra-version=4:0.5.1-1ubuntu1 –prefix=/usr –enable-avfilter –enable-avfilter-lavf –enable-vdpau –enable-bzlib –enable-libgsm –enable-libschroedinger –enable-libspeex –enable-libtheora –enable-libvorbis –enable-pthreads –enable-zlib –disable-stripping –disable-vhook –enable-runtime-cpudetect –enable-gpl –enable-postproc –enable-swscale –enable-x11grab –enable-libdc1394 –enable-shared –disable-static
    libavutil 49.15. 0 / 49.15. 0
    libavcodec 52.20. 1 / 52.20. 1
    libavformat 52.31. 0 / 52.31. 0
    libavdevice 52. 1. 0 / 52. 1. 0
    libavfilter 0. 4. 0 / 0. 4. 0
    libswscale 0. 7. 1 / 0. 7. 1
    libpostproc 51. 2. 0 / 51. 2. 0
    built on Mar 4 2010 12:35:30, gcc: 4.4.3
    Input #0, aac, from ‘temp_audio.ogg’:
    Duration: 00:40:25.85, bitrate: 217 kb/s
    Stream #0.0: Audio: aac, 48000 Hz, stereo, s16, 217 kb/s

    Seems stream 0 codec frame rate differs from container frame rate: 47.95 (48000/1001) -> 23.98 (48000/2002)
    Input #1, h264, from ‘temp_video.avi’:
    Duration: N/A, bitrate: N/A
    Stream #1.0: Video: h264, yuv420p, 1280×720, 23.98 tbr, 1200k tbn, 47.95 tbc
    Output #0, avi, to ‘myvideo.avi’:
    Stream #0.0: Video: libx264, yuv420p, 1280×720, q=2-31, 90k tbn, 23.98 tbc
    Stream #0.1: Audio: mp2, 48000 Hz, stereo, s16, 64 kb/s
    Stream mapping:
    Stream #1.0 -> #0.0
    Stream #0.0 -> #0.1
    Press [q] to stop encoding
    [NULL @ 0x8c63110]error, non monotone timestamps 62562 >= 62562=3236.6kbits/s
    av_interleaved_write_frame(): Error while opening file

    Cleaning files

    I’ve proved this http://ubuntuforums.org/showthread.php?t=786095&page=34
    but didn’t work ;-(

    PS: I keep looking in Google ;-)

  27. At last, I’ve found a set of options which don’t cause error:

    os.system(“ffmpeg -i temp_audio.ogg -i temp_video.avi -f avi -vcodec mpeg4 -b 950k -g 300 -bf 2 -acodec mp2 -ab 64k -vtag divx ‘%s’.avi” % (basename) )

    PS: However, it’s not a optimal set of options :-( This was just a try!

  28. for those who have a syntax error; it is due to the python version. you need to explicitly state python2 in the case of archlinux. script needs modification for python3.

    jesse

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>