]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blobdiff - libavformat/mov.c
remove comment
[frescor/ffmpeg.git] / libavformat / mov.c
index ed027db04e20b326fd5c5d4cf89681f5eaba137c..c3882b4a84aa4ec5d12bdd2659f5b3a75b40e4ac 100644 (file)
@@ -1,6 +1,7 @@
 /*
  * MOV demuxer
- * Copyright (c) 2001 Fabrice Bellard.
+ * Copyright (c) 2001 Fabrice Bellard
+ * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  *
  * This file is part of FFmpeg.
  *
 #include <limits.h>
 
 //#define DEBUG
+//#define DEBUG_METADATA
+//#define MOV_EXPORT_ALL_METADATA
 
+#include "libavutil/intreadwrite.h"
+#include "libavutil/avstring.h"
 #include "avformat.h"
 #include "riff.h"
 #include "isom.h"
-#include "dv.h"
 #include "libavcodec/mpeg4audio.h"
 #include "libavcodec/mpegaudiodata.h"
+#include "libavcodec/get_bits.h"
 
-#ifdef CONFIG_ZLIB
+#if CONFIG_ZLIB
 #include <zlib.h>
 #endif
 
 #undef NDEBUG
 #include <assert.h>
 
-/* the QuickTime file format is quite convoluted...
- * it has lots of index tables, each indexing something in another one...
- * Here we just use what is needed to read the chunks
- */
-
-typedef struct {
-    int first;
-    int count;
-    int id;
-} MOVStsc;
-
-typedef struct {
-    uint32_t type;
-    char *path;
-} MOVDref;
-
-typedef struct {
-    uint32_t type;
-    int64_t offset;
-    int64_t size; /* total size (excluding the size and type fields) */
-} MOVAtom;
-
-struct MOVParseTableEntry;
-
-typedef struct {
-    unsigned track_id;
-    uint64_t base_data_offset;
-    uint64_t moof_offset;
-    unsigned stsd_id;
-    unsigned duration;
-    unsigned size;
-    unsigned flags;
-} MOVFragment;
-
-typedef struct {
-    unsigned track_id;
-    unsigned stsd_id;
-    unsigned duration;
-    unsigned size;
-    unsigned flags;
-} MOVTrackExt;
-
-typedef struct MOVStreamContext {
-    ByteIOContext *pb;
-    int ffindex; /* the ffmpeg stream id */
-    int next_chunk;
-    unsigned int chunk_count;
-    int64_t *chunk_offsets;
-    unsigned int stts_count;
-    MOVStts *stts_data;
-    unsigned int ctts_count;
-    MOVStts *ctts_data;
-    unsigned int edit_count; /* number of 'edit' (elst atom) */
-    unsigned int sample_to_chunk_sz;
-    MOVStsc *sample_to_chunk;
-    int sample_to_ctime_index;
-    int sample_to_ctime_sample;
-    unsigned int sample_size;
-    unsigned int sample_count;
-    int *sample_sizes;
-    unsigned int keyframe_count;
-    int *keyframes;
-    int time_scale;
-    int time_rate;
-    int current_sample;
-    unsigned int bytes_per_frame;
-    unsigned int samples_per_frame;
-    int dv_audio_container;
-    int pseudo_stream_id; ///< -1 means demux all ids
-    int16_t audio_cid; ///< stsd audio compression id
-    unsigned drefs_count;
-    MOVDref *drefs;
-    int dref_id;
-    int wrong_dts; ///< dts are wrong due to negative ctts
-} MOVStreamContext;
-
-typedef struct MOVContext {
-    AVFormatContext *fc;
-    int time_scale;
-    int64_t duration; /* duration of the longest track */
-    int found_moov; /* when both 'moov' and 'mdat' sections has been found */
-    int found_mdat; /* we suppose we have enough data to read the file */
-    AVPaletteControl palette_control;
-    DVDemuxContext *dv_demux;
-    AVFormatContext *dv_fctx;
-    int isom; /* 1 if file is ISO Media (mp4/3gp) */
-    MOVFragment fragment; ///< current fragment in moof atom
-    MOVTrackExt *trex_data;
-    unsigned trex_count;
-    int itunes_metadata; ///< metadata are itunes style
-} MOVContext;
-
-
 /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
 
 /* those functions parse an atom */
@@ -168,6 +80,96 @@ typedef struct MOVParseTableEntry {
 
 static const MOVParseTableEntry mov_default_parse_table[];
 
+static int mov_metadata_trkn(MOVContext *c, ByteIOContext *pb, unsigned len)
+{
+    char buf[16];
+
+    get_be16(pb); // unknown
+    snprintf(buf, sizeof(buf), "%d", get_be16(pb));
+    av_metadata_set(&c->fc->metadata, "track", buf);
+
+    get_be16(pb); // total tracks
+
+    return 0;
+}
+
+static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+{
+#ifdef MOV_EXPORT_ALL_METADATA
+    char tmp_key[5];
+#endif
+    char str[1024], key2[16], language[4] = {0};
+    const char *key = NULL;
+    uint16_t str_size;
+    int (*parse)(MOVContext*, ByteIOContext*, unsigned) = NULL;
+
+    switch (atom.type) {
+    case MKTAG(0xa9,'n','a','m'): key = "title";     break;
+    case MKTAG(0xa9,'a','u','t'):
+    case MKTAG(0xa9,'A','R','T'):
+    case MKTAG(0xa9,'w','r','t'): key = "author";    break;
+    case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
+    case MKTAG(0xa9,'c','m','t'):
+    case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
+    case MKTAG(0xa9,'a','l','b'): key = "album";     break;
+    case MKTAG(0xa9,'d','a','y'): key = "year";      break;
+    case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
+    case MKTAG(0xa9,'t','o','o'):
+    case MKTAG(0xa9,'e','n','c'): key = "muxer";     break;
+    case MKTAG( 't','r','k','n'): key = "track";
+        parse = mov_metadata_trkn; break;
+    }
+
+    if (c->itunes_metadata && atom.size > 8) {
+        int data_size = get_be32(pb);
+        int tag = get_le32(pb);
+        if (tag == MKTAG('d','a','t','a')) {
+            get_be32(pb); // type
+            get_be32(pb); // unknown
+            str_size = data_size - 16;
+            atom.size -= 16;
+        } else return 0;
+    } else if (atom.size > 4 && key && !c->itunes_metadata) {
+        str_size = get_be16(pb); // string length
+        ff_mov_lang_to_iso639(get_be16(pb), language);
+        atom.size -= 4;
+    } else
+        str_size = atom.size;
+
+#ifdef MOV_EXPORT_ALL_METADATA
+    if (!key) {
+        snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
+        key = tmp_key;
+    }
+#endif
+
+    if (!key)
+        return 0;
+    if (atom.size < 0)
+        return -1;
+
+    str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
+
+    if (parse)
+        parse(c, pb, str_size);
+    else {
+        get_buffer(pb, str, str_size);
+        str[str_size] = 0;
+        av_metadata_set(&c->fc->metadata, key, str);
+        if (*language && strcmp(language, "und")) {
+            snprintf(key2, sizeof(key2), "%s-%s", key, language);
+            av_metadata_set(&c->fc->metadata, key2, str);
+        }
+    }
+#ifdef DEBUG_METADATA
+    av_log(c->fc, AV_LOG_DEBUG, "lang \"%3s\" ", language);
+    av_log(c->fc, AV_LOG_DEBUG, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %lld\n",
+           key, str, (char*)&atom.type, str_size, atom.size);
+#endif
+
+    return 0;
+}
+
 static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
     int64_t total_size = 0;
@@ -180,6 +182,7 @@ static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     if (atom.size < 0)
         atom.size = INT64_MAX;
     while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
+        int (*parse)(MOVContext*, ByteIOContext*, MOVAtom) = NULL;
         a.size = atom.size;
         a.type=0;
         if(atom.size >= 8) {
@@ -205,16 +208,23 @@ static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
             break;
         a.size = FFMIN(a.size, atom.size - total_size);
 
-        for (i = 0; mov_default_parse_table[i].type != 0
-             && mov_default_parse_table[i].type != a.type; i++)
-            /* empty */;
+        for (i = 0; mov_default_parse_table[i].type; i++)
+            if (mov_default_parse_table[i].type == a.type) {
+                parse = mov_default_parse_table[i].parse;
+                break;
+            }
+
+        // container is user data
+        if (!parse && (atom.type == MKTAG('u','d','t','a') ||
+                       atom.type == MKTAG('i','l','s','t')))
+            parse = mov_read_udta_string;
 
-        if (mov_default_parse_table[i].type == 0) { /* skip leaf atoms data */
+        if (!parse) { /* skip leaf atoms data */
             url_fskip(pb, a.size);
         } else {
             int64_t start_pos = url_ftell(pb);
             int64_t left;
-            err = mov_default_parse_table[i].parse(c, pb, a);
+            err = parse(c, pb, a);
             if (url_is_streamed(pb) && c->found_moov && c->found_mdat)
                 break;
             left = a.size - url_ftell(pb) + start_pos;
@@ -242,8 +252,10 @@ static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     entries = get_be32(pb);
     if (entries >= UINT_MAX / sizeof(*sc->drefs))
         return -1;
-    sc->drefs_count = entries;
     sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
+    if (!sc->drefs)
+        return AVERROR(ENOMEM);
+    sc->drefs_count = entries;
 
     for (i = 0; i < sc->drefs_count; i++) {
         MOVDref *dref = &sc->drefs[i];
@@ -302,10 +314,15 @@ static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
 static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
+    AVStream *st;
     uint32_t type;
     uint32_t ctype;
 
+    if (c->fc->nb_streams < 1) // meta before first trak
+        return 0;
+
+    st = c->fc->streams[c->fc->nb_streams-1];
+
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
 
@@ -313,21 +330,18 @@ static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     ctype = get_le32(pb);
     type = get_le32(pb); /* component subtype */
 
-    dprintf(c->fc, "ctype= %c%c%c%c (0x%08x)\n", *((char *)&ctype), ((char *)&ctype)[1],
-            ((char *)&ctype)[2], ((char *)&ctype)[3], (int) ctype);
-    dprintf(c->fc, "stype= %c%c%c%c\n",
-            *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
-    if(!ctype)
-        c->isom = 1;
+    dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
+    dprintf(c->fc, "stype= %.4s\n", (char*)&type);
+
     if     (type == MKTAG('v','i','d','e'))
         st->codec->codec_type = CODEC_TYPE_VIDEO;
     else if(type == MKTAG('s','o','u','n'))
         st->codec->codec_type = CODEC_TYPE_AUDIO;
     else if(type == MKTAG('m','1','a',' '))
         st->codec->codec_id = CODEC_ID_MP2;
-    else if(type == MKTAG('s','u','b','p')) {
+    else if(type == MKTAG('s','u','b','p'))
         st->codec->codec_type = CODEC_TYPE_SUBTITLE;
-    }
+
     get_be32(pb); /* component  manufacture */
     get_be32(pb); /* component flags */
     get_be32(pb); /* component flags mask */
@@ -366,11 +380,12 @@ static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
 #define MP4DecSpecificDescrTag          0x05
 
 static const AVCodecTag mp4_audio_types[] = {
-    { CODEC_ID_MP3ON4, 29 }, /* old mp3on4 draft */
-    { CODEC_ID_MP3ON4, 32 }, /* layer 1 */
-    { CODEC_ID_MP3ON4, 33 }, /* layer 2 */
-    { CODEC_ID_MP3ON4, 34 }, /* layer 3 */
-    { CODEC_ID_NONE,    0 },
+    { CODEC_ID_MP3ON4, AOT_PS   }, /* old mp3on4 draft */
+    { CODEC_ID_MP3ON4, AOT_L1   }, /* layer 1 */
+    { CODEC_ID_MP3ON4, AOT_L2   }, /* layer 2 */
+    { CODEC_ID_MP3ON4, AOT_L3   }, /* layer 3 */
+    { CODEC_ID_MP4ALS, AOT_ALS  }, /* MPEG-4 ALS */
+    { CODEC_ID_NONE,   AOT_NULL },
 };
 
 static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
@@ -436,10 +451,11 @@ static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     const int den = get_be32(pb);
     AVStream * const st = c->fc->streams[c->fc->nb_streams-1];
     if (den != 0) {
-        if ((st->sample_aspect_ratio.den && den != st->sample_aspect_ratio.den) ||
-            (st->sample_aspect_ratio.num && num != st->sample_aspect_ratio.num))
+        if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
+            (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
             av_log(c->fc, AV_LOG_WARNING,
-                   "sample aspect ratio already set, overriding by 'pasp' atom\n");
+                   "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
+                   st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
         st->sample_aspect_ratio.num = num;
         st->sample_aspect_ratio.den = den;
     }
@@ -490,7 +506,8 @@ static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
     MOVStreamContext *sc = st->priv_data;
     int version = get_byte(pb);
-    int lang;
+    char language[4] = {0};
+    unsigned lang;
 
     if (version > 1)
         return -1; /* unsupported */
@@ -508,7 +525,8 @@ static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
 
     lang = get_be16(pb); /* language */
-    ff_mov_lang_to_iso639(lang, st->language);
+    if (ff_mov_lang_to_iso639(lang, language))
+        av_metadata_set(&st->metadata, "language", language);
     get_be16(pb); /* quality */
 
     return 0;
@@ -679,10 +697,11 @@ static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     if(entries >= UINT_MAX/sizeof(int64_t))
         return -1;
 
-    sc->chunk_count = entries;
     sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
     if (!sc->chunk_offsets)
-        return -1;
+        return AVERROR(ENOMEM);
+    sc->chunk_count = entries;
+
     if      (atom.type == MKTAG('s','t','c','o'))
         for(i=0; i<entries; i++)
             sc->chunk_offsets[i] = get_be32(pb);
@@ -835,6 +854,7 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
                 unsigned int color_start, color_count, color_end;
                 unsigned char r, g, b;
 
+                st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
                 if (color_greyscale) {
                     int color_index, color_dec;
                     /* compute the greyscale palette */
@@ -844,7 +864,7 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
                     color_dec = 256 / (color_count - 1);
                     for (j = 0; j < color_count; j++) {
                         r = g = b = color_index;
-                        c->palette_control.palette[j] =
+                        st->codec->palctrl->palette[j] =
                             (r << 16) | (g << 8) | (b);
                         color_index -= color_dec;
                         if (color_index < 0)
@@ -862,10 +882,10 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
                         color_table = ff_qt_default_palette_256;
 
                     for (j = 0; j < color_count; j++) {
-                        r = color_table[j * 4 + 0];
-                        g = color_table[j * 4 + 1];
-                        b = color_table[j * 4 + 2];
-                        c->palette_control.palette[j] =
+                        r = color_table[j * 3 + 0];
+                        g = color_table[j * 3 + 1];
+                        b = color_table[j * 3 + 2];
+                        st->codec->palctrl->palette[j] =
                             (r << 16) | (g << 8) | (b);
                     }
                 } else {
@@ -887,15 +907,13 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
                             get_byte(pb);
                             b = get_byte(pb);
                             get_byte(pb);
-                            c->palette_control.palette[j] =
+                            st->codec->palctrl->palette[j] =
                                 (r << 16) | (g << 8) | (b);
                         }
                     }
                 }
-                st->codec->palctrl = &c->palette_control;
                 st->codec->palctrl->palette_changed = 1;
-            } else
-                st->codec->palctrl = NULL;
+            }
         } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
             int bits_per_sample, flags;
             uint16_t version = get_be16(pb);
@@ -980,8 +998,11 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
             // ttxt stsd contains display flags, justification, background
             // color, fonts, and default styles, so fake an atom to read it
             MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
-            mov_read_glbl(c, pb, fake_atom);
+            if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
+                mov_read_glbl(c, pb, fake_atom);
             st->codec->codec_id= id;
+            st->codec->width = sc->width;
+            st->codec->height = sc->height;
         } else {
             /* other codec type, just skip (rtp, mp4s, tmcd ...) */
             url_fskip(pb, size - (url_ftell(pb) - start_pos));
@@ -1000,9 +1021,9 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     /* special codec parameters handling */
     switch (st->codec->codec_id) {
-#ifdef CONFIG_DV_DEMUXER
+#if CONFIG_DV_DEMUXER
     case CODEC_ID_DVAUDIO:
-        c->dv_fctx = av_alloc_format_context();
+        c->dv_fctx = avformat_alloc_context();
         c->dv_demux = dv_init_demux(c->dv_fctx);
         if (!c->dv_demux) {
             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
@@ -1014,6 +1035,9 @@ static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 #endif
     /* no ifdef since parameters are always those */
     case CODEC_ID_QCELP:
+        // force sample rate for qcelp when not stored in mov
+        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
+            st->codec->sample_rate = 8000;
         st->codec->frame_size= 160;
         st->codec->channels= 1; /* really needed */
         break;
@@ -1061,19 +1085,19 @@ static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     entries = get_be32(pb);
 
-    if(entries >= UINT_MAX / sizeof(*sc->sample_to_chunk))
-        return -1;
-
     dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
 
-    sc->sample_to_chunk_sz = entries;
-    sc->sample_to_chunk = av_malloc(entries * sizeof(*sc->sample_to_chunk));
-    if (!sc->sample_to_chunk)
+    if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
         return -1;
+    sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
+    if (!sc->stsc_data)
+        return AVERROR(ENOMEM);
+    sc->stsc_count = entries;
+
     for(i=0; i<entries; i++) {
-        sc->sample_to_chunk[i].first = get_be32(pb);
-        sc->sample_to_chunk[i].count = get_be32(pb);
-        sc->sample_to_chunk[i].id = get_be32(pb);
+        sc->stsc_data[i].first = get_be32(pb);
+        sc->stsc_data[i].count = get_be32(pb);
+        sc->stsc_data[i].id = get_be32(pb);
     }
     return 0;
 }
@@ -1089,16 +1113,15 @@ static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     entries = get_be32(pb);
 
+    dprintf(c->fc, "keyframe_count = %d\n", entries);
+
     if(entries >= UINT_MAX / sizeof(int))
         return -1;
-
-    sc->keyframe_count = entries;
-
-    dprintf(c->fc, "keyframe_count = %d\n", sc->keyframe_count);
-
     sc->keyframes = av_malloc(entries * sizeof(int));
     if (!sc->keyframes)
-        return -1;
+        return AVERROR(ENOMEM);
+    sc->keyframe_count = entries;
+
     for(i=0; i<entries; i++) {
         sc->keyframes[i] = get_be32(pb);
         //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
@@ -1110,29 +1133,62 @@ static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
     MOVStreamContext *sc = st->priv_data;
-    unsigned int i, entries, sample_size;
+    unsigned int i, entries, sample_size, field_size, num_bytes;
+    GetBitContext gb;
+    unsigned char* buf;
 
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
 
-    sample_size = get_be32(pb);
-    if (!sc->sample_size) /* do not overwrite value computed in stsd */
-        sc->sample_size = sample_size;
+    if (atom.type == MKTAG('s','t','s','z')) {
+        sample_size = get_be32(pb);
+        if (!sc->sample_size) /* do not overwrite value computed in stsd */
+            sc->sample_size = sample_size;
+        field_size = 32;
+    } else {
+        sample_size = 0;
+        get_be24(pb); /* reserved */
+        field_size = get_byte(pb);
+    }
     entries = get_be32(pb);
-    if(entries >= UINT_MAX / sizeof(int))
-        return -1;
+
+    dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
 
     sc->sample_count = entries;
     if (sample_size)
         return 0;
 
-    dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, sc->sample_count);
+    if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
+        av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
+        return -1;
+    }
 
+    if(entries >= UINT_MAX / sizeof(int))
+        return -1;
     sc->sample_sizes = av_malloc(entries * sizeof(int));
     if (!sc->sample_sizes)
+        return AVERROR(ENOMEM);
+
+    num_bytes = (entries*field_size+4)>>3;
+
+    buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
+    if (!buf) {
+        av_freep(&sc->sample_sizes);
+        return AVERROR(ENOMEM);
+    }
+
+    if (get_buffer(pb, buf, num_bytes) < num_bytes) {
+        av_freep(&sc->sample_sizes);
+        av_free(buf);
         return -1;
+    }
+
+    init_get_bits(&gb, buf, 8*num_bytes);
+
     for(i=0; i<entries; i++)
-        sc->sample_sizes[i] = get_be32(pb);
+        sc->sample_sizes[i] = get_bits_long(&gb, field_size);
+
+    av_free(buf);
     return 0;
 }
 
@@ -1147,16 +1203,15 @@ static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
     entries = get_be32(pb);
+
+    dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
+
     if(entries >= UINT_MAX / sizeof(*sc->stts_data))
         return -1;
-
-    sc->stts_count = entries;
     sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
     if (!sc->stts_data)
-        return -1;
-    dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
-
-    sc->time_rate=0;
+        return AVERROR(ENOMEM);
+    sc->stts_count = entries;
 
     for(i=0; i<entries; i++) {
         int sample_duration;
@@ -1167,7 +1222,7 @@ static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         sc->stts_data[i].count= sample_count;
         sc->stts_data[i].duration= sample_duration;
 
-        sc->time_rate= ff_gcd(sc->time_rate, sample_duration);
+        sc->time_rate= av_gcd(sc->time_rate, sample_duration);
 
         dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
 
@@ -1181,6 +1236,31 @@ static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     return 0;
 }
 
+static int mov_read_cslg(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
+{
+    AVStream *st;
+    MOVStreamContext *sc;
+
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
+    get_be32(pb); // version + flags
+
+    sc->dts_shift = get_be32(pb);
+    dprintf(c->fc, "dts shift %d\n", sc->dts_shift);
+
+    sc->time_rate= av_gcd(sc->time_rate, FFABS(sc->dts_shift));
+
+    get_be32(pb); // least dts to pts delta
+    get_be32(pb); // greatest dts to pts delta
+    get_be32(pb); // pts start
+    get_be32(pb); // pts end
+
+    return 0;
+}
+
 static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
@@ -1190,27 +1270,24 @@ static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
     entries = get_be32(pb);
+
+    dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
+
     if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
         return -1;
-
-    sc->ctts_count = entries;
     sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
     if (!sc->ctts_data)
-        return -1;
-    dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
+        return AVERROR(ENOMEM);
+    sc->ctts_count = entries;
 
     for(i=0; i<entries; i++) {
         int count    =get_be32(pb);
         int duration =get_be32(pb);
 
-        if (duration < 0) {
-            sc->wrong_dts = 1;
-            st->codec->has_b_frames = 1;
-        }
         sc->ctts_data[i].count   = count;
         sc->ctts_data[i].duration= duration;
 
-        sc->time_rate= ff_gcd(sc->time_rate, FFABS(duration));
+        sc->time_rate= av_gcd(sc->time_rate, FFABS(duration));
     }
     return 0;
 }
@@ -1225,6 +1302,19 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
     unsigned int stss_index = 0;
     unsigned int i, j;
 
+    /* adjust first dts according to edit list */
+    if (sc->time_offset) {
+        int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
+        assert(sc->time_offset % sc->time_rate == 0);
+        current_dts = - (rescaled / sc->time_rate);
+        if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
+            /* more than 16 frames delay, dts are likely wrong
+               this happens with files created by iMovie */
+            sc->wrong_dts = 1;
+            st->codec->has_b_frames = 1;
+        }
+    }
+
     /* only use old uncompressed audio chunk demuxing when stts specifies it */
     if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
@@ -1234,16 +1324,19 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
         unsigned int distance = 0;
         int key_off = sc->keyframes && sc->keyframes[0] == 1;
 
+        sc->dts_shift /= sc->time_rate;
+        current_dts -= sc->dts_shift;
+
         st->nb_frames = sc->sample_count;
         for (i = 0; i < sc->chunk_count; i++) {
             current_offset = sc->chunk_offsets[i];
-            if (stsc_index + 1 < sc->sample_to_chunk_sz &&
-                i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
+            if (stsc_index + 1 < sc->stsc_count &&
+                i + 1 == sc->stsc_data[stsc_index + 1].first)
                 stsc_index++;
-            for (j = 0; j < sc->sample_to_chunk[stsc_index].count; j++) {
+            for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
                 if (current_sample >= sc->sample_count) {
                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
-                    goto out;
+                    return;
                 }
                 keyframe = !sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index];
                 if (keyframe) {
@@ -1253,13 +1346,14 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
                 }
                 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
                 if(sc->pseudo_stream_id == -1 ||
-                   sc->sample_to_chunk[stsc_index].id - 1 == sc->pseudo_stream_id) {
+                   sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
                     av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
                                     keyframe ? AVINDEX_KEYFRAME : 0);
                     dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
                             current_offset, current_dts, sample_size, distance, keyframe);
                 }
+
                 current_offset += sample_size;
                 assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
                 current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
@@ -1277,10 +1371,10 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
         unsigned int frames = 1;
         for (i = 0; i < sc->chunk_count; i++) {
             current_offset = sc->chunk_offsets[i];
-            if (stsc_index + 1 < sc->sample_to_chunk_sz &&
-                i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
+            if (stsc_index + 1 < sc->stsc_count &&
+                i + 1 == sc->stsc_data[stsc_index + 1].first)
                 stsc_index++;
-            chunk_samples = sc->sample_to_chunk[stsc_index].count;
+            chunk_samples = sc->stsc_data[stsc_index].count;
             /* get chunk size, beware of alaw/ulaw/mace */
             if (sc->samples_per_frame > 0 &&
                 (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0)) {
@@ -1318,9 +1412,6 @@ static void mov_build_index(MOVContext *mov, AVStream *st)
             }
         }
     }
- out:
-    /* adjust sample count to avindex entries */
-    sc->sample_count = st->nb_index_entries;
 }
 
 static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
@@ -1336,34 +1427,38 @@ static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     st->priv_data = sc;
     st->codec->codec_type = CODEC_TYPE_DATA;
-    st->start_time = 0; /* XXX: check */
+    sc->ffindex = st->index;
 
     if ((ret = mov_read_default(c, pb, atom)) < 0)
         return ret;
 
     /* sanity checks */
-    if(sc->chunk_count && (!sc->stts_count || !sc->sample_to_chunk_sz ||
-                           (!sc->sample_size && !sc->sample_count))){
+    if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
+                            (!sc->sample_size && !sc->sample_count))) {
         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
                st->index);
-        sc->sample_count = 0; //ignore track
         return 0;
     }
-    if(!sc->time_rate)
-        sc->time_rate=1;
-    if(!sc->time_scale)
-        sc->time_scale= c->time_scale;
+
+    if (!sc->time_rate)
+        sc->time_rate = 1;
+    if (!sc->time_scale)
+        sc->time_scale = c->time_scale;
+
     av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
 
     if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
-        !st->codec->frame_size && sc->stts_count == 1)
-        st->codec->frame_size = av_rescale(sc->time_rate, st->codec->sample_rate, sc->time_scale);
+        !st->codec->frame_size && sc->stts_count == 1) {
+        st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
+                                           st->codec->sample_rate, sc->time_scale);
+        dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
+    }
 
-    if(st->duration != AV_NOPTS_VALUE){
+    if (st->duration != AV_NOPTS_VALUE) {
         assert(st->duration % sc->time_rate == 0);
         st->duration /= sc->time_rate;
     }
-    sc->ffindex = st->index;
+
     mov_build_index(c, st);
 
     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
@@ -1374,23 +1469,26 @@ static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         sc->pb = c->fc->pb;
 
     switch (st->codec->codec_id) {
-#ifdef CONFIG_H261_DECODER
+#if CONFIG_H261_DECODER
     case CODEC_ID_H261:
 #endif
-#ifdef CONFIG_H263_DECODER
+#if CONFIG_H263_DECODER
     case CODEC_ID_H263:
 #endif
-#ifdef CONFIG_MPEG4_DECODER
+#if CONFIG_H264_DECODER
+    case CODEC_ID_H264:
+#endif
+#if CONFIG_MPEG4_DECODER
     case CODEC_ID_MPEG4:
 #endif
-        st->codec->width= 0; /* let decoder init width/height */
+        st->codec->width = 0; /* let decoder init width/height */
         st->codec->height= 0;
         break;
     }
 
     /* Do not need those anymore. */
     av_freep(&sc->chunk_offsets);
-    av_freep(&sc->sample_to_chunk);
+    av_freep(&sc->stsc_data);
     av_freep(&sc->sample_sizes);
     av_freep(&sc->keyframes);
     av_freep(&sc->stts_data);
@@ -1409,56 +1507,15 @@ static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
 static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    url_fskip(pb, 4); // version + flags
-    atom.size -= 4;
-    return mov_read_default(c, pb, atom);
-}
-
-static int mov_read_trkn(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
-{
-    get_be32(pb); // type
-    get_be32(pb); // unknown
-    c->fc->track = get_be32(pb);
-    dprintf(c->fc, "%.4s %d\n", (char*)&atom.type, c->fc->track);
-    return 0;
-}
-
-static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
-{
-    char *str = NULL;
-    int size;
-    uint16_t str_size;
-
-    if (c->itunes_metadata) {
-        int data_size = get_be32(pb);
-        int tag = get_le32(pb);
-        if (tag == MKTAG('d','a','t','a')) {
-            get_be32(pb); // type
-            get_be32(pb); // unknown
-            str_size = data_size - 16;
-        } else return 0;
-    } else {
-        str_size = get_be16(pb); // string length
-        get_be16(pb); // language
-    }
-    switch (atom.type) {
-    case MKTAG(0xa9,'n','a','m'):
-        str = c->fc->title; size = sizeof(c->fc->title); break;
-    case MKTAG(0xa9,'A','R','T'):
-    case MKTAG(0xa9,'w','r','t'):
-        str = c->fc->author; size = sizeof(c->fc->author); break;
-    case MKTAG(0xa9,'c','p','y'):
-        str = c->fc->copyright; size = sizeof(c->fc->copyright); break;
-    case MKTAG(0xa9,'c','m','t'):
-    case MKTAG(0xa9,'i','n','f'):
-        str = c->fc->comment; size = sizeof(c->fc->comment); break;
-    case MKTAG(0xa9,'a','l','b'):
-        str = c->fc->album; size = sizeof(c->fc->album); break;
+    while (atom.size > 8) {
+        uint32_t tag = get_le32(pb);
+        atom.size -= 4;
+        if (tag == MKTAG('h','d','l','r')) {
+            url_fseek(pb, -8, SEEK_CUR);
+            atom.size += 8;
+            return mov_read_default(c, pb, atom);
+        }
     }
-    if (!str)
-        return 0;
-    get_buffer(pb, str, FFMIN(size, str_size));
-    dprintf(c->fc, "%.4s %s\n", (char*)&atom.type, str);
     return 0;
 }
 
@@ -1470,6 +1527,7 @@ static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     int64_t disp_transform[2];
     int display_matrix[3][2];
     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
+    MOVStreamContext *sc = st->priv_data;
     int version = get_byte(pb);
 
     get_be24(pb); /* flags */
@@ -1489,7 +1547,7 @@ static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     }
     st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
     get_be32(pb); /* reserved */
-    st->start_time = 0; /* check */
+
     /* highlevel (considering edits) duration in movie timebase */
     (version == 1) ? get_be64(pb) : get_be32(pb);
     get_be32(pb); /* reserved */
@@ -1511,6 +1569,8 @@ static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     width = get_be32(pb);       // 16.16 fixed point track width
     height = get_be32(pb);      // 16.16 fixed point track height
+    sc->width = width >> 16;
+    sc->height = height >> 16;
 
     //transform the display width/height according to the matrix
     // skip this if the display matrix is the default identity matrix
@@ -1543,7 +1603,7 @@ static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     flags = get_be24(pb);
 
     track_id = get_be32(pb);
-    if (!track_id || track_id > c->fc->nb_streams)
+    if (!track_id)
         return -1;
     frag->track_id = track_id;
     for (i = 0; i < c->trex_count; i++)
@@ -1574,9 +1634,10 @@ static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
         return -1;
-    c->trex_data = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
-    if (!c->trex_data)
+    trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
+    if (!trex)
         return AVERROR(ENOMEM);
+    c->trex_data = trex;
     trex = &c->trex_data[c->trex_count++];
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
@@ -1591,7 +1652,7 @@ static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
     MOVFragment *frag = &c->fragment;
-    AVStream *st;
+    AVStream *st = NULL;
     MOVStreamContext *sc;
     uint64_t offset;
     int64_t dts;
@@ -1599,9 +1660,16 @@ static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     unsigned entries, first_sample_flags = frag->flags;
     int flags, distance, i;
 
-    if (!frag->track_id || frag->track_id > c->fc->nb_streams)
+    for (i = 0; i < c->fc->nb_streams; i++) {
+        if (c->fc->streams[i]->id == frag->track_id) {
+            st = c->fc->streams[i];
+            break;
+        }
+    }
+    if (!st) {
+        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
         return -1;
-    st = c->fc->streams[frag->track_id-1];
+    }
     sc = st->priv_data;
     if (sc->pseudo_stream_id+1 != frag->stsd_id)
         return 0;
@@ -1612,12 +1680,14 @@ static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     if (flags & 0x001) data_offset        = get_be32(pb);
     if (flags & 0x004) first_sample_flags = get_be32(pb);
     if (flags & 0x800) {
+        MOVStts *ctts_data;
         if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
             return -1;
-        sc->ctts_data = av_realloc(sc->ctts_data,
-                                   (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
-        if (!sc->ctts_data)
+        ctts_data = av_realloc(sc->ctts_data,
+                               (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
+        if (!ctts_data)
             return AVERROR(ENOMEM);
+        sc->ctts_data = ctts_data;
     }
     dts = st->duration;
     offset = frag->base_data_offset + data_offset;
@@ -1651,7 +1721,6 @@ static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
         offset += sample_size;
     }
     frag->moof_offset = offset;
-    sc->sample_count = st->nb_index_entries;
     st->duration = dts;
     return 0;
 }
@@ -1682,7 +1751,7 @@ static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
 static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-#ifdef CONFIG_ZLIB
+#if CONFIG_ZLIB
     ByteIOContext ctx;
     uint8_t *cmov_data;
     uint8_t *moov_data; /* uncompressed data */
@@ -1693,7 +1762,7 @@ static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
     if (get_le32(pb) != MKTAG('d','c','o','m'))
         return -1;
     if (get_le32(pb) != MKTAG('z','l','i','b')) {
-        av_log(NULL, AV_LOG_ERROR, "unknown compression for cmov atom !");
+        av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
         return -1;
     }
     get_be32(pb); /* cmvd atom */
@@ -1704,11 +1773,11 @@ static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     cmov_data = av_malloc(cmov_len);
     if (!cmov_data)
-        return -1;
+        return AVERROR(ENOMEM);
     moov_data = av_malloc(moov_len);
     if (!moov_data) {
         av_free(cmov_data);
-        return -1;
+        return AVERROR(ENOMEM);
     }
     get_buffer(pb, cmov_data, cmov_len);
     if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
@@ -1740,24 +1809,31 @@ static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
-    edit_count= sc->edit_count = get_be32(pb);     /* entries */
+    edit_count = get_be32(pb); /* entries */
 
     for(i=0; i<edit_count; i++){
         int time;
-        get_be32(pb); /* Track duration */
+        int duration = get_be32(pb); /* Track duration */
         time = get_be32(pb); /* Media time */
         get_be32(pb); /* Media rate */
-        if (time != 0)
-            av_log(c->fc, AV_LOG_WARNING, "edit list not starting at 0, "
-                   "a/v desync might occur, patch welcome\n");
+        if (i == 0 && time >= -1) {
+            sc->time_offset = time != -1 ? time : -duration;
+            sc->time_rate = av_gcd(sc->time_rate, FFABS(sc->time_offset));
+        }
     }
-    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, sc->edit_count);
+
+    if(edit_count > 1)
+        av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
+               "a/v desync might occur, patch welcome\n");
+
+    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
     return 0;
 }
 
 static const MOVParseTableEntry mov_default_parse_table[] = {
 { MKTAG('a','v','s','s'), mov_read_extradata },
 { MKTAG('c','o','6','4'), mov_read_stco },
+{ MKTAG('c','s','l','g'), mov_read_cslg },
 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
 { MKTAG('d','i','n','f'), mov_read_default },
 { MKTAG('d','r','e','f'), mov_read_dref },
@@ -1790,26 +1866,18 @@ static const MOVParseTableEntry mov_default_parse_table[] = {
 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
 { MKTAG('s','t','t','s'), mov_read_stts },
+{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
 { MKTAG('t','r','a','k'), mov_read_trak },
 { MKTAG('t','r','a','f'), mov_read_default },
 { MKTAG('t','r','e','x'), mov_read_trex },
-{ MKTAG('t','r','k','n'), mov_read_trkn },
 { MKTAG('t','r','u','n'), mov_read_trun },
 { MKTAG('u','d','t','a'), mov_read_default },
 { MKTAG('w','a','v','e'), mov_read_wave },
 { MKTAG('e','s','d','s'), mov_read_esds },
 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
 { MKTAG('c','m','o','v'), mov_read_cmov },
-{ MKTAG(0xa9,'n','a','m'), mov_read_udta_string },
-{ MKTAG(0xa9,'w','r','t'), mov_read_udta_string },
-{ MKTAG(0xa9,'c','p','y'), mov_read_udta_string },
-{ MKTAG(0xa9,'i','n','f'), mov_read_udta_string },
-{ MKTAG(0xa9,'i','n','f'), mov_read_udta_string },
-{ MKTAG(0xa9,'A','R','T'), mov_read_udta_string },
-{ MKTAG(0xa9,'a','l','b'), mov_read_udta_string },
-{ MKTAG(0xa9,'c','m','t'), mov_read_udta_string },
 { 0, NULL }
 };
 
@@ -1892,12 +1960,12 @@ static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
     MOVStreamContext *sc = 0;
     AVIndexEntry *sample = 0;
     int64_t best_dts = INT64_MAX;
-    int i;
+    int i, ret;
  retry:
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
         MOVStreamContext *msc = st->priv_data;
-        if (st->discard != AVDISCARD_ALL && msc->pb && msc->current_sample < msc->sample_count) {
+        if (st->discard != AVDISCARD_ALL && msc->pb && msc->current_sample < st->nb_index_entries) {
             AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
             int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate,
                                      AV_TIME_BASE, msc->time_scale);
@@ -1929,8 +1997,10 @@ static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
                sc->ffindex, sample->pos);
         return -1;
     }
-    av_get_packet(sc->pb, pkt, sample->size);
-#ifdef CONFIG_DV_DEMUXER
+    ret = av_get_packet(sc->pb, pkt, sample->size);
+    if (ret < 0)
+        return ret;
+#if CONFIG_DV_DEMUXER
     if (mov->dv_demux && sc->dv_audio_container) {
         dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
         av_free(pkt->data);
@@ -1942,20 +2012,20 @@ static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
     pkt->stream_index = sc->ffindex;
     pkt->dts = sample->timestamp;
     if (sc->ctts_data) {
-        assert(sc->ctts_data[sc->sample_to_ctime_index].duration % sc->time_rate == 0);
-        pkt->pts = pkt->dts + sc->ctts_data[sc->sample_to_ctime_index].duration / sc->time_rate;
+        assert(sc->ctts_data[sc->ctts_index].duration % sc->time_rate == 0);
+        pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration / sc->time_rate;
         /* update ctts context */
-        sc->sample_to_ctime_sample++;
-        if (sc->sample_to_ctime_index < sc->ctts_count &&
-            sc->ctts_data[sc->sample_to_ctime_index].count == sc->sample_to_ctime_sample) {
-            sc->sample_to_ctime_index++;
-            sc->sample_to_ctime_sample = 0;
+        sc->ctts_sample++;
+        if (sc->ctts_index < sc->ctts_count &&
+            sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
+            sc->ctts_index++;
+            sc->ctts_sample = 0;
         }
         if (sc->wrong_dts)
             pkt->dts = AV_NOPTS_VALUE;
     } else {
         AVStream *st = s->streams[sc->ffindex];
-        int64_t next_dts = (sc->current_sample < sc->sample_count) ?
+        int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
             st->index_entries[sc->current_sample].timestamp : st->duration;
         pkt->duration = next_dts - pkt->dts;
         pkt->pts = pkt->dts;
@@ -1985,8 +2055,8 @@ static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
         for (i = 0; i < sc->ctts_count; i++) {
             int next = time_sample + sc->ctts_data[i].count;
             if (next > sc->current_sample) {
-                sc->sample_to_ctime_index = i;
-                sc->sample_to_ctime_sample = sc->current_sample - time_sample;
+                sc->ctts_index = i;
+                sc->ctts_sample = sc->current_sample - time_sample;
                 break;
             }
             time_sample = next;
@@ -2004,6 +2074,8 @@ static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_ti
 
     if (stream_index >= s->nb_streams)
         return -1;
+    if (sample_time < 0)
+        sample_time = 0;
 
     st = s->streams[stream_index];
     sample = mov_seek_stream(st, sample_time, flags);
@@ -2026,26 +2098,34 @@ static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_ti
 
 static int mov_read_close(AVFormatContext *s)
 {
-    int i, j;
     MOVContext *mov = s->priv_data;
-    for(i=0; i<s->nb_streams; i++) {
-        MOVStreamContext *sc = s->streams[i]->priv_data;
+    int i, j;
+
+    for (i = 0; i < s->nb_streams; i++) {
+        AVStream *st = s->streams[i];
+        MOVStreamContext *sc = st->priv_data;
+
         av_freep(&sc->ctts_data);
-        for (j=0; j<sc->drefs_count; j++)
+        for (j = 0; j < sc->drefs_count; j++)
             av_freep(&sc->drefs[j].path);
         av_freep(&sc->drefs);
         if (sc->pb && sc->pb != s->pb)
             url_fclose(sc->pb);
+
+        av_freep(&st->codec->palctrl);
     }
-    if(mov->dv_demux){
-        for(i=0; i<mov->dv_fctx->nb_streams; i++){
+
+    if (mov->dv_demux) {
+        for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
             av_freep(&mov->dv_fctx->streams[i]->codec);
             av_freep(&mov->dv_fctx->streams[i]);
         }
         av_freep(&mov->dv_fctx);
         av_freep(&mov->dv_demux);
     }
+
     av_freep(&mov->trex_data);
+
     return 0;
 }