parse SONY hidden MPEG-4 extradata, fix C0023S01.mxf
[ffmpeg.git] / libavformat / mxf.c
1 /*
2  * MXF demuxer.
3  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19
20 /*
21  * References
22  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
23  * SMPTE 377M MXF File Format Specifications
24  * SMPTE 378M Operational Pattern 1a
25  * SMPTE 379M MXF Generic Container
26  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
27  * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
28  * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
29  *
30  * Principle
31  * Search for Track numbers which will identify essence element KLV packets.
32  * Search for SourcePackage which define tracks which contains Track numbers.
33  * Material Package contains tracks with reference to SourcePackage tracks.
34  * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
35  * Assign Descriptors to correct Tracks.
36  *
37  * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
38  * Metadata parsing resolves Strong References to objects.
39  *
40  * Simple demuxer, only OP1A supported and some files might not work at all.
41  * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
42  */
43
44 //#define DEBUG
45
46 #include "avformat.h"
47
48 typedef uint8_t UID[16];
49
50 enum MXFMetadataSetType {
51     MaterialPackage,
52     SourcePackage,
53     SourceClip,
54     TimecodeComponent,
55     Sequence,
56     MultipleDescriptor,
57     Descriptor,
58     Track,
59     EssenceContainerData,
60 };
61
62 typedef struct MXFStructuralComponent {
63     UID uid;
64     enum MXFMetadataSetType type;
65     UID source_package_uid;
66     UID data_definition_ul;
67     int64_t duration;
68     int64_t start_position;
69     int source_track_id;
70 } MXFStructuralComponent;
71
72 typedef struct MXFSequence {
73     UID uid;
74     enum MXFMetadataSetType type;
75     UID data_definition_ul;
76     UID *structural_components_refs;
77     int structural_components_count;
78     int64_t duration;
79 } MXFSequence;
80
81 typedef struct MXFTrack {
82     UID uid;
83     enum MXFMetadataSetType type;
84     MXFSequence *sequence; /* mandatory, and only one */
85     UID sequence_ref;
86     int track_id;
87     uint8_t track_number[4];
88     AVRational edit_rate;
89 } MXFTrack;
90
91 typedef struct MXFDescriptor {
92     UID uid;
93     enum MXFMetadataSetType type;
94     UID essence_container_ul;
95     UID essence_codec_ul;
96     AVRational sample_rate;
97     AVRational aspect_ratio;
98     int width;
99     int height;
100     int channels;
101     int bits_per_sample;
102     UID *sub_descriptors_refs;
103     int sub_descriptors_count;
104     int linked_track_id;
105     uint8_t *extradata;
106     int extradata_size;
107 } MXFDescriptor;
108
109 typedef struct MXFPackage {
110     UID uid;
111     enum MXFMetadataSetType type;
112     UID package_uid;
113     UID *tracks_refs;
114     int tracks_count;
115     MXFDescriptor *descriptor; /* only one */
116     UID descriptor_ref;
117 } MXFPackage;
118
119 typedef struct MXFEssenceContainerData {
120     UID uid;
121     enum MXFMetadataSetType type;
122     UID linked_package_uid;
123 } MXFEssenceContainerData;
124
125 typedef struct {
126     UID uid;
127     enum MXFMetadataSetType type;
128 } MXFMetadataSet;
129
130 typedef struct MXFContext {
131     UID *packages_refs;
132     int packages_count;
133     UID *essence_container_data_sets_refs;
134     int essence_container_data_sets_count;
135     UID *essence_containers_uls; /* Universal Labels SMPTE RP224 */
136     int essence_containers_uls_count;
137     UID operational_pattern_ul;
138     UID content_storage_uid;
139     MXFMetadataSet **metadata_sets;
140     int metadata_sets_count;
141     AVFormatContext *fc;
142 } MXFContext;
143
144 typedef struct KLVPacket {
145     UID key;
146     offset_t offset;
147     uint64_t length;
148 } KLVPacket;
149
150 enum MXFWrappingScheme {
151     Frame,
152     Clip,
153 };
154
155 typedef struct MXFCodecUL {
156     UID uid;
157     enum CodecID id;
158     enum MXFWrappingScheme wrapping;
159 } MXFCodecUL;
160
161 typedef struct MXFMetadataReadTableEntry {
162     const UID key;
163     int (*read)(MXFContext *mxf, KLVPacket *klv);
164 } MXFMetadataReadTableEntry;
165
166 /* partial keys to match */
167 static const uint8_t mxf_header_partition_pack_key[]       = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
168 static const uint8_t mxf_essence_element_key[]             = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
169
170 static offset_t mxf_header_offset = 0;
171
172 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
173
174 #define PRINT_KEY(x) dprintf("%02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n", \
175                              (x)[0], (x)[1], (x)[2], (x)[3], (x)[4], (x)[5], (x)[6], (x)[7], (x)[8], (x)[9], (x)[10], (x)[11], (x)[12], (x)[13], (x)[14], (x)[15])
176
177 static int64_t klv_decode_ber_length(ByteIOContext *pb)
178 {
179     int64_t size = 0;
180     uint8_t length = get_byte(pb);
181     int type = length >> 7;
182
183     if (type) { /* long form */
184         int bytes_num = length & 0x7f;
185         /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
186         if (bytes_num > 8)
187             return -1;
188         while (bytes_num--)
189             size = size << 8 | get_byte(pb);
190     } else {
191         size = length & 0x7f;
192     }
193     return size;
194 }
195
196 static int klv_read_packet(KLVPacket *klv, ByteIOContext *pb)
197 {
198     klv->offset = url_ftell(pb);
199     get_buffer(pb, klv->key, 16);
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 -1;
215 }
216
217 static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
218 {
219     KLVPacket klv;
220
221     while (!url_feof(&s->pb)) {
222         if (klv_read_packet(&klv, &s->pb) < 0) {
223             av_log(s, AV_LOG_ERROR, "error reading KLV packet\n");
224             return -1;
225         }
226 #ifdef DEBUG
227         PRINT_KEY(klv.key);
228 #endif
229         if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
230             av_get_packet(&s->pb, pkt, klv.length);
231             pkt->stream_index = mxf_get_stream_index(s, &klv);
232             return pkt->stream_index == -1 ? -1 : 0;
233         } else
234             url_fskip(&s->pb, klv.length);
235     }
236     return AVERROR_IO;
237 }
238
239 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
240 {
241     mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
242     mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
243     mxf->metadata_sets_count++;
244     return 0;
245 }
246
247 static int mxf_read_metadata_preface(MXFContext *mxf, KLVPacket *klv)
248 {
249     ByteIOContext *pb = &mxf->fc->pb;
250     int bytes_read = 0;
251
252     while (bytes_read < klv->length) {
253         int tag = get_be16(pb);
254         int size = get_be16(pb); /* SMPTE 336M Table 8 KLV specified length, 0x53 */
255
256         switch (tag) {
257         case 0x3B03:
258             get_buffer(pb, mxf->content_storage_uid, 16);
259             break;
260         case 0x3B09:
261             get_buffer(pb, mxf->operational_pattern_ul, 16);
262             break;
263         case 0x3B0A:
264             mxf->essence_containers_uls_count = get_be32(pb);
265             if (mxf->essence_containers_uls_count >= UINT_MAX / sizeof(UID))
266                 return -1;
267             mxf->essence_containers_uls = av_malloc(mxf->essence_containers_uls_count * sizeof(UID));
268             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
269             get_buffer(pb, mxf->essence_containers_uls, mxf->essence_containers_uls_count * sizeof(UID));
270             break;
271         default:
272             url_fskip(pb, size);
273         }
274         bytes_read += size + 4;
275     }
276     return 0;
277 }
278
279 static int mxf_read_metadata_content_storage(MXFContext *mxf, KLVPacket *klv)
280 {
281     ByteIOContext *pb = &mxf->fc->pb;
282     int bytes_read = 0;
283
284     while (bytes_read < klv->length) {
285         int tag = get_be16(pb);
286         int size = get_be16(pb); /* SMPTE 336M Table 8 KLV specified length, 0x53 */
287
288         dprintf("tag 0x%04X, size %d\n", tag, size);
289         switch (tag) {
290         case 0x1901:
291             mxf->packages_count = get_be32(pb);
292             if (mxf->packages_count >= UINT_MAX / sizeof(UID))
293                 return -1;
294             mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
295             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
296             get_buffer(pb, mxf->packages_refs, mxf->packages_count * sizeof(UID));
297             break;
298         case 0x1902:
299             mxf->essence_container_data_sets_count = get_be32(pb);
300             if (mxf->essence_container_data_sets_count >= UINT_MAX / sizeof(UID))
301                 return -1;
302             mxf->essence_container_data_sets_refs = av_malloc(mxf->essence_container_data_sets_count * sizeof(UID));
303             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
304             get_buffer(pb, mxf->essence_container_data_sets_refs, mxf->essence_container_data_sets_count * sizeof(UID));
305             break;
306         default:
307             url_fskip(pb, size);
308         }
309         bytes_read += size + 4;
310     }
311     return 0;
312 }
313
314 static int mxf_read_metadata_source_clip(MXFContext *mxf, KLVPacket *klv)
315 {
316     ByteIOContext *pb = &mxf->fc->pb;
317     MXFStructuralComponent *source_clip = av_mallocz(sizeof(*source_clip));
318     int bytes_read = 0;
319
320     while (bytes_read < klv->length) {
321         int tag = get_be16(pb);
322         int size = get_be16(pb); /* SMPTE 336M Table 8 KLV specified length, 0x53 */
323
324         dprintf("tag 0x%04X, size %d\n", tag, size);
325         switch (tag) {
326         case 0x3C0A:
327             get_buffer(pb, source_clip->uid, 16);
328             break;
329         case 0x0202:
330             source_clip->duration = get_be64(pb);
331             break;
332         case 0x1201:
333             source_clip->start_position = get_be64(pb);
334             break;
335         case 0x1101:
336             /* UMID, only get last 16 bytes */
337             url_fskip(pb, 16);
338             get_buffer(pb, source_clip->source_package_uid, 16);
339             break;
340         case 0x1102:
341             source_clip->source_track_id = get_be32(pb);
342             break;
343         default:
344             url_fskip(pb, size);
345         }
346         bytes_read += size + 4;
347     }
348     source_clip->type = SourceClip;
349     return mxf_add_metadata_set(mxf, source_clip);
350 }
351
352 static int mxf_read_metadata_material_package(MXFContext *mxf, KLVPacket *klv)
353 {
354     ByteIOContext *pb = &mxf->fc->pb;
355     MXFPackage *package = av_mallocz(sizeof(*package));
356     int bytes_read = 0;
357
358     while (bytes_read < klv->length) {
359         int tag = get_be16(pb);
360         int size = get_be16(pb); /* KLV specified by 0x53 */
361
362         switch (tag) {
363         case 0x3C0A:
364             get_buffer(pb, package->uid, 16);
365             break;
366         case 0x4403:
367             package->tracks_count = get_be32(pb);
368             if (package->tracks_count >= UINT_MAX / sizeof(UID))
369                 return -1;
370             package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
371             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
372             get_buffer(pb, package->tracks_refs, package->tracks_count * sizeof(UID));
373             break;
374         default:
375             url_fskip(pb, size);
376         }
377         bytes_read += size + 4;
378     }
379     package->type = MaterialPackage;
380     return mxf_add_metadata_set(mxf, package);
381 }
382
383 static int mxf_read_metadata_track(MXFContext *mxf, KLVPacket *klv)
384 {
385     ByteIOContext *pb = &mxf->fc->pb;
386     MXFTrack *track = av_mallocz(sizeof(*track));
387     int bytes_read = 0;
388
389     while (bytes_read < klv->length) {
390         int tag = get_be16(pb);
391         int size = get_be16(pb); /* KLV specified by 0x53 */
392
393         dprintf("tag 0x%04X, size %d\n", tag, size);
394         switch (tag) {
395         case 0x3C0A:
396             get_buffer(pb, track->uid, 16);
397             break;
398         case 0x4801:
399             track->track_id = get_be32(pb);
400             break;
401         case 0x4804:
402             get_buffer(pb, track->track_number, 4);
403             break;
404         case 0x4B01:
405             track->edit_rate.den = get_be32(pb);
406             track->edit_rate.num = get_be32(pb);
407             break;
408         case 0x4803:
409             get_buffer(pb, track->sequence_ref, 16);
410             break;
411         default:
412             url_fskip(pb, size);
413         }
414         bytes_read += size + 4;
415     }
416     track->type = Track;
417     return mxf_add_metadata_set(mxf, track);
418 }
419
420 static int mxf_read_metadata_sequence(MXFContext *mxf, KLVPacket *klv)
421 {
422     ByteIOContext *pb = &mxf->fc->pb;
423     MXFSequence *sequence = av_mallocz(sizeof(*sequence));
424     int bytes_read = 0;
425
426     while (bytes_read < klv->length) {
427         int tag = get_be16(pb);
428         int size = get_be16(pb); /* KLV specified by 0x53 */
429
430         dprintf("tag 0x%04X, size %d\n", tag, size);
431         switch (tag) {
432         case 0x3C0A:
433             get_buffer(pb, sequence->uid, 16);
434             break;
435         case 0x0202:
436             sequence->duration = get_be64(pb);
437             break;
438         case 0x0201:
439             get_buffer(pb, sequence->data_definition_ul, 16);
440             break;
441         case 0x1001:
442             sequence->structural_components_count = get_be32(pb);
443             if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
444                 return -1;
445             sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
446             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
447             get_buffer(pb, sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
448             break;
449         default:
450             url_fskip(pb, size);
451         }
452         bytes_read += size + 4;
453     }
454     sequence->type = Sequence;
455     return mxf_add_metadata_set(mxf, sequence);
456 }
457
458 static int mxf_read_metadata_source_package(MXFContext *mxf, KLVPacket *klv)
459 {
460     ByteIOContext *pb = &mxf->fc->pb;
461     MXFPackage *package = av_mallocz(sizeof(*package));
462     int bytes_read = 0;
463
464     while (bytes_read < klv->length) {
465         int tag = get_be16(pb);
466         int size = get_be16(pb); /* KLV specified by 0x53 */
467
468         dprintf("tag 0x%04X, size %d\n", tag, size);
469         switch (tag) {
470         case 0x3C0A:
471             get_buffer(pb, package->uid, 16);
472             break;
473         case 0x4403:
474             package->tracks_count = get_be32(pb);
475             if (package->tracks_count >= UINT_MAX / sizeof(UID))
476                 return -1;
477             package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
478             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
479             get_buffer(pb, package->tracks_refs, package->tracks_count * sizeof(UID));
480             break;
481         case 0x4401:
482             /* UMID, only get last 16 bytes */
483             url_fskip(pb, 16);
484             get_buffer(pb, package->package_uid, 16);
485             break;
486         case 0x4701:
487             get_buffer(pb, package->descriptor_ref, 16);
488             break;
489         default:
490             url_fskip(pb, size);
491         }
492         bytes_read += size + 4;
493     }
494     package->type = SourcePackage;
495     return mxf_add_metadata_set(mxf, package);
496 }
497
498 static int mxf_read_metadata_multiple_descriptor(MXFContext *mxf, KLVPacket *klv)
499 {
500     ByteIOContext *pb = &mxf->fc->pb;
501     MXFDescriptor *descriptor = av_mallocz(sizeof(*descriptor));
502     int bytes_read = 0;
503
504     while (bytes_read < klv->length) {
505         int tag = get_be16(pb);
506         int size = get_be16(pb); /* KLV specified by 0x53 */
507
508         dprintf("tag 0x%04X, size %d\n", tag, size);
509         switch (tag) {
510         case 0x3C0A:
511             get_buffer(pb, descriptor->uid, 16);
512             break;
513         case 0x3F01:
514             descriptor->sub_descriptors_count = get_be32(pb);
515             if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
516                 return -1;
517             descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
518             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
519             get_buffer(pb, descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
520             break;
521         default:
522             url_fskip(pb, size);
523         }
524         bytes_read += size + 4;
525     }
526     descriptor->type = MultipleDescriptor;
527     return mxf_add_metadata_set(mxf, descriptor);
528 }
529
530 static void mxf_read_metadata_pixel_layout(ByteIOContext *pb, MXFDescriptor *descriptor)
531 {
532     int code;
533
534     do {
535         code = get_byte(pb);
536         dprintf("pixel layout: code 0x%x\n", code);
537         switch (code) {
538         case 0x52: /* R */
539             descriptor->bits_per_sample += get_byte(pb);
540             break;
541         case 0x47: /* G */
542             descriptor->bits_per_sample += get_byte(pb);
543             break;
544         case 0x42: /* B */
545             descriptor->bits_per_sample += get_byte(pb);
546             break;
547         default:
548             get_byte(pb);
549         }
550     } while (code != 0); /* SMPTE 377M E.2.46 */
551 }
552
553 static int mxf_read_metadata_generic_descriptor(MXFContext *mxf, KLVPacket *klv)
554 {
555     ByteIOContext *pb = &mxf->fc->pb;
556     MXFDescriptor *descriptor = av_mallocz(sizeof(*descriptor));
557     int bytes_read = 0;
558
559     while (bytes_read < klv->length) {
560         int tag = get_be16(pb);
561         int size = get_be16(pb); /* KLV specified by 0x53 */
562
563         dprintf("tag 0x%04X, size %d\n", tag, size);
564         switch (tag) {
565         case 0x3C0A:
566             get_buffer(pb, descriptor->uid, 16);
567             break;
568         case 0x3004:
569             get_buffer(pb, descriptor->essence_container_ul, 16);
570             break;
571         case 0x3006:
572             descriptor->linked_track_id = get_be32(pb);
573             break;
574         case 0x3201: /* PictureEssenceCoding */
575             get_buffer(pb, descriptor->essence_codec_ul, 16);
576             break;
577         case 0x3203:
578             descriptor->width = get_be32(pb);
579             break;
580         case 0x3202:
581             descriptor->height = get_be32(pb);
582             break;
583         case 0x320E:
584             descriptor->aspect_ratio.num = get_be32(pb);
585             descriptor->aspect_ratio.den = get_be32(pb);
586             break;
587         case 0x3D03:
588             descriptor->sample_rate.num = get_be32(pb);
589             descriptor->sample_rate.den = get_be32(pb);
590             break;
591         case 0x3D06: /* SoundEssenceCompression */
592             get_buffer(pb, descriptor->essence_codec_ul, 16);
593             break;
594         case 0x3D07:
595             descriptor->channels = get_be32(pb);
596             break;
597         case 0x3D01:
598             descriptor->bits_per_sample = get_be32(pb);
599             break;
600         case 0x3401:
601             mxf_read_metadata_pixel_layout(pb, descriptor);
602             break;
603         case 0x8201: /* Private tag used by SONY C0023S01.mxf */
604             descriptor->extradata = av_malloc(size);
605             descriptor->extradata_size = size;
606             get_buffer(pb, descriptor->extradata, size);
607             break;
608         default:
609             url_fskip(pb, size);
610         }
611         bytes_read += size + 4;
612     }
613     descriptor->type = Descriptor;
614     return mxf_add_metadata_set(mxf, descriptor);
615 }
616
617 /* SMPTE RP224 http://www.smpte-ra.org/mdd/index.html */
618 static const UID picture_essence_track_ul = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x01,0x03,0x02,0x02,0x01,0x00,0x00,0x00 };
619 static const UID sound_essence_track_ul   = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x01,0x03,0x02,0x02,0x02,0x00,0x00,0x00 };
620
621 static const MXFCodecUL mxf_codec_uls[] = {
622     /* PictureEssenceCoding */
623     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* 422P@ML I-Frame */
624     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* 422P@HL Long GoP */
625     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* MP@ML Long GoP */
626     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* 422P@ML Long GoP */
627     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* MP@HL Long GoP */
628     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x20,0x02,0x03 },      CODEC_ID_MPEG4, Frame }, /* XDCAM proxy_pal030926.mxf */
629     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x20,0x02,0x04 },      CODEC_ID_MPEG4, Frame }, /* XDCAM Proxy C0023S01.mxf */
630     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x05 }, CODEC_ID_MPEG2VIDEO, Frame }, /* D-10 30Mbps PAL */
631     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 }, CODEC_ID_MPEG2VIDEO, Frame }, /* D-10 50Mbps PAL */
632     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x04,0x00 },    CODEC_ID_DVVIDEO, Frame }, /* DVCPRO50 PAL */
633     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x02,0x00 },    CODEC_ID_DVVIDEO, Frame }, /* DVCPRO25 PAL */
634     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x02,0x00 },    CODEC_ID_DVVIDEO, Frame }, /* DV25 IEC PAL */
635   //{ { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 },     CODEC_ID_JPEG2K, Frame }, /* JPEG2000 Codestream */
636     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x01,0x7F,0x00,0x00,0x00 },   CODEC_ID_RAWVIDEO, Frame }, /* Uncompressed */
637     /* SoundEssenceCompression */
638     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },  CODEC_ID_PCM_S16LE, Frame }, /* Uncompressed */
639     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x7F,0x00,0x00,0x00 },  CODEC_ID_PCM_S16LE, Frame },
640     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x07,0x04,0x02,0x02,0x01,0x7E,0x00,0x00,0x00 },  CODEC_ID_PCM_S16BE, Frame }, /* From Omneon MXF file */
641     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x01,0x01,0x00 },   CODEC_ID_PCM_ALAW, Frame },
642     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x04,0x04,0x02,0x02,0x02,0x03,0x01,0x01,0x00 },   CODEC_ID_PCM_ALAW, Frame }, /* XDCAM Proxy C0023S01.mxf */
643     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x01,0x00 },        CODEC_ID_AC3, Frame },
644     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x05,0x00 },        CODEC_ID_MP2, Frame }, /* MP2 or MP3 */
645   //{ { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x1C,0x00 },    CODEC_ID_DOLBY_E, Frame }, /* Dolby-E */
646     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },       CODEC_ID_NONE, Frame },
647 };
648
649 static const MXFCodecUL mxf_picture_essence_container_uls[] = {
650     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, CODEC_ID_MPEG2VIDEO, Frame }, /* MPEG-ES Frame wrapped */
651     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0xe0,0x02 }, CODEC_ID_MPEG2VIDEO,  Clip }, /* MPEG-ES Clip wrapped, 0xe0 MPV stream id */
652     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x04,0x61,0x07 }, CODEC_ID_MPEG2VIDEO,  Clip }, /* MPEG-ES Custom wrapped, 0x61 ??? stream id */
653     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },       CODEC_ID_NONE, Frame },
654 };
655
656 static const MXFCodecUL mxf_sound_essence_container_uls[] = {
657     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },  CODEC_ID_PCM_S16LE, Frame }, /* BWF Frame wrapped */
658     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },  CODEC_ID_PCM_S16LE, Frame }, /* AES Frame wrapped */
659     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x40,0x01 },        CODEC_ID_MP2, Frame }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */
660     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0xc0,0x01 },        CODEC_ID_MP2, Frame }, /* MPEG-ES Frame wrapped, 0xc0 MPA stream id */
661     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0xc0,0x02 },        CODEC_ID_MP2,  Clip }, /* MPEG-ES Clip wrapped, 0xc0 MPA stream id */
662   //{ { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 },   CODEC_ID_PCM_AES3, Frame }, /* D-10 Mapping 30Mbps PAL Extended Template */
663     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },       CODEC_ID_NONE, Frame },
664 };
665
666 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
667 {
668     while (uls->id != CODEC_ID_NONE) {
669         if(!memcmp(uls->uid, *uid, 16))
670             break;
671         uls++;
672     }
673     return uls;
674 }
675
676 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref)
677 {
678     int i;
679
680     if (!strong_ref)
681         return NULL;
682     for (i = 0; i < mxf->metadata_sets_count; i++) {
683         if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16)) {
684             return mxf->metadata_sets[i];
685         }
686     }
687     return NULL;
688 }
689
690 static int mxf_parse_structural_metadata(MXFContext *mxf)
691 {
692     MXFPackage *material_package = NULL;
693     MXFPackage *source_package = NULL;
694     MXFPackage *temp_package = NULL;
695     int i, j, k;
696
697     dprintf("metadata sets count %d\n", mxf->metadata_sets_count);
698     /* TODO: handle multiple material packages (OP3x) */
699     for (i = 0; i < mxf->packages_count; i++) {
700         if (!(temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i]))) {
701             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve package strong ref\n");
702             return -1;
703         }
704         if (temp_package->type == MaterialPackage) {
705             material_package = temp_package;
706             break;
707         }
708     }
709     if (!material_package) {
710         av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
711         return -1;
712     }
713
714     for (i = 0; i < material_package->tracks_count; i++) {
715         MXFTrack *material_track = NULL;
716         MXFTrack *source_track = NULL;
717         MXFTrack *temp_track = NULL;
718         MXFDescriptor *descriptor = NULL;
719         MXFStructuralComponent *component = NULL;
720         const MXFCodecUL *codec_ul = NULL;
721         const MXFCodecUL *container_ul = NULL;
722         AVStream *st;
723
724         if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i]))) {
725             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
726             continue;
727         }
728
729         if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref))) {
730             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
731             return -1;
732         }
733
734         /* TODO: handle multiple source clips */
735         for (j = 0; j < material_track->sequence->structural_components_count; j++) {
736             /* TODO: handle timecode component */
737             component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j]);
738             if (!component || component->type != SourceClip)
739                 continue;
740
741             for (k = 0; k < mxf->packages_count; k++) {
742                 if (!(temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k]))) {
743                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
744                     return -1;
745                 }
746                 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
747                     source_package = temp_package;
748                     break;
749                 }
750             }
751             if (!source_package) {
752                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source package found\n", material_track->track_id);
753                 break;
754             }
755             for (k = 0; k < source_package->tracks_count; k++) {
756                 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k]))) {
757                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
758                     return -1;
759                 }
760                 if (temp_track->track_id == component->source_track_id) {
761                     source_track = temp_track;
762                     break;
763                 }
764             }
765             if (!source_track) {
766                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
767                 break;
768             }
769         }
770         if (!source_track)
771             continue;
772
773         st = av_new_stream(mxf->fc, source_track->track_id);
774         st->priv_data = source_track;
775         st->duration = component->duration;
776         if (st->duration == -1)
777             st->duration = AV_NOPTS_VALUE;
778         st->start_time = component->start_position;
779         av_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
780
781         if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref))) {
782             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
783             return -1;
784         }
785
786 #ifdef DEBUG
787         PRINT_KEY(source_track->sequence->data_definition_ul);
788 #endif
789         if (!memcmp(source_track->sequence->data_definition_ul, picture_essence_track_ul, 16))
790             st->codec->codec_type = CODEC_TYPE_VIDEO;
791         else if (!memcmp(source_track->sequence->data_definition_ul, sound_essence_track_ul, 16))
792             st->codec->codec_type = CODEC_TYPE_AUDIO;
793         else
794             st->codec->codec_type = CODEC_TYPE_DATA;
795
796         source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref);
797         if (source_package->descriptor) {
798             if (source_package->descriptor->type == MultipleDescriptor) {
799                 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
800                     MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j]);
801
802                     if (!sub_descriptor) {
803                         av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
804                         continue;
805                     }
806                     if (sub_descriptor->linked_track_id == source_track->track_id) {
807                         descriptor = sub_descriptor;
808                         break;
809                     }
810                 }
811             } else
812                 descriptor = source_package->descriptor;
813         }
814         if (!descriptor) {
815             av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
816             continue;
817         }
818 #ifdef DEBUG
819         PRINT_KEY(descriptor->essence_codec_ul);
820         PRINT_KEY(descriptor->essence_container_ul);
821 #endif
822         /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
823         codec_ul = mxf_get_codec_ul(mxf_codec_uls, &descriptor->essence_codec_ul);
824         st->codec->codec_id = codec_ul->id;
825         if (descriptor->extradata) {
826             st->codec->extradata = descriptor->extradata;
827             st->codec->extradata_size = descriptor->extradata_size;
828         }
829         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
830             container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, &descriptor->essence_container_ul);
831             if (st->codec->codec_id == CODEC_ID_NONE)
832                 st->codec->codec_id = container_ul->id;
833             st->codec->width = descriptor->width;
834             st->codec->height = descriptor->height;
835             st->codec->bits_per_sample = descriptor->bits_per_sample; /* Uncompressed */
836         } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
837             container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, &descriptor->essence_container_ul);
838             if (st->codec->codec_id == CODEC_ID_NONE)
839                 st->codec->codec_id = container_ul->id;
840             st->codec->channels = descriptor->channels;
841             st->codec->bits_per_sample = descriptor->bits_per_sample;
842             st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
843             /* TODO: implement CODEC_ID_RAWAUDIO */
844             if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
845                 if (descriptor->bits_per_sample == 24)
846                     st->codec->codec_id = CODEC_ID_PCM_S24LE;
847                 else if (descriptor->bits_per_sample == 32)
848                     st->codec->codec_id = CODEC_ID_PCM_S32LE;
849             } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
850                 if (descriptor->bits_per_sample == 24)
851                     st->codec->codec_id = CODEC_ID_PCM_S24BE;
852                 else if (descriptor->bits_per_sample == 32)
853                     st->codec->codec_id = CODEC_ID_PCM_S32BE;
854             }
855         }
856         if (container_ul && container_ul->wrapping == Clip) {
857             dprintf("stream %d: clip wrapped essence\n", st->index);
858             st->need_parsing = 1;
859         }
860     }
861     return 0;
862 }
863
864 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
865     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2F,0x00 }, mxf_read_metadata_preface },
866     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_metadata_content_storage },
867     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_metadata_source_package },
868     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_metadata_material_package },
869     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_metadata_sequence },
870     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_metadata_source_clip },
871     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_metadata_multiple_descriptor },
872     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_metadata_generic_descriptor }, /* Generic Sound */
873     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_metadata_generic_descriptor }, /* CDCI */
874     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_metadata_generic_descriptor }, /* RGBA */
875     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_metadata_generic_descriptor }, /* MPEG 2 Video */
876     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_metadata_generic_descriptor }, /* Wave */
877     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_metadata_generic_descriptor }, /* AES3 */
878     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_metadata_track }, /* Static Track */
879     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_metadata_track }, /* Generic Track */
880     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL },
881 };
882
883 static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
884 {
885     MXFContext *mxf = s->priv_data;
886     KLVPacket klv;
887
888     mxf->fc = s;
889     dprintf("header offset %llx\n", mxf_header_offset);
890     if (url_fseek(&s->pb, mxf_header_offset, SEEK_SET) < 0) {
891         av_log(s, AV_LOG_ERROR, "error seeking to header offset\n");
892         return -1;
893     }
894     while (!url_feof(&s->pb)) {
895         const MXFMetadataReadTableEntry *function;
896
897         if (klv_read_packet(&klv, &s->pb) < 0) {
898             av_log(s, AV_LOG_ERROR, "error reading KLV packet\n");
899             return -1;
900         }
901 #ifdef DEBUG
902         PRINT_KEY(klv.key);
903 #endif
904         if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
905             /* FIXME avoid seek */
906             url_fseek(&s->pb, klv.offset, SEEK_SET);
907             break;
908         }
909
910         for (function = mxf_metadata_read_table; function->read; function++) {
911             if (IS_KLV_KEY(klv.key, function->key)) {
912                 if (function->read(mxf, &klv) < 0) {
913                     av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
914                     return -1;
915                 }
916                 break;
917             }
918         }
919         if (!function->read)
920             url_fskip(&s->pb, klv.length);
921     }
922     return mxf_parse_structural_metadata(mxf);
923 }
924
925 static int mxf_read_close(AVFormatContext *s)
926 {
927     MXFContext *mxf = s->priv_data;
928     int i;
929
930     av_freep(&mxf->packages_refs);
931     av_freep(&mxf->essence_container_data_sets_refs);
932     av_freep(&mxf->essence_containers_uls);
933     for (i = 0; i < mxf->metadata_sets_count; i++) {
934         switch (mxf->metadata_sets[i]->type) {
935         case MultipleDescriptor:
936             av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
937             break;
938         case Sequence:
939             av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
940             break;
941         case SourcePackage:
942         case MaterialPackage:
943             av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
944             break;
945         default:
946             break;
947         }
948         av_freep(&mxf->metadata_sets[i]);
949     }
950     av_freep(&mxf->metadata_sets);
951     return 0;
952 }
953
954 static int mxf_probe(AVProbeData *p) {
955     uint8_t *bufp = p->buf;
956     uint8_t *end = p->buf + p->buf_size;
957
958     if (p->buf_size < sizeof(mxf_header_partition_pack_key))
959         return 0;
960
961     /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
962     end -= sizeof(mxf_header_partition_pack_key);
963     for (; bufp < end; bufp++) {
964         if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key)) {
965             mxf_header_offset = bufp - p->buf;
966             return AVPROBE_SCORE_MAX;
967         }
968     }
969     return 0;
970 }
971
972
973 AVInputFormat mxf_demuxer = {
974     "mxf",
975     "MXF format",
976     sizeof(MXFContext),
977     mxf_probe,
978     mxf_read_header,
979     mxf_read_packet,
980     mxf_read_close,
981     NULL,
982 };