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