]> git.sesse.net Git - ffmpeg/blob - libavformat/mxfdec.c
Do not try to parse empty strf tags.
[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 "mxf.h"
53
54 typedef enum {
55     Header,
56     BodyPartition,
57     Footer
58 } MXFPartitionType;
59
60 typedef enum {
61     OP1a,
62     OP1b,
63     OP1c,
64     OP2a,
65     OP2b,
66     OP2c,
67     OP3a,
68     OP3b,
69     OP3c,
70     OPAtom,
71 } MXFOP;
72
73 typedef struct {
74     int closed;
75     int complete;
76     MXFPartitionType type;
77     uint64_t previous_partition;
78     int index_sid;
79     int body_sid;
80 } MXFPartition;
81
82 typedef struct {
83     UID uid;
84     enum MXFMetadataSetType type;
85     UID source_container_ul;
86 } MXFCryptoContext;
87
88 typedef struct {
89     UID uid;
90     enum MXFMetadataSetType type;
91     UID source_package_uid;
92     UID data_definition_ul;
93     int64_t duration;
94     int64_t start_position;
95     int source_track_id;
96 } MXFStructuralComponent;
97
98 typedef struct {
99     UID uid;
100     enum MXFMetadataSetType type;
101     UID data_definition_ul;
102     UID *structural_components_refs;
103     int structural_components_count;
104     int64_t duration;
105 } MXFSequence;
106
107 typedef struct {
108     UID uid;
109     enum MXFMetadataSetType type;
110     MXFSequence *sequence; /* mandatory, and only one */
111     UID sequence_ref;
112     int track_id;
113     uint8_t track_number[4];
114     AVRational edit_rate;
115 } MXFTrack;
116
117 typedef struct {
118     UID uid;
119     enum MXFMetadataSetType type;
120     UID essence_container_ul;
121     UID essence_codec_ul;
122     AVRational sample_rate;
123     AVRational aspect_ratio;
124     int width;
125     int height;
126     int channels;
127     int bits_per_sample;
128     UID *sub_descriptors_refs;
129     int sub_descriptors_count;
130     int linked_track_id;
131     uint8_t *extradata;
132     int extradata_size;
133     enum PixelFormat pix_fmt;
134 } MXFDescriptor;
135
136 typedef struct {
137     UID uid;
138     enum MXFMetadataSetType type;
139 } MXFIndexTableSegment;
140
141 typedef struct {
142     UID uid;
143     enum MXFMetadataSetType type;
144     UID package_uid;
145     UID *tracks_refs;
146     int tracks_count;
147     MXFDescriptor *descriptor; /* only one */
148     UID descriptor_ref;
149 } MXFPackage;
150
151 typedef struct {
152     UID uid;
153     enum MXFMetadataSetType type;
154 } MXFMetadataSet;
155
156 typedef struct {
157     MXFPartition *partitions;
158     unsigned partitions_count;
159     MXFOP op;
160     UID *packages_refs;
161     int packages_count;
162     MXFMetadataSet **metadata_sets;
163     int metadata_sets_count;
164     AVFormatContext *fc;
165     struct AVAES *aesc;
166     uint8_t *local_tags;
167     int local_tags_count;
168     uint64_t footer_partition;
169 } MXFContext;
170
171 enum MXFWrappingScheme {
172     Frame,
173     Clip,
174 };
175
176 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid);
177
178 typedef struct {
179     const UID key;
180     MXFMetadataReadFunc *read;
181     int ctx_size;
182     enum MXFMetadataSetType type;
183 } MXFMetadataReadTableEntry;
184
185 /* partial keys to match */
186 static const uint8_t mxf_header_partition_pack_key[]       = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
187 static const uint8_t mxf_essence_element_key[]             = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
188 static const uint8_t mxf_klv_key[]                         = { 0x06,0x0e,0x2b,0x34 };
189 /* complete keys to match */
190 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 };
191 static const uint8_t mxf_encrypted_triplet_key[]           = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
192 static const uint8_t mxf_encrypted_essence_container[]     = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
193 static const uint8_t mxf_sony_mpeg4_extradata[]            = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
194
195 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
196
197 static int64_t klv_decode_ber_length(AVIOContext *pb)
198 {
199     uint64_t size = avio_r8(pb);
200     if (size & 0x80) { /* long form */
201         int bytes_num = size & 0x7f;
202         /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
203         if (bytes_num > 8)
204             return -1;
205         size = 0;
206         while (bytes_num--)
207             size = size << 8 | avio_r8(pb);
208     }
209     return size;
210 }
211
212 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
213 {
214     int i, b;
215     for (i = 0; i < size && !url_feof(pb); i++) {
216         b = avio_r8(pb);
217         if (b == key[0])
218             i = 0;
219         else if (b != key[i])
220             i = -1;
221     }
222     return i == size;
223 }
224
225 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
226 {
227     if (!mxf_read_sync(pb, mxf_klv_key, 4))
228         return -1;
229     klv->offset = avio_tell(pb) - 4;
230     memcpy(klv->key, mxf_klv_key, 4);
231     avio_read(pb, klv->key + 4, 12);
232     klv->length = klv_decode_ber_length(pb);
233     return klv->length == -1 ? -1 : 0;
234 }
235
236 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
237 {
238     int i;
239
240     for (i = 0; i < s->nb_streams; i++) {
241         MXFTrack *track = s->streams[i]->priv_data;
242         /* SMPTE 379M 7.3 */
243         if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
244             return i;
245     }
246     /* return 0 if only one stream, for OP Atom files with 0 as track number */
247     return s->nb_streams == 1 ? 0 : -1;
248 }
249
250 /* XXX: use AVBitStreamFilter */
251 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
252 {
253     const uint8_t *buf_ptr, *end_ptr;
254     uint8_t *data_ptr;
255     int i;
256
257     if (length > 61444) /* worst case PAL 1920 samples 8 channels */
258         return -1;
259     length = av_get_packet(pb, pkt, length);
260     if (length < 0)
261         return length;
262     data_ptr = pkt->data;
263     end_ptr = pkt->data + length;
264     buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
265     for (; buf_ptr + st->codec->channels*4 < end_ptr; ) {
266         for (i = 0; i < st->codec->channels; i++) {
267             uint32_t sample = bytestream_get_le32(&buf_ptr);
268             if (st->codec->bits_per_coded_sample == 24)
269                 bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
270             else
271                 bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
272         }
273         buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
274     }
275     av_shrink_packet(pkt, data_ptr - pkt->data);
276     return 0;
277 }
278
279 static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
280 {
281     static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
282     MXFContext *mxf = s->priv_data;
283     AVIOContext *pb = s->pb;
284     int64_t end = avio_tell(pb) + klv->length;
285     uint64_t size;
286     uint64_t orig_size;
287     uint64_t plaintext_size;
288     uint8_t ivec[16];
289     uint8_t tmpbuf[16];
290     int index;
291
292     if (!mxf->aesc && s->key && s->keylen == 16) {
293         mxf->aesc = av_malloc(av_aes_size);
294         if (!mxf->aesc)
295             return -1;
296         av_aes_init(mxf->aesc, s->key, 128, 1);
297     }
298     // crypto context
299     avio_skip(pb, klv_decode_ber_length(pb));
300     // plaintext offset
301     klv_decode_ber_length(pb);
302     plaintext_size = avio_rb64(pb);
303     // source klv key
304     klv_decode_ber_length(pb);
305     avio_read(pb, klv->key, 16);
306     if (!IS_KLV_KEY(klv, mxf_essence_element_key))
307         return -1;
308     index = mxf_get_stream_index(s, klv);
309     if (index < 0)
310         return -1;
311     // source size
312     klv_decode_ber_length(pb);
313     orig_size = avio_rb64(pb);
314     if (orig_size < plaintext_size)
315         return -1;
316     // enc. code
317     size = klv_decode_ber_length(pb);
318     if (size < 32 || size - 32 < orig_size)
319         return -1;
320     avio_read(pb, ivec, 16);
321     avio_read(pb, tmpbuf, 16);
322     if (mxf->aesc)
323         av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
324     if (memcmp(tmpbuf, checkv, 16))
325         av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
326     size -= 32;
327     size = av_get_packet(pb, pkt, size);
328     if (size < 0)
329         return size;
330     else if (size < plaintext_size)
331         return AVERROR_INVALIDDATA;
332     size -= plaintext_size;
333     if (mxf->aesc)
334         av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
335                      &pkt->data[plaintext_size], size >> 4, ivec, 1);
336     av_shrink_packet(pkt, orig_size);
337     pkt->stream_index = index;
338     avio_skip(pb, end - avio_tell(pb));
339     return 0;
340 }
341
342 static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
343 {
344     KLVPacket klv;
345
346     while (!url_feof(s->pb)) {
347         if (klv_read_packet(&klv, s->pb) < 0)
348             return -1;
349         PRINT_KEY(s, "read packet", klv.key);
350         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
351         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
352             int res = mxf_decrypt_triplet(s, pkt, &klv);
353             if (res < 0) {
354                 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
355                 return -1;
356             }
357             return 0;
358         }
359         if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
360             int index = mxf_get_stream_index(s, &klv);
361             if (index < 0) {
362                 av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
363                 goto skip;
364             }
365             if (s->streams[index]->discard == AVDISCARD_ALL)
366                 goto skip;
367             /* check for 8 channels AES3 element */
368             if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
369                 if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
370                     av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
371                     return -1;
372                 }
373             } else {
374                 int ret = av_get_packet(s->pb, pkt, klv.length);
375                 if (ret < 0)
376                     return ret;
377             }
378             pkt->stream_index = index;
379             pkt->pos = klv.offset;
380             return 0;
381         } else
382         skip:
383             avio_skip(s->pb, klv.length);
384     }
385     return AVERROR_EOF;
386 }
387
388 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid)
389 {
390     MXFContext *mxf = arg;
391     int item_num = avio_rb32(pb);
392     int item_len = avio_rb32(pb);
393
394     if (item_len != 18) {
395         av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");
396         return -1;
397     }
398     if (item_num > UINT_MAX / item_len)
399         return -1;
400     mxf->local_tags_count = item_num;
401     mxf->local_tags = av_malloc(item_num*item_len);
402     if (!mxf->local_tags)
403         return -1;
404     avio_read(pb, mxf->local_tags, item_num*item_len);
405     return 0;
406 }
407
408 static int mxf_read_partition_pack(void *arg, ByteIOContext *pb, int tag, int size, UID uid)
409 {
410     MXFContext *mxf = arg;
411     MXFPartition *partition;
412     UID op;
413     uint64_t footer_partition;
414
415     if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
416         return AVERROR(ENOMEM);
417
418     mxf->partitions = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
419     if (!mxf->partitions)
420         return AVERROR(ENOMEM);
421
422     partition = &mxf->partitions[mxf->partitions_count++];
423
424     switch(uid[13]) {
425     case 2:
426         partition->type = Header;
427         break;
428     case 3:
429         partition->type = BodyPartition;
430         break;
431     case 4:
432         partition->type = Footer;
433         break;
434     default:
435         av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
436         return AVERROR_INVALIDDATA;
437     }
438
439     /* consider both footers to be closed (there is only Footer and CompleteFooter) */
440     partition->closed = partition->type == Footer || !(uid[14] & 1);
441     partition->complete = uid[14] > 2;
442     avio_skip(pb, 16);
443     partition->previous_partition = avio_rb64(pb);
444     footer_partition = avio_rb64(pb);
445     avio_skip(pb, 16);
446     partition->index_sid = avio_rb32(pb);
447     avio_skip(pb, 8);
448     partition->body_sid = avio_rb32(pb);
449     avio_read(pb, op, sizeof(UID));
450
451     /* some files don'thave FooterPartition set in every partition */
452     if (footer_partition) {
453         if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
454             av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %li != %li\n",
455                    mxf->footer_partition, footer_partition);
456         } else {
457             mxf->footer_partition = footer_partition;
458         }
459     }
460
461     av_dlog(mxf->fc, "PartitionPack: PreviousPartition = 0x%lx, "
462             "FooterPartition = 0x%lx, IndexSID = %i, BodySID = %i\n",
463             partition->previous_partition, footer_partition,
464             partition->index_sid, partition->body_sid);
465
466     if      (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
467     else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
468     else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
469     else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
470     else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
471     else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
472     else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
473     else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
474     else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
475     else if (op[12] == 0x10)             mxf->op = OPAtom;
476     else
477         av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh\n", op[12], op[13]);
478
479     return 0;
480 }
481
482 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
483 {
484     if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
485         return AVERROR(ENOMEM);
486     mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
487     if (!mxf->metadata_sets)
488         return -1;
489     mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
490     mxf->metadata_sets_count++;
491     return 0;
492 }
493
494 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid)
495 {
496     MXFCryptoContext *cryptocontext = arg;
497     if (size != 16)
498         return -1;
499     if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
500         avio_read(pb, cryptocontext->source_container_ul, 16);
501     return 0;
502 }
503
504 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid)
505 {
506     MXFContext *mxf = arg;
507     switch (tag) {
508     case 0x1901:
509         mxf->packages_count = avio_rb32(pb);
510         if (mxf->packages_count >= UINT_MAX / sizeof(UID))
511             return -1;
512         mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
513         if (!mxf->packages_refs)
514             return -1;
515         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
516         avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
517         break;
518     }
519     return 0;
520 }
521
522 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid)
523 {
524     MXFStructuralComponent *source_clip = arg;
525     switch(tag) {
526     case 0x0202:
527         source_clip->duration = avio_rb64(pb);
528         break;
529     case 0x1201:
530         source_clip->start_position = avio_rb64(pb);
531         break;
532     case 0x1101:
533         /* UMID, only get last 16 bytes */
534         avio_skip(pb, 16);
535         avio_read(pb, source_clip->source_package_uid, 16);
536         break;
537     case 0x1102:
538         source_clip->source_track_id = avio_rb32(pb);
539         break;
540     }
541     return 0;
542 }
543
544 static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
545 {
546     MXFPackage *package = arg;
547     switch(tag) {
548     case 0x4403:
549         package->tracks_count = avio_rb32(pb);
550         if (package->tracks_count >= UINT_MAX / sizeof(UID))
551             return -1;
552         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
553         if (!package->tracks_refs)
554             return -1;
555         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
556         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
557         break;
558     }
559     return 0;
560 }
561
562 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid)
563 {
564     MXFTrack *track = arg;
565     switch(tag) {
566     case 0x4801:
567         track->track_id = avio_rb32(pb);
568         break;
569     case 0x4804:
570         avio_read(pb, track->track_number, 4);
571         break;
572     case 0x4B01:
573         track->edit_rate.den = avio_rb32(pb);
574         track->edit_rate.num = avio_rb32(pb);
575         break;
576     case 0x4803:
577         avio_read(pb, track->sequence_ref, 16);
578         break;
579     }
580     return 0;
581 }
582
583 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid)
584 {
585     MXFSequence *sequence = arg;
586     switch(tag) {
587     case 0x0202:
588         sequence->duration = avio_rb64(pb);
589         break;
590     case 0x0201:
591         avio_read(pb, sequence->data_definition_ul, 16);
592         break;
593     case 0x1001:
594         sequence->structural_components_count = avio_rb32(pb);
595         if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
596             return -1;
597         sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
598         if (!sequence->structural_components_refs)
599             return -1;
600         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
601         avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
602         break;
603     }
604     return 0;
605 }
606
607 static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
608 {
609     MXFPackage *package = arg;
610     switch(tag) {
611     case 0x4403:
612         package->tracks_count = avio_rb32(pb);
613         if (package->tracks_count >= UINT_MAX / sizeof(UID))
614             return -1;
615         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
616         if (!package->tracks_refs)
617             return -1;
618         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
619         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
620         break;
621     case 0x4401:
622         /* UMID, only get last 16 bytes */
623         avio_skip(pb, 16);
624         avio_read(pb, package->package_uid, 16);
625         break;
626     case 0x4701:
627         avio_read(pb, package->descriptor_ref, 16);
628         break;
629     }
630     return 0;
631 }
632
633 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid)
634 {
635     switch(tag) {
636     case 0x3F05: av_dlog(NULL, "EditUnitByteCount %d\n", avio_rb32(pb)); break;
637     case 0x3F06: av_dlog(NULL, "IndexSID %d\n", avio_rb32(pb)); break;
638     case 0x3F07: av_dlog(NULL, "BodySID %d\n", avio_rb32(pb)); break;
639     case 0x3F0B: av_dlog(NULL, "IndexEditRate %d/%d\n", avio_rb32(pb), avio_rb32(pb)); break;
640     case 0x3F0C: av_dlog(NULL, "IndexStartPosition %"PRIu64"\n", avio_rb64(pb)); break;
641     case 0x3F0D: av_dlog(NULL, "IndexDuration %"PRIu64"\n", avio_rb64(pb)); break;
642     }
643     return 0;
644 }
645
646 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
647 {
648     int code, value, ofs = 0;
649     char layout[16] = {0};
650
651     do {
652         code = avio_r8(pb);
653         value = avio_r8(pb);
654         av_dlog(NULL, "pixel layout: code %#x\n", code);
655
656         if (ofs < 16) {
657             layout[ofs++] = code;
658             layout[ofs++] = value;
659         }
660     } while (code != 0); /* SMPTE 377M E.2.46 */
661
662     ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
663 }
664
665 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid)
666 {
667     MXFDescriptor *descriptor = arg;
668     switch(tag) {
669     case 0x3F01:
670         descriptor->sub_descriptors_count = avio_rb32(pb);
671         if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
672             return -1;
673         descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
674         if (!descriptor->sub_descriptors_refs)
675             return -1;
676         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
677         avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
678         break;
679     case 0x3004:
680         avio_read(pb, descriptor->essence_container_ul, 16);
681         break;
682     case 0x3006:
683         descriptor->linked_track_id = avio_rb32(pb);
684         break;
685     case 0x3201: /* PictureEssenceCoding */
686         avio_read(pb, descriptor->essence_codec_ul, 16);
687         break;
688     case 0x3203:
689         descriptor->width = avio_rb32(pb);
690         break;
691     case 0x3202:
692         descriptor->height = avio_rb32(pb);
693         break;
694     case 0x320E:
695         descriptor->aspect_ratio.num = avio_rb32(pb);
696         descriptor->aspect_ratio.den = avio_rb32(pb);
697         break;
698     case 0x3D03:
699         descriptor->sample_rate.num = avio_rb32(pb);
700         descriptor->sample_rate.den = avio_rb32(pb);
701         break;
702     case 0x3D06: /* SoundEssenceCompression */
703         avio_read(pb, descriptor->essence_codec_ul, 16);
704         break;
705     case 0x3D07:
706         descriptor->channels = avio_rb32(pb);
707         break;
708     case 0x3D01:
709         descriptor->bits_per_sample = avio_rb32(pb);
710         break;
711     case 0x3401:
712         mxf_read_pixel_layout(pb, descriptor);
713         break;
714     default:
715         /* Private uid used by SONY C0023S01.mxf */
716         if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
717             descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
718             if (!descriptor->extradata)
719                 return -1;
720             descriptor->extradata_size = size;
721             avio_read(pb, descriptor->extradata, size);
722         }
723         break;
724     }
725     return 0;
726 }
727
728 /*
729  * Match an uid independently of the version byte and up to len common bytes
730  * Returns: boolean
731  */
732 static int mxf_match_uid(const UID key, const UID uid, int len)
733 {
734     int i;
735     for (i = 0; i < len; i++) {
736         if (i != 7 && key[i] != uid[i])
737             return 0;
738     }
739     return 1;
740 }
741
742 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
743 {
744     while (uls->uid[0]) {
745         if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
746             break;
747         uls++;
748     }
749     return uls;
750 }
751
752 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
753 {
754     int i;
755
756     if (!strong_ref)
757         return NULL;
758     for (i = 0; i < mxf->metadata_sets_count; i++) {
759         if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
760             (type == AnyType || mxf->metadata_sets[i]->type == type)) {
761             return mxf->metadata_sets[i];
762         }
763     }
764     return NULL;
765 }
766
767 static const MXFCodecUL mxf_essence_container_uls[] = {
768     // video essence container uls
769     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
770     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14,    CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
771     // sound essence container uls
772     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
773     { { 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 */
774     { { 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 */
775     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      CODEC_ID_NONE },
776 };
777
778 static int mxf_parse_structural_metadata(MXFContext *mxf)
779 {
780     MXFPackage *material_package = NULL;
781     MXFPackage *temp_package = NULL;
782     int i, j, k;
783
784     av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
785     /* TODO: handle multiple material packages (OP3x) */
786     for (i = 0; i < mxf->packages_count; i++) {
787         material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
788         if (material_package) break;
789     }
790     if (!material_package) {
791         av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
792         return -1;
793     }
794
795     for (i = 0; i < material_package->tracks_count; i++) {
796         MXFPackage *source_package = NULL;
797         MXFTrack *material_track = NULL;
798         MXFTrack *source_track = NULL;
799         MXFTrack *temp_track = NULL;
800         MXFDescriptor *descriptor = NULL;
801         MXFStructuralComponent *component = NULL;
802         UID *essence_container_ul = NULL;
803         const MXFCodecUL *codec_ul = NULL;
804         const MXFCodecUL *container_ul = NULL;
805         AVStream *st;
806
807         if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
808             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
809             continue;
810         }
811
812         if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
813             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
814             continue;
815         }
816
817         /* TODO: handle multiple source clips */
818         for (j = 0; j < material_track->sequence->structural_components_count; j++) {
819             /* TODO: handle timecode component */
820             component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
821             if (!component)
822                 continue;
823
824             for (k = 0; k < mxf->packages_count; k++) {
825                 temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
826                 if (!temp_package)
827                     continue;
828                 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
829                     source_package = temp_package;
830                     break;
831                 }
832             }
833             if (!source_package) {
834                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source package found\n", material_track->track_id);
835                 break;
836             }
837             for (k = 0; k < source_package->tracks_count; k++) {
838                 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
839                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
840                     return -1;
841                 }
842                 if (temp_track->track_id == component->source_track_id) {
843                     source_track = temp_track;
844                     break;
845                 }
846             }
847             if (!source_track) {
848                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
849                 break;
850             }
851         }
852         if (!source_track)
853             continue;
854
855         st = av_new_stream(mxf->fc, source_track->track_id);
856         if (!st) {
857             av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
858             return -1;
859         }
860         st->priv_data = source_track;
861         st->duration = component->duration;
862         if (st->duration == -1)
863             st->duration = AV_NOPTS_VALUE;
864         st->start_time = component->start_position;
865         av_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
866
867         if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
868             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
869             return -1;
870         }
871
872         PRINT_KEY(mxf->fc, "data definition   ul", source_track->sequence->data_definition_ul);
873         codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
874         st->codec->codec_type = codec_ul->id;
875
876         source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
877         if (source_package->descriptor) {
878             if (source_package->descriptor->type == MultipleDescriptor) {
879                 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
880                     MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
881
882                     if (!sub_descriptor) {
883                         av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
884                         continue;
885                     }
886                     if (sub_descriptor->linked_track_id == source_track->track_id) {
887                         descriptor = sub_descriptor;
888                         break;
889                     }
890                 }
891             } else if (source_package->descriptor->type == Descriptor)
892                 descriptor = source_package->descriptor;
893         }
894         if (!descriptor) {
895             av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
896             continue;
897         }
898         PRINT_KEY(mxf->fc, "essence codec     ul", descriptor->essence_codec_ul);
899         PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
900         essence_container_ul = &descriptor->essence_container_ul;
901         /* HACK: replacing the original key with mxf_encrypted_essence_container
902          * is not allowed according to s429-6, try to find correct information anyway */
903         if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
904             av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
905             for (k = 0; k < mxf->metadata_sets_count; k++) {
906                 MXFMetadataSet *metadata = mxf->metadata_sets[k];
907                 if (metadata->type == CryptoContext) {
908                     essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
909                     break;
910                 }
911             }
912         }
913         /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
914         codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
915         st->codec->codec_id = codec_ul->id;
916         if (descriptor->extradata) {
917             st->codec->extradata = descriptor->extradata;
918             st->codec->extradata_size = descriptor->extradata_size;
919         }
920         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
921             container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
922             if (st->codec->codec_id == CODEC_ID_NONE)
923                 st->codec->codec_id = container_ul->id;
924             st->codec->width = descriptor->width;
925             st->codec->height = descriptor->height;
926             if (st->codec->codec_id == CODEC_ID_RAWVIDEO)
927                 st->codec->pix_fmt = descriptor->pix_fmt;
928             st->need_parsing = AVSTREAM_PARSE_HEADERS;
929         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
930             container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
931             if (st->codec->codec_id == CODEC_ID_NONE)
932                 st->codec->codec_id = container_ul->id;
933             st->codec->channels = descriptor->channels;
934             st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
935             st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
936             /* TODO: implement CODEC_ID_RAWAUDIO */
937             if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
938                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
939                     st->codec->codec_id = CODEC_ID_PCM_S24LE;
940                 else if (descriptor->bits_per_sample == 32)
941                     st->codec->codec_id = CODEC_ID_PCM_S32LE;
942             } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
943                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
944                     st->codec->codec_id = CODEC_ID_PCM_S24BE;
945                 else if (descriptor->bits_per_sample == 32)
946                     st->codec->codec_id = CODEC_ID_PCM_S32BE;
947             } else if (st->codec->codec_id == CODEC_ID_MP2) {
948                 st->need_parsing = AVSTREAM_PARSE_FULL;
949             }
950         }
951         if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
952             av_log(mxf->fc, AV_LOG_WARNING, "only frame wrapped mappings are correctly supported\n");
953             st->need_parsing = AVSTREAM_PARSE_FULL;
954         }
955     }
956     return 0;
957 }
958
959 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
960     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
961     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
962     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
963     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
964     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
965     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
966     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
967     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
968     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
969     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
970     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
971     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
972     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
973     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
974     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
975     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
976     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
977     { { 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 */
978     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
979     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
980     { { 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 */
981     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
982     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
983     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
984     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
985     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
986     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
987     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
988 };
989
990 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
991 {
992     AVIOContext *pb = mxf->fc->pb;
993     MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
994     uint64_t klv_end = avio_tell(pb) + klv->length;
995
996     if (!ctx)
997         return -1;
998     while (avio_tell(pb) + 4 < klv_end) {
999         int tag = avio_rb16(pb);
1000         int size = avio_rb16(pb); /* KLV specified by 0x53 */
1001         uint64_t next = avio_tell(pb) + size;
1002         UID uid = {0};
1003
1004         av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
1005         if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
1006             av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
1007             continue;
1008         }
1009         if (tag > 0x7FFF) { /* dynamic tag */
1010             int i;
1011             for (i = 0; i < mxf->local_tags_count; i++) {
1012                 int local_tag = AV_RB16(mxf->local_tags+i*18);
1013                 if (local_tag == tag) {
1014                     memcpy(uid, mxf->local_tags+i*18+2, 16);
1015                     av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
1016                     PRINT_KEY(mxf->fc, "uid", uid);
1017                 }
1018             }
1019         }
1020         if (ctx_size && tag == 0x3C0A)
1021             avio_read(pb, ctx->uid, 16);
1022         else if (read_child(ctx, pb, tag, size, uid) < 0)
1023             return -1;
1024
1025         avio_seek(pb, next, SEEK_SET);
1026     }
1027     if (ctx_size) ctx->type = type;
1028     return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
1029 }
1030
1031 static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
1032 {
1033     MXFContext *mxf = s->priv_data;
1034     KLVPacket klv;
1035
1036     if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
1037         av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
1038         return -1;
1039     }
1040     avio_seek(s->pb, -14, SEEK_CUR);
1041     mxf->fc = s;
1042     while (!url_feof(s->pb)) {
1043         const MXFMetadataReadTableEntry *metadata;
1044
1045         if (klv_read_packet(&klv, s->pb) < 0)
1046             return -1;
1047         PRINT_KEY(s, "read header", klv.key);
1048         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
1049         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
1050             IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
1051             /* FIXME avoid seek */
1052             avio_seek(s->pb, klv.offset, SEEK_SET);
1053             break;
1054         }
1055
1056         for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
1057             if (IS_KLV_KEY(klv.key, metadata->key)) {
1058                 int res;
1059                 if (klv.key[5] == 0x53) {
1060                     res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
1061                 } else {
1062                     uint64_t next = avio_tell(s->pb) + klv.length;
1063                     res = metadata->read(mxf, s->pb, 0, 0, klv.key);
1064                     avio_seek(s->pb, next, SEEK_SET);
1065                 }
1066                 if (res < 0) {
1067                     av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
1068                     return -1;
1069                 }
1070                 break;
1071             }
1072         }
1073         if (!metadata->read)
1074             avio_skip(s->pb, klv.length);
1075     }
1076     return mxf_parse_structural_metadata(mxf);
1077 }
1078
1079 static int mxf_read_close(AVFormatContext *s)
1080 {
1081     MXFContext *mxf = s->priv_data;
1082     int i;
1083
1084     av_freep(&mxf->packages_refs);
1085
1086     for (i = 0; i < s->nb_streams; i++)
1087         s->streams[i]->priv_data = NULL;
1088
1089     for (i = 0; i < mxf->metadata_sets_count; i++) {
1090         switch (mxf->metadata_sets[i]->type) {
1091         case MultipleDescriptor:
1092             av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
1093             break;
1094         case Sequence:
1095             av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
1096             break;
1097         case SourcePackage:
1098         case MaterialPackage:
1099             av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
1100             break;
1101         default:
1102             break;
1103         }
1104         av_freep(&mxf->metadata_sets[i]);
1105     }
1106     av_freep(&mxf->partitions);
1107     av_freep(&mxf->metadata_sets);
1108     av_freep(&mxf->aesc);
1109     av_freep(&mxf->local_tags);
1110     return 0;
1111 }
1112
1113 static int mxf_probe(AVProbeData *p) {
1114     uint8_t *bufp = p->buf;
1115     uint8_t *end = p->buf + p->buf_size;
1116
1117     if (p->buf_size < sizeof(mxf_header_partition_pack_key))
1118         return 0;
1119
1120     /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
1121     end -= sizeof(mxf_header_partition_pack_key);
1122     for (; bufp < end; bufp++) {
1123         if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
1124             return AVPROBE_SCORE_MAX;
1125     }
1126     return 0;
1127 }
1128
1129 /* rudimentary byte seek */
1130 /* XXX: use MXF Index */
1131 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1132 {
1133     AVStream *st = s->streams[stream_index];
1134     int64_t seconds;
1135
1136     if (!s->bit_rate)
1137         return -1;
1138     if (sample_time < 0)
1139         sample_time = 0;
1140     seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
1141     if (avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET) < 0)
1142         return -1;
1143     av_update_cur_dts(s, st, sample_time);
1144     return 0;
1145 }
1146
1147 AVInputFormat ff_mxf_demuxer = {
1148     .name           = "mxf",
1149     .long_name      = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1150     .priv_data_size = sizeof(MXFContext),
1151     .read_probe     = mxf_probe,
1152     .read_header    = mxf_read_header,
1153     .read_packet    = mxf_read_packet,
1154     .read_close     = mxf_read_close,
1155     .read_seek      = mxf_read_seek,
1156 };