]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/mxfdec.c
mxfdec: Make sure x < index_table->nb_ptses
[ffmpeg] / libavformat / mxfdec.c
index 571b7ef9f2b95b2eb2a196b61172c042f509a35b..ea1129388e0347150cbcf277dac4e12278469848 100644 (file)
@@ -69,6 +69,7 @@ typedef enum {
     OP3b,
     OP3c,
     OPAtom,
+    OPSONYOpt,  /* FATE sample, violates the spec in places */
 } MXFOP;
 
 typedef struct {
@@ -78,6 +79,13 @@ typedef struct {
     uint64_t previous_partition;
     int index_sid;
     int body_sid;
+    int64_t this_partition;
+    int64_t essence_offset;         /* absolute offset of essence */
+    int64_t essence_length;
+    int32_t kag_size;
+    int64_t header_byte_count;
+    int64_t index_byte_count;
+    int pack_length;
 } MXFPartition;
 
 typedef struct {
@@ -140,16 +148,12 @@ typedef struct {
     int edit_unit_byte_count;
     int index_sid;
     int body_sid;
-    int slice_count;
     AVRational index_edit_rate;
     uint64_t index_start_position;
     uint64_t index_duration;
-    int *slice;
-    int *element_delta;
-    int nb_delta_entries;
+    int8_t *temporal_offset_entries;
     int *flag_entries;
     uint64_t *stream_offset_entries;
-    uint32_t **slice_offset_entries;
     int nb_index_entries;
 } MXFIndexTableSegment;
 
@@ -168,6 +172,18 @@ typedef struct {
     enum MXFMetadataSetType type;
 } MXFMetadataSet;
 
+/* decoded index table */
+typedef struct {
+    int index_sid;
+    int body_sid;
+    int nb_ptses;               /* number of PTSes or total duration of index */
+    int64_t first_dts;          /* DTS = EditUnit + first_dts */
+    int64_t *ptses;             /* maps EditUnit -> PTS */
+    int nb_segments;
+    MXFIndexTableSegment **segments;    /* sorted by IndexStartPosition */
+    AVIndexEntry *fake_index;   /* used for calling ff_index_search_timestamp() */
+} MXFIndexTable;
+
 typedef struct {
     MXFPartition *partitions;
     unsigned partitions_count;
@@ -181,12 +197,16 @@ typedef struct {
     uint8_t *local_tags;
     int local_tags_count;
     uint64_t footer_partition;
-    int system_item;
-    int64_t essence_offset;
-    int first_essence_kl_length;
-    int64_t first_essence_length;
     KLVPacket current_klv_data;
     int current_klv_index;
+    int run_in;
+    MXFPartition *current_partition;
+    int parsing_backward;
+    int64_t last_forward_tell;
+    int last_forward_partition;
+    int current_edit_unit;
+    int nb_index_tables;
+    MXFIndexTable *index_tables;
 } MXFContext;
 
 enum MXFWrappingScheme {
@@ -194,7 +214,8 @@ enum MXFWrappingScheme {
     Clip,
 };
 
-typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid);
+/* NOTE: klv_offset is not set (-1) for local keys */
+typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
 
 typedef struct {
     const UID key;
@@ -206,6 +227,7 @@ typedef struct {
 /* partial keys to match */
 static const uint8_t mxf_header_partition_pack_key[]       = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
 static const uint8_t mxf_essence_element_key[]             = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
+static const uint8_t mxf_avid_essence_element_key[]        = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
 static const uint8_t mxf_system_item_key[]                 = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
 static const uint8_t mxf_klv_key[]                         = { 0x06,0x0e,0x2b,0x34 };
 /* complete keys to match */
@@ -361,53 +383,7 @@ static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv
     return 0;
 }
 
-static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
-{
-    KLVPacket klv;
-
-    while (!url_feof(s->pb)) {
-        if (klv_read_packet(&klv, s->pb) < 0)
-            return -1;
-        PRINT_KEY(s, "read packet", klv.key);
-        av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
-        if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
-            int res = mxf_decrypt_triplet(s, pkt, &klv);
-            if (res < 0) {
-                av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
-                return -1;
-            }
-            return 0;
-        }
-        if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
-            int index = mxf_get_stream_index(s, &klv);
-            if (index < 0) {
-                av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
-                goto skip;
-            }
-            if (s->streams[index]->discard == AVDISCARD_ALL)
-                goto skip;
-            /* check for 8 channels AES3 element */
-            if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
-                if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
-                    av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
-                    return -1;
-                }
-            } else {
-                int ret = av_get_packet(s->pb, pkt, klv.length);
-                if (ret < 0)
-                    return ret;
-            }
-            pkt->stream_index = index;
-            pkt->pos = klv.offset;
-            return 0;
-        } else
-        skip:
-            avio_skip(s->pb, klv.length);
-    }
-    return AVERROR_EOF;
-}
-
-static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFContext *mxf = arg;
     int item_num = avio_rb32(pb);
@@ -427,7 +403,7 @@ static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, U
     return 0;
 }
 
-static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFContext *mxf = arg;
     MXFPartition *partition;
@@ -441,7 +417,21 @@ static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size
     if (!mxf->partitions)
         return AVERROR(ENOMEM);
 
-    partition = &mxf->partitions[mxf->partitions_count++];
+    if (mxf->parsing_backward) {
+        /* insert the new partition pack in the middle
+         * this makes the entries in mxf->partitions sorted by offset */
+        memmove(&mxf->partitions[mxf->last_forward_partition+1],
+                &mxf->partitions[mxf->last_forward_partition],
+                (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
+        partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
+    } else {
+        mxf->last_forward_partition++;
+        partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
+    }
+
+    memset(partition, 0, sizeof(*partition));
+    mxf->partitions_count++;
+    partition->pack_length = avio_tell(pb) - klv_offset + size;
 
     switch(uid[13]) {
     case 2:
@@ -461,10 +451,13 @@ static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size
     /* consider both footers to be closed (there is only Footer and CompleteFooter) */
     partition->closed = partition->type == Footer || !(uid[14] & 1);
     partition->complete = uid[14] > 2;
-    avio_skip(pb, 16);
+    avio_skip(pb, 4);
+    partition->kag_size = avio_rb32(pb);
+    partition->this_partition = avio_rb64(pb);
     partition->previous_partition = avio_rb64(pb);
     footer_partition = avio_rb64(pb);
-    avio_skip(pb, 16);
+    partition->header_byte_count = avio_rb64(pb);
+    partition->index_byte_count = avio_rb64(pb);
     partition->index_sid = avio_rb32(pb);
     avio_skip(pb, 8);
     partition->body_sid = avio_rb32(pb);
@@ -480,8 +473,9 @@ static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size
         }
     }
 
-    av_dlog(mxf->fc, "PartitionPack: PreviousPartition = 0x%lx, "
+    av_dlog(mxf->fc, "PartitionPack: ThisPartition = 0x%lx, PreviousPartition = 0x%lx, "
             "FooterPartition = 0x%lx, IndexSID = %i, BodySID = %i\n",
+            partition->this_partition,
             partition->previous_partition, footer_partition,
             partition->index_sid, partition->body_sid);
 
@@ -495,8 +489,22 @@ static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size
     else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
     else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
     else if (op[12] == 0x10)             mxf->op = OPAtom;
-    else
-        av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh\n", op[12], op[13]);
+    else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
+    else {
+        av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
+        mxf->op = OP1a;
+    }
+
+    if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
+        av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %i - guessing ", partition->kag_size);
+
+        if (mxf->op == OPSONYOpt)
+            partition->kag_size = 512;
+        else
+            partition->kag_size = 1;
+
+        av_log(mxf->fc, AV_LOG_WARNING, "%i\n", partition->kag_size);
+    }
 
     return 0;
 }
@@ -513,7 +521,7 @@ static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
     return 0;
 }
 
-static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFCryptoContext *cryptocontext = arg;
     if (size != 16)
@@ -523,7 +531,7 @@ static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, i
     return 0;
 }
 
-static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFContext *mxf = arg;
     switch (tag) {
@@ -541,7 +549,7 @@ static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int siz
     return 0;
 }
 
-static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFStructuralComponent *source_clip = arg;
     switch(tag) {
@@ -563,7 +571,7 @@ static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, U
     return 0;
 }
 
-static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFPackage *package = arg;
     switch(tag) {
@@ -581,7 +589,7 @@ static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int si
     return 0;
 }
 
-static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFTrack *track = arg;
     switch(tag) {
@@ -602,7 +610,7 @@ static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid
     return 0;
 }
 
-static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFSequence *sequence = arg;
     switch(tag) {
@@ -626,7 +634,7 @@ static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID
     return 0;
 }
 
-static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFPackage *package = arg;
     switch(tag) {
@@ -652,25 +660,6 @@ static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size
     return 0;
 }
 
-static int mxf_read_delta_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
-{
-    int i, length;
-
-    segment->nb_delta_entries = avio_rb32(pb);
-    length = avio_rb32(pb);
-
-    if (!(segment->slice         = av_calloc(segment->nb_delta_entries, sizeof(*segment->slice))) ||
-        !(segment->element_delta = av_calloc(segment->nb_delta_entries, sizeof(*segment->element_delta))))
-        return AVERROR(ENOMEM);
-
-    for (i = 0; i < segment->nb_delta_entries; i++) {
-        avio_r8(pb);    /* PosTableIndex */
-        segment->slice[i] = avio_r8(pb);
-        segment->element_delta[i] = avio_rb32(pb);
-    }
-    return 0;
-}
-
 static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
 {
     int i, j, length;
@@ -678,32 +667,22 @@ static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *seg
     segment->nb_index_entries = avio_rb32(pb);
     length = avio_rb32(pb);
 
-    if (!(segment->flag_entries          = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
+    if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
+        !(segment->flag_entries          = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
         !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
         return AVERROR(ENOMEM);
 
-    if (segment->slice_count &&
-        !(segment->slice_offset_entries  = av_calloc(segment->nb_index_entries, sizeof(*segment->slice_offset_entries))))
-        return AVERROR(ENOMEM);
-
     for (i = 0; i < segment->nb_index_entries; i++) {
-        avio_rb16(pb);  /* TemporalOffset and KeyFrameOffset */
+        segment->temporal_offset_entries[i] = avio_r8(pb);
+        avio_r8(pb);                                        /* KeyFrameOffset */
         segment->flag_entries[i] = avio_r8(pb);
         segment->stream_offset_entries[i] = avio_rb64(pb);
-        if (segment->slice_count) {
-            if (!(segment->slice_offset_entries[i] = av_calloc(segment->slice_count, sizeof(**segment->slice_offset_entries))))
-                return AVERROR(ENOMEM);
-
-            for (j = 0; j < segment->slice_count; j++)
-                segment->slice_offset_entries[i][j] = avio_rb32(pb);
-        }
-
-        avio_skip(pb, length - 11 - 4 * segment->slice_count);
+        avio_skip(pb, length - 11);
     }
     return 0;
 }
 
-static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFIndexTableSegment *segment = arg;
     switch(tag) {
@@ -719,13 +698,6 @@ static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int
         segment->body_sid = avio_rb32(pb);
         av_dlog(NULL, "BodySID %d\n", segment->body_sid);
         break;
-    case 0x3F08:
-        segment->slice_count = avio_r8(pb);
-        av_dlog(NULL, "SliceCount %d\n", segment->slice_count);
-        break;
-    case 0x3F09:
-        av_dlog(NULL, "DeltaEntryArray found\n");
-        return mxf_read_delta_entry_array(pb, segment);
     case 0x3F0A:
         av_dlog(NULL, "IndexEntryArray found\n");
         return mxf_read_index_entry_array(pb, segment);
@@ -766,7 +738,7 @@ static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
     ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
 }
 
-static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid)
+static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
 {
     MXFDescriptor *descriptor = arg;
     switch(tag) {
@@ -868,14 +840,18 @@ static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMe
     return NULL;
 }
 
-static const MXFCodecUL mxf_essence_container_uls[] = {
+static const MXFCodecUL mxf_picture_essence_container_uls[] = {
     // video essence container uls
     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14,    CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
+    { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      CODEC_ID_NONE },
+};
+static const MXFCodecUL mxf_sound_essence_container_uls[] = {
     // sound essence container uls
     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14,       CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */
     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */
+    { { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0xFF,0x4B,0x46,0x41,0x41,0x00,0x0D,0x4D,0x4F }, 14, CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */
     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      CODEC_ID_NONE },
 };
 
@@ -936,109 +912,295 @@ static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segment
     return 0;
 }
 
-static int mxf_parse_index(MXFContext *mxf, int i, AVStream *st)
+/**
+ * Computes the absolute file offset of the given essence container offset
+ */
+static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
 {
-    int64_t accumulated_offset = 0;
-    int j, k, ret, nb_sorted_segments;
-    MXFIndexTableSegment **sorted_segments;
+    int x;
+    int64_t offset_in = offset;     /* for logging */
 
-    if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)))
-        return ret;
+    for (x = 0; x < mxf->partitions_count; x++) {
+        MXFPartition *p = &mxf->partitions[x];
+
+        if (p->body_sid != body_sid)
+            continue;
+
+        if (offset < p->essence_length || !p->essence_length) {
+            *offset_out = p->essence_offset + offset;
+            return 0;
+        }
+
+        offset -= p->essence_length;
+    }
 
-    for (j = 0; j < nb_sorted_segments; j++) {
-        int n_delta = i;
-        int duration, sample_duration = 1, last_sample_size = 0;
-        int64_t segment_size;
-        MXFIndexTableSegment *tableseg = sorted_segments[j];
+    av_log(mxf->fc, AV_LOG_ERROR, "failed to find absolute offset of %lx in BodySID %i - partial file?\n",
+           offset_in, body_sid);
 
-        /* reset accumulated_offset on BodySID change */
-        if (j > 0 && tableseg->body_sid != sorted_segments[j-1]->body_sid)
-            accumulated_offset = 0;
+    return AVERROR_INVALIDDATA;
+}
 
-        /* HACK: How to correctly link between streams and slices? */
-        if (i < mxf->system_item + st->index)
-            n_delta++;
-        if (n_delta >= tableseg->nb_delta_entries && st->index != 0)
+/**
+ * Returns the end position of the essence container with given BodySID, or zero if unknown
+ */
+static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
+{
+    int x;
+    int64_t ret = 0;
+
+    for (x = 0; x < mxf->partitions_count; x++) {
+        MXFPartition *p = &mxf->partitions[x];
+
+        if (p->body_sid != body_sid)
             continue;
-        duration = tableseg->index_duration > 0 ? tableseg->index_duration :
-            st->duration - st->nb_index_entries;
-        segment_size = tableseg->edit_unit_byte_count * duration;
-        /* check small EditUnitByteCount for audio */
-        if (tableseg->edit_unit_byte_count && tableseg->edit_unit_byte_count < 32
-            && !tableseg->index_duration) {
-            /* duration might be prime relative to the new sample_duration,
-             * which means we need to handle the last frame differently */
-            sample_duration = 8192;
-            last_sample_size = (duration % sample_duration) * tableseg->edit_unit_byte_count;
-            tableseg->edit_unit_byte_count *= sample_duration;
-            duration /= sample_duration;
-            if (last_sample_size) duration++;
-        }
 
-        for (k = 0; k < duration; k++) {
-            int64_t pos;
-            int size, flags = 0;
-
-            if (k < tableseg->nb_index_entries) {
-                pos = tableseg->stream_offset_entries[k];
-                if (n_delta < tableseg->nb_delta_entries) {
-                    if (n_delta < tableseg->nb_delta_entries - 1) {
-                        size =
-                            tableseg->slice_offset_entries[k][tableseg->slice[n_delta+1]-1] +
-                            tableseg->element_delta[n_delta+1] -
-                            tableseg->element_delta[n_delta];
-                        if (tableseg->slice[n_delta] > 0)
-                            size -= tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
-                    } else if (k < duration - 1) {
-                        size = tableseg->stream_offset_entries[k+1] -
-                            tableseg->stream_offset_entries[k] -
-                            tableseg->slice_offset_entries[k][tableseg->slice[tableseg->nb_delta_entries-1]-1] -
-                            tableseg->element_delta[tableseg->nb_delta_entries-1];
-                    } else
-                        size = 0;
-                    if (tableseg->slice[n_delta] > 0)
-                        pos += tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
-                    pos += tableseg->element_delta[n_delta];
-                } else
-                    size = 0;
-                flags = !(tableseg->flag_entries[k] & 0x30) ? AVINDEX_KEYFRAME : 0;
-            } else {
-                pos = (int64_t)k * tableseg->edit_unit_byte_count + accumulated_offset;
-                if (n_delta < tableseg->nb_delta_entries - 1)
-                    size = tableseg->element_delta[n_delta+1] - tableseg->element_delta[n_delta];
-                else {
-                    /* use smaller size for last sample if we should */
-                    if (last_sample_size && k == duration - 1)
-                        size = last_sample_size;
-                    else
-                        size = tableseg->edit_unit_byte_count;
-                    if (tableseg->nb_delta_entries)
-                        size -= tableseg->element_delta[tableseg->nb_delta_entries-1];
+        if (!p->essence_length)
+            return 0;
+
+        ret = p->essence_offset + p->essence_length;
+    }
+
+    return ret;
+}
+
+/* EditUnit -> absolute offset */
+static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, int64_t *edit_unit_out, int64_t *offset_out, int nag)
+{
+    int i;
+    int offset_temp = 0;
+
+    for (i = 0; i < index_table->nb_segments; i++) {
+        MXFIndexTableSegment *s = index_table->segments[i];
+
+        edit_unit = FFMAX(edit_unit, s->index_start_position);  /* clamp if trying to seek before start */
+
+        if (edit_unit < s->index_start_position + s->index_duration) {
+            int64_t index = edit_unit - s->index_start_position;
+
+            if (s->edit_unit_byte_count)
+                offset_temp += s->edit_unit_byte_count * index;
+            else if (s->nb_index_entries) {
+                if (s->nb_index_entries == 2 * s->index_duration + 1)
+                    index *= 2;     /* Avid index */
+
+                if (index < 0 || index > s->nb_index_entries) {
+                    av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
+                           index_table->index_sid, s->index_start_position);
+                    return AVERROR_INVALIDDATA;
                 }
-                if (n_delta < tableseg->nb_delta_entries)
-                    pos += tableseg->element_delta[n_delta];
-                flags = AVINDEX_KEYFRAME;
+
+                offset_temp = s->stream_offset_entries[index];
+            } else {
+                av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
+                       index_table->index_sid, s->index_start_position);
+                return AVERROR_INVALIDDATA;
             }
 
-            if (k > 0 && pos < mxf->first_essence_length && accumulated_offset == 0)
-                pos += mxf->first_essence_kl_length;
+            if (edit_unit_out)
+                *edit_unit_out = edit_unit;
+
+            return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out);
+        } else {
+            /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
+            offset_temp += s->edit_unit_byte_count * s->index_duration;
+        }
+    }
+
+    if (nag)
+        av_log(mxf->fc, AV_LOG_ERROR, "failed to map EditUnit %"PRId64" in IndexSID %i to an offset\n", edit_unit, index_table->index_sid);
+
+    return AVERROR_INVALIDDATA;
+}
+
+static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
+{
+    int i, j, x;
+    int8_t max_temporal_offset = -128;
 
-            pos += mxf->essence_offset;
+    /* first compute how many entries we have */
+    for (i = 0; i < index_table->nb_segments; i++) {
+        MXFIndexTableSegment *s = index_table->segments[i];
 
-            av_dlog(mxf->fc, "Stream %d IndexEntry %d n_Delta %d Offset %"PRIx64" Timestamp %"PRId64"\n",
-                    st->index, st->nb_index_entries, n_delta, pos, sample_duration * st->nb_index_entries);
+        if (!s->nb_index_entries)
+            return 0;                               /* no TemporalOffsets */
 
-            if ((ret = av_add_index_entry(st, pos, sample_duration * st->nb_index_entries, size, 0, flags)) < 0)
-                return ret;
+        index_table->nb_ptses += s->index_duration;
+    }
+
+    /* paranoid check */
+    if (index_table->nb_ptses <= 0)
+        return 0;
+
+    if (!(index_table->ptses      = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
+        !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry)))) {
+        av_freep(&index_table->ptses);
+        return AVERROR(ENOMEM);
+    }
+
+    /* we may have a few bad TemporalOffsets
+     * make sure the corresponding PTSes don't have the bogus value 0 */
+    for (x = 0; x < index_table->nb_ptses; x++)
+        index_table->ptses[x] = AV_NOPTS_VALUE;
+
+    /**
+     * We have this:
+     *
+     * x  TemporalOffset
+     * 0:  0
+     * 1:  1
+     * 2:  1
+     * 3: -2
+     * 4:  1
+     * 5:  1
+     * 6: -2
+     *
+     * We want to transform it into this:
+     *
+     * x  DTS PTS
+     * 0: -1   0
+     * 1:  0   3
+     * 2:  1   1
+     * 3:  2   2
+     * 4:  3   6
+     * 5:  4   4
+     * 6:  5   5
+     *
+     * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
+     * then settings mxf->first_dts = -max(TemporalOffset[x]).
+     * The latter makes DTS <= PTS.
+     */
+    for (i = x = 0; i < index_table->nb_segments; i++) {
+        MXFIndexTableSegment *s = index_table->segments[i];
+        int index_delta = 1;
+        int n = s->nb_index_entries;
+
+        if (s->nb_index_entries == 2 * s->index_duration + 1) {
+            index_delta = 2;    /* Avid index */
+
+            /* ignore the last entry - it's the size of the essence container */
+            n--;
+        }
+
+        for (j = 0; j < n; j += index_delta, x++) {
+            int offset = s->temporal_offset_entries[j] / index_delta;
+            int index  = x + offset;
+
+            if (x >= index_table->nb_ptses) {
+                av_log(mxf->fc, AV_LOG_ERROR, "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
+                       s->nb_index_entries, s->index_duration);
+                break;
+            }
+
+            index_table->fake_index[x].timestamp = x;
+            index_table->fake_index[x].flags = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
+
+            if (index < 0 || index >= index_table->nb_ptses) {
+                av_log(mxf->fc, AV_LOG_ERROR,
+                       "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
+                       x, offset, index);
+                continue;
+            }
+
+            index_table->ptses[index] = x;
+            max_temporal_offset = FFMAX(max_temporal_offset, offset);
         }
-        accumulated_offset += segment_size;
     }
 
-    av_free(sorted_segments);
+    index_table->first_dts = -max_temporal_offset;
 
     return 0;
 }
 
+/**
+ * Sorts and collects index table segments into index tables.
+ * Also computes PTSes if possible.
+ */
+static int mxf_compute_index_tables(MXFContext *mxf)
+{
+    int i, j, k, ret, nb_sorted_segments;
+    MXFIndexTableSegment **sorted_segments = NULL;
+
+    if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
+        nb_sorted_segments <= 0) {
+        av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
+        return 0;
+    }
+
+    /* sanity check and count unique BodySIDs/IndexSIDs */
+    for (i = 0; i < nb_sorted_segments; i++) {
+        if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
+            mxf->nb_index_tables++;
+        else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
+            av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
+            ret = AVERROR_INVALIDDATA;
+            goto finish_decoding_index;
+        }
+    }
+
+    if (!(mxf->index_tables = av_calloc(mxf->nb_index_tables, sizeof(MXFIndexTable)))) {
+        av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
+        ret = AVERROR(ENOMEM);
+        goto finish_decoding_index;
+    }
+
+    /* distribute sorted segments to index tables */
+    for (i = j = 0; i < nb_sorted_segments; i++) {
+        if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
+            /* next IndexSID */
+            j++;
+        }
+
+        mxf->index_tables[j].nb_segments++;
+    }
+
+    for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
+        MXFIndexTable *t = &mxf->index_tables[j];
+
+        if (!(t->segments = av_calloc(t->nb_segments, sizeof(MXFIndexTableSegment*)))) {
+            av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment pointer array\n");
+            ret = AVERROR(ENOMEM);
+            goto finish_decoding_index;
+        }
+
+        if (sorted_segments[i]->index_start_position)
+            av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
+                   sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
+
+        memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
+        t->index_sid = sorted_segments[i]->index_sid;
+        t->body_sid = sorted_segments[i]->body_sid;
+
+        if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
+            goto finish_decoding_index;
+
+        /* fix zero IndexDurations */
+        for (k = 0; k < t->nb_segments; k++) {
+            if (t->segments[k]->index_duration)
+                continue;
+
+            if (t->nb_segments > 1)
+                av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
+                       t->index_sid, k);
+
+            if (mxf->fc->nb_streams <= 0) {
+                av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
+                break;
+            }
+
+            /* assume the first stream's duration is reasonable
+             * leave index_duration = 0 on further segments in case we have any (unlikely)
+             */
+            t->segments[k]->index_duration = mxf->fc->streams[0]->duration;
+            break;
+        }
+    }
+
+    ret = 0;
+finish_decoding_index:
+    av_free(sorted_segments);
+    return ret;
+}
+
 static int mxf_parse_structural_metadata(MXFContext *mxf)
 {
     MXFPackage *material_package = NULL;
@@ -1095,13 +1257,14 @@ static int mxf_parse_structural_metadata(MXFContext *mxf)
                 }
             }
             if (!source_package) {
-                av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source package found\n", material_track->track_id);
+                av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
                 break;
             }
             for (k = 0; k < source_package->tracks_count; k++) {
                 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
-                    return -1;
+                    ret = -1;
+                    goto fail_and_free;
                 }
                 if (temp_track->track_id == component->source_track_id) {
                     source_track = temp_track;
@@ -1116,10 +1279,24 @@ static int mxf_parse_structural_metadata(MXFContext *mxf)
         if (!source_track)
             continue;
 
+        if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
+            av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
+            ret = -1;
+            goto fail_and_free;
+        }
+
+        /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
+         * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
+        if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
+            av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
+            continue;
+        }
+
         st = avformat_new_stream(mxf->fc, NULL);
         if (!st) {
             av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
-            return -1;
+            ret = AVERROR(ENOMEM);
+            goto fail_and_free;
         }
         st->id = source_track->track_id;
         st->priv_data = source_track;
@@ -1129,11 +1306,6 @@ static int mxf_parse_structural_metadata(MXFContext *mxf)
         st->start_time = component->start_position;
         avpriv_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
 
-        if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
-            av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
-            return -1;
-        }
-
         PRINT_KEY(mxf->fc, "data definition   ul", source_track->sequence->data_definition_ul);
         codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
         st->codec->codec_type = codec_ul->id;
@@ -1175,6 +1347,7 @@ static int mxf_parse_structural_metadata(MXFContext *mxf)
                 }
             }
         }
+
         /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
         codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
         st->codec->codec_id = codec_ul->id;
@@ -1183,7 +1356,7 @@ static int mxf_parse_structural_metadata(MXFContext *mxf)
             st->codec->extradata_size = descriptor->extradata_size;
         }
         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
-            container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
+            container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
             if (st->codec->codec_id == CODEC_ID_NONE)
                 st->codec->codec_id = container_ul->id;
             st->codec->width = descriptor->width;
@@ -1192,7 +1365,7 @@ static int mxf_parse_structural_metadata(MXFContext *mxf)
                 st->codec->pix_fmt = descriptor->pix_fmt;
             st->need_parsing = AVSTREAM_PARSE_HEADERS;
         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
-            container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
+            container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
             if (st->codec->codec_id == CODEC_ID_NONE)
                 st->codec->codec_id = container_ul->id;
             st->codec->channels = descriptor->channels;
@@ -1214,14 +1387,14 @@ static int mxf_parse_structural_metadata(MXFContext *mxf)
             }
         }
         if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
-            av_log(mxf->fc, AV_LOG_WARNING, "only frame wrapped mappings are correctly supported\n");
-            st->need_parsing = AVSTREAM_PARSE_FULL;
+            /* TODO: decode timestamps */
+            st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
         }
-
-        if ((ret = mxf_parse_index(mxf, i, st)))
-            return ret;
     }
-    return 0;
+
+    ret = 0;
+fail_and_free:
+    return ret;
 }
 
 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
@@ -1287,7 +1460,7 @@ static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadF
         }
         if (ctx_size && tag == 0x3C0A)
             avio_read(pb, ctx->uid, 16);
-        else if (read_child(ctx, pb, tag, size, uid) < 0)
+        else if (read_child(ctx, pb, tag, size, uid, -1) < 0)
             return -1;
 
         avio_seek(pb, next, SEEK_SET);
@@ -1296,10 +1469,130 @@ static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadF
     return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
 }
 
+/**
+ * Seeks to the previous partition, if possible
+ * @return <= 0 if we should stop parsing, > 0 if we should keep going
+ */
+static int mxf_seek_to_previous_partition(MXFContext *mxf)
+{
+    AVIOContext *pb = mxf->fc->pb;
+
+    if (!mxf->current_partition ||
+        mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
+        return 0;   /* we've parsed all partitions */
+
+    /* seek to previous partition */
+    avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
+    mxf->current_partition = NULL;
+
+    av_dlog(mxf->fc, "seeking to previous partition\n");
+
+    return 1;
+}
+
+/**
+ * Called when essence is encountered
+ * @return <= 0 if we should stop parsing, > 0 if we should keep going
+ */
+static int mxf_parse_handle_essence(MXFContext *mxf)
+{
+    AVIOContext *pb = mxf->fc->pb;
+    int64_t ret;
+
+    if (!mxf->current_partition) {
+        av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to PartitionPack\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (mxf->parsing_backward) {
+        return mxf_seek_to_previous_partition(mxf);
+    } else {
+        if (!mxf->footer_partition) {
+            av_dlog(mxf->fc, "no footer\n");
+            return 0;
+        }
+
+        av_dlog(mxf->fc, "seeking to footer\n");
+
+        /* remember where we were so we don't end up seeking further back than this */
+        mxf->last_forward_tell = avio_tell(pb);
+
+        if (!pb->seekable) {
+            av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing footer\n");
+            return -1;
+        }
+
+        /* seek to footer partition and parse backward */
+        if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
+            av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to footer @ 0x%"PRIx64" (%"PRId64") - partial file?\n",
+                   mxf->run_in + mxf->footer_partition, ret);
+            return ret;
+        }
+
+        mxf->current_partition = NULL;
+        mxf->parsing_backward = 1;
+    }
+
+    return 1;
+}
+
+/**
+ * Called when the next partition or EOF is encountered
+ * @return <= 0 if we should stop parsing, > 0 if we should keep going
+ */
+static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
+{
+    return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
+}
+
+/**
+ * Figures out the proper offset and length of the essence container in each partition
+ */
+static void mxf_compute_essence_containers(MXFContext *mxf)
+{
+    int x;
+
+    /* everything is already correct */
+    if (mxf->op == OPAtom)
+        return;
+
+    for (x = 0; x < mxf->partitions_count; x++) {
+        MXFPartition *p = &mxf->partitions[x];
+
+        if (!p->body_sid)
+            continue;       /* BodySID == 0 -> no essence */
+
+        if (x >= mxf->partitions_count - 1)
+            break;          /* last partition - can't compute length (and we don't need to) */
+
+        /* essence container spans to the next partition */
+        p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
+
+        if (p->essence_length < 0) {
+            /* next ThisPartition < essence_offset */
+            p->essence_length = 0;
+            av_log(mxf->fc, AV_LOG_ERROR, "partition %i: bad ThisPartition = %lx\n",
+                   x+1, mxf->partitions[x+1].this_partition);
+        }
+    }
+}
+
+static int64_t round_to_kag(int64_t position, int kag_size)
+{
+    /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
+    /* NOTE: kag_size may be any integer between 1 - 2^10 */
+    int64_t ret = (position / kag_size) * kag_size;
+    return ret == position ? ret : ret + kag_size;
+}
+
 static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     MXFContext *mxf = s->priv_data;
     KLVPacket klv;
+    int64_t essence_offset = 0;
+    int ret;
+
+    mxf->last_forward_tell = INT64_MAX;
 
     if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
         av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
@@ -1307,23 +1600,61 @@ static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
     }
     avio_seek(s->pb, -14, SEEK_CUR);
     mxf->fc = s;
+    mxf->run_in = avio_tell(s->pb);
+
     while (!url_feof(s->pb)) {
         const MXFMetadataReadTableEntry *metadata;
 
-        if (klv_read_packet(&klv, s->pb) < 0)
-            return -1;
+        if (klv_read_packet(&klv, s->pb) < 0) {
+            /* EOF - seek to previous partition or stop */
+            if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
+                break;
+            else
+                continue;
+        }
+
         PRINT_KEY(s, "read header", klv.key);
         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
-            IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
-            /* FIXME avoid seek */
-            avio_seek(s->pb, klv.offset, SEEK_SET);
-            break;
-        }
-        if (IS_KLV_KEY(klv.key, mxf_system_item_key)) {
-            mxf->system_item = 1;
-            avio_skip(s->pb, klv.length);
+            IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
+            IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||
+            IS_KLV_KEY(klv.key, mxf_system_item_key)) {
+            if (!mxf->current_partition->essence_offset) {
+                /* for OP1a we compute essence_offset
+                 * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
+                 * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
+                 *       for OPAtom we still need the actual essence_offset though (the KL's length can vary)
+                 */
+                int64_t op1a_essence_offset =
+                    round_to_kag(mxf->current_partition->this_partition +
+                                 mxf->current_partition->pack_length,       mxf->current_partition->kag_size) +
+                    round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
+                    round_to_kag(mxf->current_partition->index_byte_count,  mxf->current_partition->kag_size);
+
+                if (mxf->op == OPAtom) {
+                    /* point essence_offset to the actual data
+                    * OPAtom has all the essence in one big KLV
+                    */
+                    mxf->current_partition->essence_offset = avio_tell(s->pb);
+                    mxf->current_partition->essence_length = klv.length;
+                } else {
+                    /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf)  */
+                    mxf->current_partition->essence_offset = op1a_essence_offset;
+                }
+            }
+
+            if (!essence_offset)
+                essence_offset = klv.offset;
+
+            /* seek to footer, previous partition or stop */
+            if (mxf_parse_handle_essence(mxf) <= 0)
+                break;
             continue;
+        } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
+                   klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
+            /* next partition pack - keep going, seek to previous partition or stop */
+            if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
+                break;
         }
 
         for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
@@ -1333,7 +1664,7 @@ static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
                     res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
                 } else {
                     uint64_t next = avio_tell(s->pb) + klv.length;
-                    res = metadata->read(mxf, s->pb, 0, 0, klv.key);
+                    res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
                     avio_seek(s->pb, next, SEEK_SET);
                 }
                 if (res < 0) {
@@ -1346,7 +1677,162 @@ static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
         if (!metadata->read)
             avio_skip(s->pb, klv.length);
     }
-    return mxf_parse_structural_metadata(mxf);
+    /* FIXME avoid seek */
+    if (!essence_offset)  {
+        av_log(s, AV_LOG_ERROR, "no essence\n");
+        return AVERROR_INVALIDDATA;
+    }
+    avio_seek(s->pb, essence_offset, SEEK_SET);
+
+    mxf_compute_essence_containers(mxf);
+
+    /* we need to do this before computing the index tables
+     * to be able to fill in zero IndexDurations with st->duration */
+    if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
+        return ret;
+
+    if ((ret = mxf_compute_index_tables(mxf)) < 0)
+        return ret;
+
+    if (mxf->nb_index_tables > 1) {
+        /* TODO: look up which IndexSID to use via EssenceContainerData */
+        av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
+               mxf->nb_index_tables, mxf->index_tables[0].index_sid);
+    } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
+        av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    return 0;
+}
+
+/**
+ * Computes DTS and PTS for the given video packet based on its offset.
+ */
+static void mxf_packet_timestamps(MXFContext *mxf, AVPacket *pkt)
+{
+    int64_t next_ofs;
+    MXFIndexTable *t = &mxf->index_tables[0];
+
+    /* find mxf->current_edit_unit so that the next edit unit starts ahead of pkt->pos */
+    for (;;) {
+        if (mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1, NULL, &next_ofs, 0) < 0)
+            break;
+
+        if (next_ofs > pkt->pos)
+            break;
+
+        mxf->current_edit_unit++;
+    }
+
+    if (mxf->current_edit_unit >= t->nb_ptses)
+        return;
+
+    pkt->dts = mxf->current_edit_unit + t->first_dts;
+    pkt->pts = t->ptses[mxf->current_edit_unit];
+}
+
+static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
+{
+    KLVPacket klv;
+
+    while (!url_feof(s->pb)) {
+        if (klv_read_packet(&klv, s->pb) < 0)
+            return -1;
+        PRINT_KEY(s, "read packet", klv.key);
+        av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
+        if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
+            int res = mxf_decrypt_triplet(s, pkt, &klv);
+            if (res < 0) {
+                av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
+                return -1;
+            }
+            return 0;
+        }
+        if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
+            IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
+            int index = mxf_get_stream_index(s, &klv);
+            if (index < 0) {
+                av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
+                goto skip;
+            }
+            if (s->streams[index]->discard == AVDISCARD_ALL)
+                goto skip;
+            /* check for 8 channels AES3 element */
+            if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
+                if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
+                    av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
+                    return -1;
+                }
+            } else {
+                int ret = av_get_packet(s->pb, pkt, klv.length);
+                if (ret < 0)
+                    return ret;
+            }
+            pkt->stream_index = index;
+            pkt->pos = klv.offset;
+
+            if (s->streams[index]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
+                mxf_packet_timestamps(s->priv_data, pkt);   /* offset -> EditUnit -> DTS/PTS */
+
+            return 0;
+        } else
+        skip:
+            avio_skip(s->pb, klv.length);
+    }
+    return AVERROR_EOF;
+}
+
+static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    MXFContext *mxf = s->priv_data;
+    int ret, size;
+    int64_t ret64, pos, next_pos;
+    AVStream *st;
+    MXFIndexTable *t;
+
+    if (mxf->op != OPAtom)
+        return mxf_read_packet_old(s, pkt);
+
+    /* OPAtom - clip wrapped demuxing */
+    st = s->streams[0];
+    t = &mxf->index_tables[0];
+
+    if (mxf->current_edit_unit >= st->duration)
+        return AVERROR_EOF;
+
+    if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit, NULL, &pos, 1)) < 0)
+        return ret;
+
+    /* compute size by finding the next edit unit or the end of the essence container
+     * not pretty, but it works */
+    if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1, NULL, &next_pos, 0)) < 0 &&
+        (next_pos = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
+        av_log(s, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    if ((size = next_pos - pos) <= 0) {
+        av_log(s, AV_LOG_ERROR, "bad size: %i\n", size);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if ((ret64 = avio_seek(s->pb, pos, SEEK_SET)) < 0)
+        return ret64;
+
+        if ((ret = av_get_packet(s->pb, pkt, size)) != size)
+            return ret < 0 ? ret : AVERROR_EOF;
+
+    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses &&
+        mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) {
+        pkt->dts = mxf->current_edit_unit + t->first_dts;
+        pkt->pts = t->ptses[mxf->current_edit_unit];
+    }
+
+    pkt->stream_index = 0;
+    mxf->current_edit_unit++;
+
+    return 0;
 }
 
 static int mxf_read_close(AVFormatContext *s)
@@ -1374,13 +1860,9 @@ static int mxf_read_close(AVFormatContext *s)
             break;
         case IndexTableSegment:
             seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
-            for (j = 0; j < seg->nb_index_entries; j++)
-                av_freep(&seg->slice_offset_entries[j]);
-            av_freep(&seg->slice);
-            av_freep(&seg->element_delta);
+            av_freep(&seg->temporal_offset_entries);
             av_freep(&seg->flag_entries);
             av_freep(&seg->stream_offset_entries);
-            av_freep(&seg->slice_offset_entries);
             break;
         default:
             break;
@@ -1391,6 +1873,13 @@ static int mxf_read_close(AVFormatContext *s)
     av_freep(&mxf->metadata_sets);
     av_freep(&mxf->aesc);
     av_freep(&mxf->local_tags);
+
+    for (i = 0; i < mxf->nb_index_tables; i++) {
+        av_freep(&mxf->index_tables[i].segments);
+        av_freep(&mxf->index_tables[i].fake_index);
+    }
+    av_freep(&mxf->index_tables);
+
     return 0;
 }
 
@@ -1416,7 +1905,12 @@ static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_ti
 {
     AVStream *st = s->streams[stream_index];
     int64_t seconds;
+    MXFContext* mxf = s->priv_data;
+    int64_t seekpos;
+    int ret;
+    MXFIndexTable *t;
 
+    if (mxf->index_tables <= 0) {
     if (!s->bit_rate)
         return -1;
     if (sample_time < 0)
@@ -1425,6 +1919,30 @@ static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_ti
     if (avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET) < 0)
         return -1;
     ff_update_cur_dts(s, st, sample_time);
+    } else {
+        t = &mxf->index_tables[0];
+
+        /* clamp above zero, else ff_index_search_timestamp() returns negative
+         * this also means we allow seeking before the start */
+        sample_time = FFMAX(sample_time, 0);
+
+        if (t->fake_index) {
+            /* behave as if we have a proper index */
+            if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
+                return sample_time;
+        } else {
+            /* no IndexEntryArray (one or more CBR segments)
+             * make sure we don't seek past the end */
+            sample_time = FFMIN(sample_time, st->duration - 1);
+        }
+
+        if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) << 0)
+            return ret;
+
+        av_update_cur_dts(s, st, sample_time);
+        mxf->current_edit_unit = sample_time;
+        avio_seek(s->pb, seekpos, SEEK_SET);
+    }
     return 0;
 }