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