Extracting mp4 files from AVCHD without transcoding

My new Sony digital camera stores movies inside an AVCHD container. Luckily this format is supported on OSX natively and you can at least browse all clips inside with ease. However, if you want to export clips there is a limitation: OSX forces you to transcode the video when exporting to .mp4. This is slow and introduces quality loss. I started wondering if there is a better way and as it turns out there is :)

Internally the AVCHD container has a number of .MTS files, which in my case contain perfectly fine H264 video and AAC audio. It should be enough to re-multiplex (meaning ‘copy data stream but don’t re-encode’) these streams into an MP4 container format. MP4 is widely supported by most devices (and OSX itself). The go-to tool in these kinds of situation is ffmpeg and we will use this to re-multiplex the streams. As an added bonus, the timestamp of the MP4 file will be set to the original .MTS timestamp.

To get ffmpeg on Linux, just install the ‘ffmpeg’ package. On OSX an easy way to get ffmpeg is to install it via Homebrew

Here is the code, it should be run from the AVCHD/BDMV/STREAM directory level:

#!/bin/bash

WORKDIR=`basename $PWD`

# Safety check
if ! [[ "$WORKDIR" == "STREAM" ]]; then
        echo "This script is supposed to run from AVCHD/BDMV/STREAM directory level, exiting now"
        exit 1
fi

# Is ffmpeg installed
if ! [ -x "$(command -v ffmpeg)" ]; then
  echo "ffmpeg is not installed, exiting now"
  exit 1
fi

# Re-mux all .MTS files into an mp4 container and set the timestamp of the mp4 to the same as the .MTS file
for i in *.MTS; do ffmpeg -i $i -vcodec copy -acodec copy -f mp4 ../../../`basename $i .MTS`.mp4 && touch -r $i ../../../`basename $i .MTS`.mp4 ; done

The resulting MP4 files will be put in the same directory as the AVCHD folder. For added convenience, you can download the file here.