]> git.sesse.net Git - ffmpeg/blob - libavformat/mxfdec.c
seek-test: use standard format specifiers in snprintf()
[ffmpeg] / libavformat / mxfdec.c
1 /*
2  * MXF demuxer.
3  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /*
23  * References
24  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
25  * SMPTE 377M MXF File Format Specifications
26  * SMPTE 378M Operational Pattern 1a
27  * SMPTE 379M MXF Generic Container
28  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29  * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
30  * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
31  *
32  * Principle
33  * Search for Track numbers which will identify essence element KLV packets.
34  * Search for SourcePackage which define tracks which contains Track numbers.
35  * Material Package contains tracks with reference to SourcePackage tracks.
36  * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
37  * Assign Descriptors to correct Tracks.
38  *
39  * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
40  * Metadata parsing resolves Strong References to objects.
41  *
42  * Simple demuxer, only OP1A supported and some files might not work at all.
43  * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
44  */
45
46 //#define DEBUG
47
48 #include "libavutil/aes.h"
49 #include "libavutil/mathematics.h"
50 #include "libavcodec/bytestream.h"
51 #include "avformat.h"
52 #include "internal.h"
53 #include "mxf.h"
54
55 typedef enum {
56     Header,
57     BodyPartition,
58     Footer
59 } MXFPartitionType;
60
61 typedef enum {
62     OP1a,
63     OP1b,
64     OP1c,
65     OP2a,
66     OP2b,
67     OP2c,
68     OP3a,
69     OP3b,
70     OP3c,
71     OPAtom,
72     OPSONYOpt,  /* FATE sample, violates the spec in places */
73 } MXFOP;
74
75 typedef struct {
76     int closed;
77     int complete;
78     MXFPartitionType type;
79     uint64_t previous_partition;
80     int index_sid;
81     int body_sid;
82     int64_t this_partition;
83     int64_t essence_offset;         /* absolute offset of essence */
84     int64_t essence_length;
85     int32_t kag_size;
86     int64_t header_byte_count;
87     int64_t index_byte_count;
88     int pack_length;
89 } MXFPartition;
90
91 typedef struct {
92     UID uid;
93     enum MXFMetadataSetType type;
94     UID source_container_ul;
95 } MXFCryptoContext;
96
97 typedef struct {
98     UID uid;
99     enum MXFMetadataSetType type;
100     UID source_package_uid;
101     UID data_definition_ul;
102     int64_t duration;
103     int64_t start_position;
104     int source_track_id;
105 } MXFStructuralComponent;
106
107 typedef struct {
108     UID uid;
109     enum MXFMetadataSetType type;
110     UID data_definition_ul;
111     UID *structural_components_refs;
112     int structural_components_count;
113     int64_t duration;
114 } MXFSequence;
115
116 typedef struct {
117     UID uid;
118     enum MXFMetadataSetType type;
119     MXFSequence *sequence; /* mandatory, and only one */
120     UID sequence_ref;
121     int track_id;
122     uint8_t track_number[4];
123     AVRational edit_rate;
124 } MXFTrack;
125
126 typedef struct {
127     UID uid;
128     enum MXFMetadataSetType type;
129     UID essence_container_ul;
130     UID essence_codec_ul;
131     AVRational sample_rate;
132     AVRational aspect_ratio;
133     int width;
134     int height;
135     int channels;
136     int bits_per_sample;
137     UID *sub_descriptors_refs;
138     int sub_descriptors_count;
139     int linked_track_id;
140     uint8_t *extradata;
141     int extradata_size;
142     enum PixelFormat pix_fmt;
143 } MXFDescriptor;
144
145 typedef struct {
146     UID uid;
147     enum MXFMetadataSetType type;
148     int edit_unit_byte_count;
149     int index_sid;
150     int body_sid;
151     int slice_count;
152     AVRational index_edit_rate;
153     uint64_t index_start_position;
154     uint64_t index_duration;
155     int *slice;
156     int *element_delta;
157     int nb_delta_entries;
158     int8_t *temporal_offset_entries;
159     int *flag_entries;
160     uint64_t *stream_offset_entries;
161     uint32_t **slice_offset_entries;
162     int nb_index_entries;
163 } MXFIndexTableSegment;
164
165 typedef struct {
166     UID uid;
167     enum MXFMetadataSetType type;
168     UID package_uid;
169     UID *tracks_refs;
170     int tracks_count;
171     MXFDescriptor *descriptor; /* only one */
172     UID descriptor_ref;
173 } MXFPackage;
174
175 typedef struct {
176     UID uid;
177     enum MXFMetadataSetType type;
178 } MXFMetadataSet;
179
180 typedef struct {
181     MXFPartition *partitions;
182     unsigned partitions_count;
183     MXFOP op;
184     UID *packages_refs;
185     int packages_count;
186     MXFMetadataSet **metadata_sets;
187     int metadata_sets_count;
188     AVFormatContext *fc;
189     struct AVAES *aesc;
190     uint8_t *local_tags;
191     int local_tags_count;
192     uint64_t footer_partition;
193     KLVPacket current_klv_data;
194     int current_klv_index;
195     int run_in;
196     MXFPartition *current_partition;
197     int parsing_backward;
198     int64_t last_forward_tell;
199     int last_forward_partition;
200     int current_edit_unit;
201     int current_stream;
202     int d10;
203     int broken_index;
204 } MXFContext;
205
206 enum MXFWrappingScheme {
207     Frame,
208     Clip,
209 };
210
211 /* NOTE: klv_offset is not set (-1) for local keys */
212 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
213
214 typedef struct {
215     const UID key;
216     MXFMetadataReadFunc *read;
217     int ctx_size;
218     enum MXFMetadataSetType type;
219 } MXFMetadataReadTableEntry;
220
221 /* partial keys to match */
222 static const uint8_t mxf_header_partition_pack_key[]       = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
223 static const uint8_t mxf_essence_element_key[]             = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
224 static const uint8_t mxf_system_item_key[]                 = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
225 static const uint8_t mxf_klv_key[]                         = { 0x06,0x0e,0x2b,0x34 };
226 /* complete keys to match */
227 static const uint8_t mxf_crypto_source_container_ul[]      = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x02,0x02,0x00,0x00,0x00 };
228 static const uint8_t mxf_encrypted_triplet_key[]           = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
229 static const uint8_t mxf_encrypted_essence_container[]     = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
230 static const uint8_t mxf_sony_mpeg4_extradata[]            = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
231
232 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
233
234 static int64_t klv_decode_ber_length(AVIOContext *pb)
235 {
236     uint64_t size = avio_r8(pb);
237     if (size & 0x80) { /* long form */
238         int bytes_num = size & 0x7f;
239         /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
240         if (bytes_num > 8)
241             return -1;
242         size = 0;
243         while (bytes_num--)
244             size = size << 8 | avio_r8(pb);
245     }
246     return size;
247 }
248
249 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
250 {
251     int i, b;
252     for (i = 0; i < size && !url_feof(pb); i++) {
253         b = avio_r8(pb);
254         if (b == key[0])
255             i = 0;
256         else if (b != key[i])
257             i = -1;
258     }
259     return i == size;
260 }
261
262 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
263 {
264     if (!mxf_read_sync(pb, mxf_klv_key, 4))
265         return -1;
266     klv->offset = avio_tell(pb) - 4;
267     memcpy(klv->key, mxf_klv_key, 4);
268     avio_read(pb, klv->key + 4, 12);
269     klv->length = klv_decode_ber_length(pb);
270     return klv->length == -1 ? -1 : 0;
271 }
272
273 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
274 {
275     int i;
276
277     for (i = 0; i < s->nb_streams; i++) {
278         MXFTrack *track = s->streams[i]->priv_data;
279         /* SMPTE 379M 7.3 */
280         if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
281             return i;
282     }
283     /* return 0 if only one stream, for OP Atom files with 0 as track number */
284     return s->nb_streams == 1 ? 0 : -1;
285 }
286
287 /* XXX: use AVBitStreamFilter */
288 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
289 {
290     const uint8_t *buf_ptr, *end_ptr;
291     uint8_t *data_ptr;
292     int i;
293
294     if (length > 61444) /* worst case PAL 1920 samples 8 channels */
295         return -1;
296     length = av_get_packet(pb, pkt, length);
297     if (length < 0)
298         return length;
299     data_ptr = pkt->data;
300     end_ptr = pkt->data + length;
301     buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
302     for (; buf_ptr + st->codec->channels*4 < end_ptr; ) {
303         for (i = 0; i < st->codec->channels; i++) {
304             uint32_t sample = bytestream_get_le32(&buf_ptr);
305             if (st->codec->bits_per_coded_sample == 24)
306                 bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
307             else
308                 bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
309         }
310         buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
311     }
312     av_shrink_packet(pkt, data_ptr - pkt->data);
313     return 0;
314 }
315
316 static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
317 {
318     static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
319     MXFContext *mxf = s->priv_data;
320     AVIOContext *pb = s->pb;
321     int64_t end = avio_tell(pb) + klv->length;
322     int64_t size;
323     uint64_t orig_size;
324     uint64_t plaintext_size;
325     uint8_t ivec[16];
326     uint8_t tmpbuf[16];
327     int index;
328
329     if (!mxf->aesc && s->key && s->keylen == 16) {
330         mxf->aesc = av_malloc(av_aes_size);
331         if (!mxf->aesc)
332             return -1;
333         av_aes_init(mxf->aesc, s->key, 128, 1);
334     }
335     // crypto context
336     avio_skip(pb, klv_decode_ber_length(pb));
337     // plaintext offset
338     klv_decode_ber_length(pb);
339     plaintext_size = avio_rb64(pb);
340     // source klv key
341     klv_decode_ber_length(pb);
342     avio_read(pb, klv->key, 16);
343     if (!IS_KLV_KEY(klv, mxf_essence_element_key))
344         return -1;
345     index = mxf_get_stream_index(s, klv);
346     if (index < 0)
347         return -1;
348     // source size
349     klv_decode_ber_length(pb);
350     orig_size = avio_rb64(pb);
351     if (orig_size < plaintext_size)
352         return -1;
353     // enc. code
354     size = klv_decode_ber_length(pb);
355     if (size < 32 || size - 32 < orig_size)
356         return -1;
357     avio_read(pb, ivec, 16);
358     avio_read(pb, tmpbuf, 16);
359     if (mxf->aesc)
360         av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
361     if (memcmp(tmpbuf, checkv, 16))
362         av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
363     size -= 32;
364     size = av_get_packet(pb, pkt, size);
365     if (size < 0)
366         return size;
367     else if (size < plaintext_size)
368         return AVERROR_INVALIDDATA;
369     size -= plaintext_size;
370     if (mxf->aesc)
371         av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
372                      &pkt->data[plaintext_size], size >> 4, ivec, 1);
373     av_shrink_packet(pkt, orig_size);
374     pkt->stream_index = index;
375     avio_skip(pb, end - avio_tell(pb));
376     return 0;
377 }
378
379 static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
380 {
381     KLVPacket klv;
382
383     while (!url_feof(s->pb)) {
384         if (klv_read_packet(&klv, s->pb) < 0)
385             return -1;
386         PRINT_KEY(s, "read packet", klv.key);
387         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
388         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
389             int res = mxf_decrypt_triplet(s, pkt, &klv);
390             if (res < 0) {
391                 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
392                 return -1;
393             }
394             return 0;
395         }
396         if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
397             int index = mxf_get_stream_index(s, &klv);
398             if (index < 0) {
399                 av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
400                 goto skip;
401             }
402             if (s->streams[index]->discard == AVDISCARD_ALL)
403                 goto skip;
404             /* check for 8 channels AES3 element */
405             if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
406                 if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
407                     av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
408                     return -1;
409                 }
410             } else {
411                 int ret = av_get_packet(s->pb, pkt, klv.length);
412                 if (ret < 0)
413                     return ret;
414             }
415             pkt->stream_index = index;
416             pkt->pos = klv.offset;
417             return 0;
418         } else
419         skip:
420             avio_skip(s->pb, klv.length);
421     }
422     return AVERROR_EOF;
423 }
424
425 static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
426 {
427     MXFContext *mxf = s->priv_data;
428     AVIndexEntry *e;
429     int ret;
430     int64_t ret64;
431     KLVPacket klv;
432     AVStream *st;
433
434     /* TODO: better logic for this?
435      * only files that lack all index segments prior to the essence need this */
436     if (!s->pb->seekable && mxf->op != OPAtom || mxf->d10 || mxf->broken_index)
437         return mxf_read_packet_old(s, pkt);
438
439     if (mxf->current_stream >= s->nb_streams) {
440         mxf->current_edit_unit++;
441         mxf->current_stream = 0;
442     }
443
444     st = s->streams[mxf->current_stream];
445
446     if (mxf->current_edit_unit >= st->nb_index_entries)
447         return AVERROR_EOF;
448
449     e = &st->index_entries[mxf->current_edit_unit];
450
451     if ((ret64 = avio_seek(s->pb, e->pos, SEEK_SET)) < 0)
452         return ret64;
453
454     if (mxf->op == OPAtom) {
455         /* OPAtom - no KL, just essence */
456         if ((ret = av_get_packet(s->pb, pkt, e->size)) != e->size)
457             return ret < 0 ? ret : AVERROR_EOF;
458     } else {
459         /* read KL, read L bytes of essence */
460         if ((ret = klv_read_packet(&klv, s->pb)) < 0)
461             return ret;
462
463         /* untested, but looks OK */
464         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
465             int res = mxf_decrypt_triplet(s, pkt, &klv);
466             if (res < 0) {
467                 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
468                 return -1;
469             }
470             return 0;
471         }
472
473         if ((ret = av_get_packet(s->pb, pkt, klv.length)) != klv.length)
474             return ret < 0 ? ret : AVERROR_EOF;
475
476         pkt->pos = e->pos;
477     }
478
479     pkt->stream_index = mxf->current_stream++;
480
481     return 0;
482 }
483
484 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
485 {
486     MXFContext *mxf = arg;
487     int item_num = avio_rb32(pb);
488     int item_len = avio_rb32(pb);
489
490     if (item_len != 18) {
491         av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");
492         return -1;
493     }
494     if (item_num > UINT_MAX / item_len)
495         return -1;
496     mxf->local_tags_count = item_num;
497     mxf->local_tags = av_malloc(item_num*item_len);
498     if (!mxf->local_tags)
499         return -1;
500     avio_read(pb, mxf->local_tags, item_num*item_len);
501     return 0;
502 }
503
504 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
505 {
506     MXFContext *mxf = arg;
507     MXFPartition *partition;
508     UID op;
509     uint64_t footer_partition;
510
511     if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
512         return AVERROR(ENOMEM);
513
514     mxf->partitions = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
515     if (!mxf->partitions)
516         return AVERROR(ENOMEM);
517
518     if (mxf->parsing_backward) {
519         /* insert the new partition pack in the middle
520          * this makes the entries in mxf->partitions sorted by offset */
521         memmove(&mxf->partitions[mxf->last_forward_partition+1],
522                 &mxf->partitions[mxf->last_forward_partition],
523                 (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
524         partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
525     } else {
526         mxf->last_forward_partition++;
527         partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
528     }
529
530     memset(partition, 0, sizeof(*partition));
531     mxf->partitions_count++;
532     partition->pack_length = avio_tell(pb) - klv_offset + size;
533
534     switch(uid[13]) {
535     case 2:
536         partition->type = Header;
537         break;
538     case 3:
539         partition->type = BodyPartition;
540         break;
541     case 4:
542         partition->type = Footer;
543         break;
544     default:
545         av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
546         return AVERROR_INVALIDDATA;
547     }
548
549     /* consider both footers to be closed (there is only Footer and CompleteFooter) */
550     partition->closed = partition->type == Footer || !(uid[14] & 1);
551     partition->complete = uid[14] > 2;
552     avio_skip(pb, 4);
553     partition->kag_size = avio_rb32(pb);
554     partition->this_partition = avio_rb64(pb);
555     partition->previous_partition = avio_rb64(pb);
556     footer_partition = avio_rb64(pb);
557     partition->header_byte_count = avio_rb64(pb);
558     partition->index_byte_count = avio_rb64(pb);
559     partition->index_sid = avio_rb32(pb);
560     avio_skip(pb, 8);
561     partition->body_sid = avio_rb32(pb);
562     avio_read(pb, op, sizeof(UID));
563
564     /* some files don'thave FooterPartition set in every partition */
565     if (footer_partition) {
566         if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
567             av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %li != %li\n",
568                    mxf->footer_partition, footer_partition);
569         } else {
570             mxf->footer_partition = footer_partition;
571         }
572     }
573
574     av_dlog(mxf->fc, "PartitionPack: ThisPartition = 0x%lx, PreviousPartition = 0x%lx, "
575             "FooterPartition = 0x%lx, IndexSID = %i, BodySID = %i\n",
576             partition->this_partition,
577             partition->previous_partition, footer_partition,
578             partition->index_sid, partition->body_sid);
579
580     if      (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
581     else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
582     else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
583     else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
584     else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
585     else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
586     else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
587     else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
588     else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
589     else if (op[12] == 0x10)             mxf->op = OPAtom;
590     else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
591     else {
592         av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
593         mxf->op = OP1a;
594     }
595
596     if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
597         av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %i - guessing ", partition->kag_size);
598
599         if (mxf->op == OPSONYOpt)
600             partition->kag_size = 512;
601         else
602             partition->kag_size = 1;
603
604         av_log(mxf->fc, AV_LOG_WARNING, "%i\n", partition->kag_size);
605     }
606
607     return 0;
608 }
609
610 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
611 {
612     if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
613         return AVERROR(ENOMEM);
614     mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
615     if (!mxf->metadata_sets)
616         return -1;
617     mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
618     mxf->metadata_sets_count++;
619     return 0;
620 }
621
622 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
623 {
624     MXFCryptoContext *cryptocontext = arg;
625     if (size != 16)
626         return -1;
627     if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
628         avio_read(pb, cryptocontext->source_container_ul, 16);
629     return 0;
630 }
631
632 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
633 {
634     MXFContext *mxf = arg;
635     switch (tag) {
636     case 0x1901:
637         mxf->packages_count = avio_rb32(pb);
638         if (mxf->packages_count >= UINT_MAX / sizeof(UID))
639             return -1;
640         mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
641         if (!mxf->packages_refs)
642             return -1;
643         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
644         avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
645         break;
646     }
647     return 0;
648 }
649
650 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
651 {
652     MXFStructuralComponent *source_clip = arg;
653     switch(tag) {
654     case 0x0202:
655         source_clip->duration = avio_rb64(pb);
656         break;
657     case 0x1201:
658         source_clip->start_position = avio_rb64(pb);
659         break;
660     case 0x1101:
661         /* UMID, only get last 16 bytes */
662         avio_skip(pb, 16);
663         avio_read(pb, source_clip->source_package_uid, 16);
664         break;
665     case 0x1102:
666         source_clip->source_track_id = avio_rb32(pb);
667         break;
668     }
669     return 0;
670 }
671
672 static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
673 {
674     MXFPackage *package = arg;
675     switch(tag) {
676     case 0x4403:
677         package->tracks_count = avio_rb32(pb);
678         if (package->tracks_count >= UINT_MAX / sizeof(UID))
679             return -1;
680         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
681         if (!package->tracks_refs)
682             return -1;
683         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
684         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
685         break;
686     }
687     return 0;
688 }
689
690 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
691 {
692     MXFTrack *track = arg;
693     switch(tag) {
694     case 0x4801:
695         track->track_id = avio_rb32(pb);
696         break;
697     case 0x4804:
698         avio_read(pb, track->track_number, 4);
699         break;
700     case 0x4B01:
701         track->edit_rate.den = avio_rb32(pb);
702         track->edit_rate.num = avio_rb32(pb);
703         break;
704     case 0x4803:
705         avio_read(pb, track->sequence_ref, 16);
706         break;
707     }
708     return 0;
709 }
710
711 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
712 {
713     MXFSequence *sequence = arg;
714     switch(tag) {
715     case 0x0202:
716         sequence->duration = avio_rb64(pb);
717         break;
718     case 0x0201:
719         avio_read(pb, sequence->data_definition_ul, 16);
720         break;
721     case 0x1001:
722         sequence->structural_components_count = avio_rb32(pb);
723         if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
724             return -1;
725         sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
726         if (!sequence->structural_components_refs)
727             return -1;
728         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
729         avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
730         break;
731     }
732     return 0;
733 }
734
735 static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
736 {
737     MXFPackage *package = arg;
738     switch(tag) {
739     case 0x4403:
740         package->tracks_count = avio_rb32(pb);
741         if (package->tracks_count >= UINT_MAX / sizeof(UID))
742             return -1;
743         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
744         if (!package->tracks_refs)
745             return -1;
746         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
747         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
748         break;
749     case 0x4401:
750         /* UMID, only get last 16 bytes */
751         avio_skip(pb, 16);
752         avio_read(pb, package->package_uid, 16);
753         break;
754     case 0x4701:
755         avio_read(pb, package->descriptor_ref, 16);
756         break;
757     }
758     return 0;
759 }
760
761 static int mxf_read_delta_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
762 {
763     int i, length;
764
765     segment->nb_delta_entries = avio_rb32(pb);
766     length = avio_rb32(pb);
767
768     if (!(segment->slice         = av_calloc(segment->nb_delta_entries, sizeof(*segment->slice))) ||
769         !(segment->element_delta = av_calloc(segment->nb_delta_entries, sizeof(*segment->element_delta))))
770         return AVERROR(ENOMEM);
771
772     for (i = 0; i < segment->nb_delta_entries; i++) {
773         avio_r8(pb);    /* PosTableIndex */
774         segment->slice[i] = avio_r8(pb);
775         segment->element_delta[i] = avio_rb32(pb);
776     }
777     return 0;
778 }
779
780 static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
781 {
782     int i, j, length;
783
784     segment->nb_index_entries = avio_rb32(pb);
785     length = avio_rb32(pb);
786
787     if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
788         !(segment->flag_entries          = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
789         !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
790         return AVERROR(ENOMEM);
791
792     if (segment->slice_count &&
793         !(segment->slice_offset_entries  = av_calloc(segment->nb_index_entries, sizeof(*segment->slice_offset_entries))))
794         return AVERROR(ENOMEM);
795
796     for (i = 0; i < segment->nb_index_entries; i++) {
797         segment->temporal_offset_entries[i] = avio_r8(pb);
798         avio_r8(pb);                                        /* KeyFrameOffset */
799         segment->flag_entries[i] = avio_r8(pb);
800         segment->stream_offset_entries[i] = avio_rb64(pb);
801         if (segment->slice_count) {
802             if (!(segment->slice_offset_entries[i] = av_calloc(segment->slice_count, sizeof(**segment->slice_offset_entries))))
803                 return AVERROR(ENOMEM);
804
805             for (j = 0; j < segment->slice_count; j++)
806                 segment->slice_offset_entries[i][j] = avio_rb32(pb);
807         }
808
809         avio_skip(pb, length - 11 - 4 * segment->slice_count);
810     }
811     return 0;
812 }
813
814 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
815 {
816     MXFIndexTableSegment *segment = arg;
817     switch(tag) {
818     case 0x3F05:
819         segment->edit_unit_byte_count = avio_rb32(pb);
820         av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
821         break;
822     case 0x3F06:
823         segment->index_sid = avio_rb32(pb);
824         av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
825         break;
826     case 0x3F07:
827         segment->body_sid = avio_rb32(pb);
828         av_dlog(NULL, "BodySID %d\n", segment->body_sid);
829         break;
830     case 0x3F08:
831         segment->slice_count = avio_r8(pb);
832         av_dlog(NULL, "SliceCount %d\n", segment->slice_count);
833         break;
834     case 0x3F09:
835         av_dlog(NULL, "DeltaEntryArray found\n");
836         return mxf_read_delta_entry_array(pb, segment);
837     case 0x3F0A:
838         av_dlog(NULL, "IndexEntryArray found\n");
839         return mxf_read_index_entry_array(pb, segment);
840     case 0x3F0B:
841         segment->index_edit_rate.num = avio_rb32(pb);
842         segment->index_edit_rate.den = avio_rb32(pb);
843         av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
844                 segment->index_edit_rate.den);
845         break;
846     case 0x3F0C:
847         segment->index_start_position = avio_rb64(pb);
848         av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
849         break;
850     case 0x3F0D:
851         segment->index_duration = avio_rb64(pb);
852         av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
853         break;
854     }
855     return 0;
856 }
857
858 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
859 {
860     int code, value, ofs = 0;
861     char layout[16] = {0};
862
863     do {
864         code = avio_r8(pb);
865         value = avio_r8(pb);
866         av_dlog(NULL, "pixel layout: code %#x\n", code);
867
868         if (ofs < 16) {
869             layout[ofs++] = code;
870             layout[ofs++] = value;
871         }
872     } while (code != 0); /* SMPTE 377M E.2.46 */
873
874     ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
875 }
876
877 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
878 {
879     MXFDescriptor *descriptor = arg;
880     switch(tag) {
881     case 0x3F01:
882         descriptor->sub_descriptors_count = avio_rb32(pb);
883         if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
884             return -1;
885         descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
886         if (!descriptor->sub_descriptors_refs)
887             return -1;
888         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
889         avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
890         break;
891     case 0x3004:
892         avio_read(pb, descriptor->essence_container_ul, 16);
893         break;
894     case 0x3006:
895         descriptor->linked_track_id = avio_rb32(pb);
896         break;
897     case 0x3201: /* PictureEssenceCoding */
898         avio_read(pb, descriptor->essence_codec_ul, 16);
899         break;
900     case 0x3203:
901         descriptor->width = avio_rb32(pb);
902         break;
903     case 0x3202:
904         descriptor->height = avio_rb32(pb);
905         break;
906     case 0x320E:
907         descriptor->aspect_ratio.num = avio_rb32(pb);
908         descriptor->aspect_ratio.den = avio_rb32(pb);
909         break;
910     case 0x3D03:
911         descriptor->sample_rate.num = avio_rb32(pb);
912         descriptor->sample_rate.den = avio_rb32(pb);
913         break;
914     case 0x3D06: /* SoundEssenceCompression */
915         avio_read(pb, descriptor->essence_codec_ul, 16);
916         break;
917     case 0x3D07:
918         descriptor->channels = avio_rb32(pb);
919         break;
920     case 0x3D01:
921         descriptor->bits_per_sample = avio_rb32(pb);
922         break;
923     case 0x3401:
924         mxf_read_pixel_layout(pb, descriptor);
925         break;
926     default:
927         /* Private uid used by SONY C0023S01.mxf */
928         if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
929             descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
930             if (!descriptor->extradata)
931                 return -1;
932             descriptor->extradata_size = size;
933             avio_read(pb, descriptor->extradata, size);
934         }
935         break;
936     }
937     return 0;
938 }
939
940 /*
941  * Match an uid independently of the version byte and up to len common bytes
942  * Returns: boolean
943  */
944 static int mxf_match_uid(const UID key, const UID uid, int len)
945 {
946     int i;
947     for (i = 0; i < len; i++) {
948         if (i != 7 && key[i] != uid[i])
949             return 0;
950     }
951     return 1;
952 }
953
954 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
955 {
956     while (uls->uid[0]) {
957         if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
958             break;
959         uls++;
960     }
961     return uls;
962 }
963
964 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
965 {
966     int i;
967
968     if (!strong_ref)
969         return NULL;
970     for (i = 0; i < mxf->metadata_sets_count; i++) {
971         if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
972             (type == AnyType || mxf->metadata_sets[i]->type == type)) {
973             return mxf->metadata_sets[i];
974         }
975     }
976     return NULL;
977 }
978
979 static const MXFCodecUL mxf_picture_essence_container_uls[] = {
980     // video essence container uls
981     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
982     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14,    CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
983     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      CODEC_ID_NONE },
984 };
985 static const MXFCodecUL mxf_sound_essence_container_uls[] = {
986     // sound essence container uls
987     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
988     { { 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 */
989     { { 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 */
990     { { 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 */
991     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      CODEC_ID_NONE },
992 };
993
994 static UID mxf_d10_ul = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 };
995
996 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
997 {
998     int i, j, nb_segments = 0;
999     MXFIndexTableSegment **unsorted_segments;
1000     int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
1001
1002     /* count number of segments, allocate arrays and copy unsorted segments */
1003     for (i = 0; i < mxf->metadata_sets_count; i++)
1004         if (mxf->metadata_sets[i]->type == IndexTableSegment)
1005             nb_segments++;
1006
1007     if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
1008         !(*sorted_segments  = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
1009         av_free(unsorted_segments);
1010         return AVERROR(ENOMEM);
1011     }
1012
1013     for (i = j = 0; i < mxf->metadata_sets_count; i++)
1014         if (mxf->metadata_sets[i]->type == IndexTableSegment)
1015             unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
1016
1017     *nb_sorted_segments = 0;
1018
1019     /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
1020     for (i = 0; i < nb_segments; i++) {
1021         int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
1022
1023         for (j = 0; j < nb_segments; j++) {
1024             MXFIndexTableSegment *s = unsorted_segments[j];
1025
1026             /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
1027              * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
1028              */
1029             if ((i == 0     || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
1030                 (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start)) {
1031                 best             = j;
1032                 best_body_sid    = s->body_sid;
1033                 best_index_sid   = s->index_sid;
1034                 best_index_start = s->index_start_position;
1035             }
1036         }
1037
1038         /* no suitable entry found -> we're done */
1039         if (best == -1)
1040             break;
1041
1042         (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
1043         last_body_sid    = best_body_sid;
1044         last_index_sid   = best_index_sid;
1045         last_index_start = best_index_start;
1046     }
1047
1048     av_free(unsorted_segments);
1049
1050     return 0;
1051 }
1052
1053 /**
1054  * Computes the absolute file offset of the given essence container offset
1055  */
1056 static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
1057 {
1058     int x;
1059     int64_t offset_in = offset;     /* for logging */
1060
1061     for (x = 0; x < mxf->partitions_count; x++) {
1062         MXFPartition *p = &mxf->partitions[x];
1063
1064         if (p->body_sid != body_sid)
1065             continue;
1066
1067         if (offset < p->essence_length || !p->essence_length) {
1068             *offset_out = p->essence_offset + offset;
1069             return 0;
1070         }
1071
1072         offset -= p->essence_length;
1073     }
1074
1075     av_log(mxf->fc, AV_LOG_ERROR, "failed to find absolute offset of %lx in BodySID %i - partial file?\n",
1076            offset_in, body_sid);
1077
1078     return AVERROR_INVALIDDATA;
1079 }
1080
1081 static int mxf_parse_index(MXFContext *mxf, int track_id, AVStream *st)
1082 {
1083     int j, k, ret, nb_sorted_segments;
1084     MXFIndexTableSegment **sorted_segments = NULL;
1085     int n_delta = track_id - 1;  /* TrackID = 1-based stream index */
1086
1087     if (track_id < 1) {
1088         av_log(mxf->fc, AV_LOG_ERROR, "TrackID not positive: %i\n", track_id);
1089         ret = AVERROR_INVALIDDATA;
1090         goto err_out;
1091     }
1092
1093     if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)))
1094         goto err_out;
1095
1096     if (nb_sorted_segments <= 0) {
1097         av_log(mxf->fc, AV_LOG_WARNING, "Empty index for stream %i\n", st->index);
1098         ret = 0;
1099         goto err_out;
1100     }
1101
1102     for (j = 0; j < nb_sorted_segments; j++) {
1103         int duration, sample_duration = 1, last_sample_size = 0;
1104         int64_t segment_size;
1105         MXFIndexTableSegment *tableseg = sorted_segments[j];
1106
1107         if (n_delta >= tableseg->nb_delta_entries && st->index != 0)
1108             continue;
1109         duration = tableseg->index_duration > 0 ? tableseg->index_duration :
1110             st->duration - st->nb_index_entries;
1111         segment_size = tableseg->edit_unit_byte_count * duration;
1112         /* check small EditUnitByteCount for audio */
1113         if (tableseg->edit_unit_byte_count && tableseg->edit_unit_byte_count < 32
1114             && !tableseg->index_duration) {
1115             /* duration might be prime relative to the new sample_duration,
1116              * which means we need to handle the last frame differently */
1117             sample_duration = 8192;
1118             last_sample_size = (duration % sample_duration) * tableseg->edit_unit_byte_count;
1119             tableseg->edit_unit_byte_count *= sample_duration;
1120             duration /= sample_duration;
1121             if (last_sample_size) duration++;
1122         }
1123
1124         if (duration <= 0) {
1125             av_log(mxf->fc, AV_LOG_WARNING, "0 duration in index for stream %i\n", st->index);
1126             ret = 0;
1127             goto err_out;
1128         }
1129
1130         for (k = 0; k < duration; k++) {
1131             int64_t pos;
1132             int size, flags = 0;
1133
1134             if (k < tableseg->nb_index_entries) {
1135                 pos = tableseg->stream_offset_entries[k];
1136                 if (n_delta < tableseg->nb_delta_entries) {
1137                     if (n_delta < tableseg->nb_delta_entries - 1) {
1138                         size =
1139                             tableseg->slice_offset_entries[k][tableseg->slice[n_delta+1]-1] +
1140                             tableseg->element_delta[n_delta+1] -
1141                             tableseg->element_delta[n_delta];
1142                         if (tableseg->slice[n_delta] > 0)
1143                             size -= tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
1144                     } else if (k < duration - 1) {
1145                         size = tableseg->stream_offset_entries[k+1] -
1146                             tableseg->stream_offset_entries[k] -
1147                             tableseg->slice_offset_entries[k][tableseg->slice[tableseg->nb_delta_entries-1]-1] -
1148                             tableseg->element_delta[tableseg->nb_delta_entries-1];
1149                     } else
1150                         size = 0;
1151                     if (tableseg->slice[n_delta] > 0)
1152                         pos += tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
1153                     pos += tableseg->element_delta[n_delta];
1154                 } else
1155                     size = 0;
1156                 flags = !(tableseg->flag_entries[k] & 0x30) ? AVINDEX_KEYFRAME : 0;
1157             } else {
1158                 pos = (int64_t)(tableseg->index_start_position + k) * tableseg->edit_unit_byte_count;
1159                 if (n_delta < tableseg->nb_delta_entries - 1)
1160                     size = tableseg->element_delta[n_delta+1] - tableseg->element_delta[n_delta];
1161                 else {
1162                     /* use smaller size for last sample if we should */
1163                     if (last_sample_size && k == duration - 1)
1164                         size = last_sample_size;
1165                     else
1166                         size = tableseg->edit_unit_byte_count;
1167                     if (tableseg->nb_delta_entries)
1168                         size -= tableseg->element_delta[tableseg->nb_delta_entries-1];
1169                 }
1170                 if (n_delta < tableseg->nb_delta_entries)
1171                     pos += tableseg->element_delta[n_delta];
1172                 flags = AVINDEX_KEYFRAME;
1173             }
1174
1175             if (mxf_absolute_bodysid_offset(mxf, tableseg->body_sid, pos, &pos) < 0) {
1176                 /* probably partial file - no point going further for this stream */
1177                 break;
1178             }
1179
1180             av_dlog(mxf->fc, "Stream %d IndexEntry %d TrackID %d Offset %"PRIx64" Timestamp %"PRId64"\n",
1181                     st->index, st->nb_index_entries, track_id, pos, sample_duration * st->nb_index_entries);
1182
1183             if ((ret = av_add_index_entry(st, pos, sample_duration * st->nb_index_entries, size, 0, flags)) < 0)
1184                 return ret;
1185         }
1186     }
1187
1188     av_free(sorted_segments);
1189
1190     return 0;
1191
1192 err_out:
1193     av_free(sorted_segments);
1194     mxf->broken_index = 1;
1195     return ret;
1196 }
1197
1198 static int mxf_parse_structural_metadata(MXFContext *mxf)
1199 {
1200     MXFPackage *material_package = NULL;
1201     MXFPackage *temp_package = NULL;
1202     int i, j, k, ret;
1203
1204     av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
1205     /* TODO: handle multiple material packages (OP3x) */
1206     for (i = 0; i < mxf->packages_count; i++) {
1207         material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
1208         if (material_package) break;
1209     }
1210     if (!material_package) {
1211         av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
1212         return -1;
1213     }
1214
1215     for (i = 0; i < material_package->tracks_count; i++) {
1216         MXFPackage *source_package = NULL;
1217         MXFTrack *material_track = NULL;
1218         MXFTrack *source_track = NULL;
1219         MXFTrack *temp_track = NULL;
1220         MXFDescriptor *descriptor = NULL;
1221         MXFStructuralComponent *component = NULL;
1222         UID *essence_container_ul = NULL;
1223         const MXFCodecUL *codec_ul = NULL;
1224         const MXFCodecUL *container_ul = NULL;
1225         AVStream *st;
1226
1227         if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
1228             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
1229             continue;
1230         }
1231
1232         if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
1233             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
1234             continue;
1235         }
1236
1237         /* TODO: handle multiple source clips */
1238         for (j = 0; j < material_track->sequence->structural_components_count; j++) {
1239             /* TODO: handle timecode component */
1240             component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
1241             if (!component)
1242                 continue;
1243
1244             for (k = 0; k < mxf->packages_count; k++) {
1245                 temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
1246                 if (!temp_package)
1247                     continue;
1248                 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
1249                     source_package = temp_package;
1250                     break;
1251                 }
1252             }
1253             if (!source_package) {
1254                 av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
1255                 break;
1256             }
1257             for (k = 0; k < source_package->tracks_count; k++) {
1258                 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
1259                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
1260                     return -1;
1261                 }
1262                 if (temp_track->track_id == component->source_track_id) {
1263                     source_track = temp_track;
1264                     break;
1265                 }
1266             }
1267             if (!source_track) {
1268                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
1269                 break;
1270             }
1271         }
1272         if (!source_track)
1273             continue;
1274
1275         if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
1276             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
1277             return -1;
1278         }
1279
1280         /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
1281          * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
1282         if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
1283             av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
1284             continue;
1285         }
1286
1287         st = avformat_new_stream(mxf->fc, NULL);
1288         if (!st) {
1289             av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
1290             return -1;
1291         }
1292         st->id = source_track->track_id;
1293         st->priv_data = source_track;
1294         st->duration = component->duration;
1295         if (st->duration == -1)
1296             st->duration = AV_NOPTS_VALUE;
1297         st->start_time = component->start_position;
1298         avpriv_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
1299
1300         PRINT_KEY(mxf->fc, "data definition   ul", source_track->sequence->data_definition_ul);
1301         codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
1302         st->codec->codec_type = codec_ul->id;
1303
1304         source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
1305         if (source_package->descriptor) {
1306             if (source_package->descriptor->type == MultipleDescriptor) {
1307                 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
1308                     MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
1309
1310                     if (!sub_descriptor) {
1311                         av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
1312                         continue;
1313                     }
1314                     if (sub_descriptor->linked_track_id == source_track->track_id) {
1315                         descriptor = sub_descriptor;
1316                         break;
1317                     }
1318                 }
1319             } else if (source_package->descriptor->type == Descriptor)
1320                 descriptor = source_package->descriptor;
1321         }
1322         if (!descriptor) {
1323             av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
1324             continue;
1325         }
1326         PRINT_KEY(mxf->fc, "essence codec     ul", descriptor->essence_codec_ul);
1327         PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
1328         essence_container_ul = &descriptor->essence_container_ul;
1329         /* HACK: replacing the original key with mxf_encrypted_essence_container
1330          * is not allowed according to s429-6, try to find correct information anyway */
1331         if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
1332             av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
1333             for (k = 0; k < mxf->metadata_sets_count; k++) {
1334                 MXFMetadataSet *metadata = mxf->metadata_sets[k];
1335                 if (metadata->type == CryptoContext) {
1336                     essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
1337                     break;
1338                 }
1339             }
1340         }
1341
1342         /* HACK: revert to the old demuxing/seeking scode for D-10 for now */
1343         if (mxf_match_uid(essence_container_ul, mxf_d10_ul, 14))
1344             mxf->d10 = 1;
1345
1346         /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
1347         codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
1348         st->codec->codec_id = codec_ul->id;
1349         if (descriptor->extradata) {
1350             st->codec->extradata = descriptor->extradata;
1351             st->codec->extradata_size = descriptor->extradata_size;
1352         }
1353         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1354             container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
1355             if (st->codec->codec_id == CODEC_ID_NONE)
1356                 st->codec->codec_id = container_ul->id;
1357             st->codec->width = descriptor->width;
1358             st->codec->height = descriptor->height;
1359             if (st->codec->codec_id == CODEC_ID_RAWVIDEO)
1360                 st->codec->pix_fmt = descriptor->pix_fmt;
1361             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1362         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1363             container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
1364             if (st->codec->codec_id == CODEC_ID_NONE)
1365                 st->codec->codec_id = container_ul->id;
1366             st->codec->channels = descriptor->channels;
1367             st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
1368             st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
1369             /* TODO: implement CODEC_ID_RAWAUDIO */
1370             if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
1371                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1372                     st->codec->codec_id = CODEC_ID_PCM_S24LE;
1373                 else if (descriptor->bits_per_sample == 32)
1374                     st->codec->codec_id = CODEC_ID_PCM_S32LE;
1375             } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
1376                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1377                     st->codec->codec_id = CODEC_ID_PCM_S24BE;
1378                 else if (descriptor->bits_per_sample == 32)
1379                     st->codec->codec_id = CODEC_ID_PCM_S32BE;
1380             } else if (st->codec->codec_id == CODEC_ID_MP2) {
1381                 st->need_parsing = AVSTREAM_PARSE_FULL;
1382             }
1383         }
1384         if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
1385             /* TODO: decode timestamps */
1386             st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
1387         }
1388
1389         if ((ret = mxf_parse_index(mxf, material_track->track_id, st)))
1390             return ret;
1391     }
1392     return 0;
1393 }
1394
1395 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
1396     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
1397     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
1398     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
1399     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
1400     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
1401     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
1402     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
1403     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
1404     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
1405     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
1406     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
1407     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
1408     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
1409     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
1410     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
1411     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
1412     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
1413     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Generic Sound */
1414     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
1415     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
1416     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG 2 Video */
1417     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
1418     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
1419     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
1420     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
1421     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
1422     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
1423     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
1424 };
1425
1426 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
1427 {
1428     AVIOContext *pb = mxf->fc->pb;
1429     MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
1430     uint64_t klv_end = avio_tell(pb) + klv->length;
1431
1432     if (!ctx)
1433         return -1;
1434     while (avio_tell(pb) + 4 < klv_end) {
1435         int tag = avio_rb16(pb);
1436         int size = avio_rb16(pb); /* KLV specified by 0x53 */
1437         uint64_t next = avio_tell(pb) + size;
1438         UID uid = {0};
1439
1440         av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
1441         if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
1442             av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
1443             continue;
1444         }
1445         if (tag > 0x7FFF) { /* dynamic tag */
1446             int i;
1447             for (i = 0; i < mxf->local_tags_count; i++) {
1448                 int local_tag = AV_RB16(mxf->local_tags+i*18);
1449                 if (local_tag == tag) {
1450                     memcpy(uid, mxf->local_tags+i*18+2, 16);
1451                     av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
1452                     PRINT_KEY(mxf->fc, "uid", uid);
1453                 }
1454             }
1455         }
1456         if (ctx_size && tag == 0x3C0A)
1457             avio_read(pb, ctx->uid, 16);
1458         else if (read_child(ctx, pb, tag, size, uid, -1) < 0)
1459             return -1;
1460
1461         avio_seek(pb, next, SEEK_SET);
1462     }
1463     if (ctx_size) ctx->type = type;
1464     return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
1465 }
1466
1467 /**
1468  * Seeks to the previous partition, if possible
1469  * @return <= 0 if we should stop parsing, > 0 if we should keep going
1470  */
1471 static int mxf_seek_to_previous_partition(MXFContext *mxf)
1472 {
1473     AVIOContext *pb = mxf->fc->pb;
1474
1475     if (!mxf->current_partition ||
1476         mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
1477         return 0;   /* we've parsed all partitions */
1478
1479     /* seek to previous partition */
1480     avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
1481     mxf->current_partition = NULL;
1482
1483     av_dlog(mxf->fc, "seeking to previous partition\n");
1484
1485     return 1;
1486 }
1487
1488 /**
1489  * Called when essence is encountered
1490  * @return <= 0 if we should stop parsing, > 0 if we should keep going
1491  */
1492 static int mxf_parse_handle_essence(MXFContext *mxf)
1493 {
1494     AVIOContext *pb = mxf->fc->pb;
1495     int64_t ret;
1496
1497     if (!mxf->current_partition) {
1498         av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to PartitionPack\n");
1499         return AVERROR_INVALIDDATA;
1500     }
1501
1502     if (mxf->parsing_backward) {
1503         return mxf_seek_to_previous_partition(mxf);
1504     } else {
1505         if (!mxf->footer_partition) {
1506             av_dlog(mxf->fc, "no footer\n");
1507             return 0;
1508         }
1509
1510         av_dlog(mxf->fc, "seeking to footer\n");
1511
1512         /* remember where we were so we don't end up seeking further back than this */
1513         mxf->last_forward_tell = avio_tell(pb);
1514
1515         if (!pb->seekable) {
1516             av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing footer\n");
1517             return -1;
1518         }
1519
1520         /* seek to footer partition and parse backward */
1521         if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
1522             av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to footer @ 0x%"PRIx64" (%"PRId64") - partial file?\n",
1523                    mxf->run_in + mxf->footer_partition, ret);
1524             return ret;
1525         }
1526
1527         mxf->current_partition = NULL;
1528         mxf->parsing_backward = 1;
1529     }
1530
1531     return 1;
1532 }
1533
1534 /**
1535  * Called when the next partition or EOF is encountered
1536  * @return <= 0 if we should stop parsing, > 0 if we should keep going
1537  */
1538 static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
1539 {
1540     return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
1541 }
1542
1543 /**
1544  * Figures out the proper offset and length of the essence container in each partition
1545  */
1546 static void mxf_compute_essence_containers(MXFContext *mxf)
1547 {
1548     int x;
1549
1550     /* everything is already correct */
1551     if (mxf->op == OPAtom)
1552         return;
1553
1554     for (x = 0; x < mxf->partitions_count; x++) {
1555         MXFPartition *p = &mxf->partitions[x];
1556
1557         if (!p->body_sid)
1558             continue;       /* BodySID == 0 -> no essence */
1559
1560         if (x >= mxf->partitions_count - 1)
1561             break;          /* last partition - can't compute length (and we don't need to) */
1562
1563         /* essence container spans to the next partition */
1564         p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
1565
1566         if (p->essence_length < 0) {
1567             /* next ThisPartition < essence_offset */
1568             p->essence_length = 0;
1569             av_log(mxf->fc, AV_LOG_ERROR, "partition %i: bad ThisPartition = %lx\n",
1570                    x+1, mxf->partitions[x+1].this_partition);
1571         }
1572     }
1573 }
1574
1575 static int64_t round_to_kag(int64_t position, int kag_size)
1576 {
1577     /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
1578     /* NOTE: kag_size may be any integer between 1 - 2^10 */
1579     int64_t ret = (position / kag_size) * kag_size;
1580     return ret == position ? ret : ret + kag_size;
1581 }
1582
1583 static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
1584 {
1585     MXFContext *mxf = s->priv_data;
1586     KLVPacket klv;
1587     int64_t essence_offset = 0;
1588
1589     mxf->last_forward_tell = INT64_MAX;
1590
1591     if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
1592         av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
1593         return -1;
1594     }
1595     avio_seek(s->pb, -14, SEEK_CUR);
1596     mxf->fc = s;
1597     mxf->run_in = avio_tell(s->pb);
1598
1599     while (!url_feof(s->pb)) {
1600         const MXFMetadataReadTableEntry *metadata;
1601
1602         if (klv_read_packet(&klv, s->pb) < 0) {
1603             /* EOF - seek to previous partition or stop */
1604             if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
1605                 break;
1606             else
1607                 continue;
1608         }
1609
1610         PRINT_KEY(s, "read header", klv.key);
1611         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
1612         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
1613             IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
1614             IS_KLV_KEY(klv.key, mxf_system_item_key)) {
1615             if (!mxf->current_partition->essence_offset) {
1616                 /* for OP1a we compute essence_offset
1617                  * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)
1618                  * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset
1619                  *       for OPAtom we still need the actual essence_offset though (the KL's length can vary)
1620                  */
1621                 int64_t op1a_essence_offset =
1622                     round_to_kag(mxf->current_partition->this_partition +
1623                                  mxf->current_partition->pack_length,       mxf->current_partition->kag_size) +
1624                     round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +
1625                     round_to_kag(mxf->current_partition->index_byte_count,  mxf->current_partition->kag_size);
1626
1627                 if (mxf->op == OPAtom) {
1628                     /* point essence_offset to the actual data
1629                     * OPAtom has all the essence in one big KLV
1630                     */
1631                     mxf->current_partition->essence_offset = avio_tell(s->pb);
1632                     mxf->current_partition->essence_length = klv.length;
1633                 } else {
1634                     /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf)  */
1635                     mxf->current_partition->essence_offset = op1a_essence_offset;
1636                 }
1637             }
1638
1639             if (!essence_offset)
1640                 essence_offset = klv.offset;
1641
1642             /* seek to footer, previous partition or stop */
1643             if (mxf_parse_handle_essence(mxf) <= 0)
1644                 break;
1645             continue;
1646         } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
1647                    klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
1648             /* next partition pack - keep going, seek to previous partition or stop */
1649             if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
1650                 break;
1651         }
1652
1653         for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
1654             if (IS_KLV_KEY(klv.key, metadata->key)) {
1655                 int res;
1656                 if (klv.key[5] == 0x53) {
1657                     res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
1658                 } else {
1659                     uint64_t next = avio_tell(s->pb) + klv.length;
1660                     res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
1661                     avio_seek(s->pb, next, SEEK_SET);
1662                 }
1663                 if (res < 0) {
1664                     av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
1665                     return -1;
1666                 }
1667                 break;
1668             }
1669         }
1670         if (!metadata->read)
1671             avio_skip(s->pb, klv.length);
1672     }
1673     /* FIXME avoid seek */
1674     if (!essence_offset)  {
1675         av_log(s, AV_LOG_ERROR, "no essence\n");
1676         return AVERROR_INVALIDDATA;
1677     }
1678     avio_seek(s->pb, essence_offset, SEEK_SET);
1679
1680     mxf_compute_essence_containers(mxf);
1681
1682     return mxf_parse_structural_metadata(mxf);
1683 }
1684
1685 static int mxf_read_close(AVFormatContext *s)
1686 {
1687     MXFContext *mxf = s->priv_data;
1688     MXFIndexTableSegment *seg;
1689     int i, j;
1690
1691     av_freep(&mxf->packages_refs);
1692
1693     for (i = 0; i < s->nb_streams; i++)
1694         s->streams[i]->priv_data = NULL;
1695
1696     for (i = 0; i < mxf->metadata_sets_count; i++) {
1697         switch (mxf->metadata_sets[i]->type) {
1698         case MultipleDescriptor:
1699             av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
1700             break;
1701         case Sequence:
1702             av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
1703             break;
1704         case SourcePackage:
1705         case MaterialPackage:
1706             av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
1707             break;
1708         case IndexTableSegment:
1709             seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
1710             for (j = 0; j < seg->nb_index_entries; j++)
1711                 av_freep(&seg->slice_offset_entries[j]);
1712             av_freep(&seg->slice);
1713             av_freep(&seg->element_delta);
1714             av_freep(&seg->temporal_offset_entries);
1715             av_freep(&seg->flag_entries);
1716             av_freep(&seg->stream_offset_entries);
1717             av_freep(&seg->slice_offset_entries);
1718             break;
1719         default:
1720             break;
1721         }
1722         av_freep(&mxf->metadata_sets[i]);
1723     }
1724     av_freep(&mxf->partitions);
1725     av_freep(&mxf->metadata_sets);
1726     av_freep(&mxf->aesc);
1727     av_freep(&mxf->local_tags);
1728     return 0;
1729 }
1730
1731 static int mxf_probe(AVProbeData *p) {
1732     uint8_t *bufp = p->buf;
1733     uint8_t *end = p->buf + p->buf_size;
1734
1735     if (p->buf_size < sizeof(mxf_header_partition_pack_key))
1736         return 0;
1737
1738     /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
1739     end -= sizeof(mxf_header_partition_pack_key);
1740     for (; bufp < end; bufp++) {
1741         if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
1742             return AVPROBE_SCORE_MAX;
1743     }
1744     return 0;
1745 }
1746
1747 /* rudimentary byte seek */
1748 /* XXX: use MXF Index */
1749 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1750 {
1751     AVStream *st = s->streams[stream_index];
1752     int64_t seconds;
1753     MXFContext* mxf = s->priv_data;
1754     int64_t seekpos;
1755     int index;
1756
1757     if (mxf->d10) {
1758     if (!s->bit_rate)
1759         return -1;
1760     if (sample_time < 0)
1761         sample_time = 0;
1762     seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
1763     if (avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET) < 0)
1764         return -1;
1765     ff_update_cur_dts(s, st, sample_time);
1766     } else {
1767         if (st->nb_index_entries <= 0)
1768             return -1;
1769
1770         index = av_index_search_timestamp(st, sample_time, flags);
1771
1772         av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, sample_time, index);
1773
1774         if (index < 0) {
1775             if (sample_time < st->index_entries[0].timestamp)
1776                 index = 0;
1777             else
1778                 return -1;
1779         }
1780
1781         seekpos = st->index_entries[index].pos;
1782         av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1783         mxf->current_edit_unit = st->index_entries[index].timestamp;
1784         mxf->current_stream = 0;
1785         avio_seek(s->pb, seekpos, SEEK_SET);
1786     }
1787     return 0;
1788 }
1789
1790 AVInputFormat ff_mxf_demuxer = {
1791     .name           = "mxf",
1792     .long_name      = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1793     .priv_data_size = sizeof(MXFContext),
1794     .read_probe     = mxf_probe,
1795     .read_header    = mxf_read_header,
1796     .read_packet    = mxf_read_packet,
1797     .read_close     = mxf_read_close,
1798     .read_seek      = mxf_read_seek,
1799 };