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