use packet dts as correct media field number and use av_interleave_pkt_per_dts
[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 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
171
172 #define PRINT_KEY(x) dprintf("%02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n", \
173                              (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])
174
175 static int64_t klv_decode_ber_length(ByteIOContext *pb)
176 {
177     int64_t size = 0;
178     uint8_t length = get_byte(pb);
179     int type = length >> 7;
180
181     if (type) { /* long form */
182         int bytes_num = length & 0x7f;
183         /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
184         if (bytes_num > 8)
185             return -1;
186         while (bytes_num--)
187             size = size << 8 | get_byte(pb);
188     } else {
189         size = length & 0x7f;
190     }
191     return size;
192 }
193
194 static int klv_read_packet(KLVPacket *klv, ByteIOContext *pb)
195 {
196     klv->offset = url_ftell(pb);
197     get_buffer(pb, klv->key, 16);
198     klv->length = klv_decode_ber_length(pb);
199     return klv->length == -1 ? -1 : 0;
200 }
201
202 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
203 {
204     int i;
205
206     for (i = 0; i < s->nb_streams; i++) {
207         MXFTrack *track = s->streams[i]->priv_data;
208          /* SMPTE 379M 7.3 */
209         if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
210             return i;
211     }
212     return -1;
213 }
214
215 static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
216 {
217     KLVPacket klv;
218
219     while (!url_feof(&s->pb)) {
220         if (klv_read_packet(&klv, &s->pb) < 0) {
221             av_log(s, AV_LOG_ERROR, "error reading KLV packet\n");
222             return -1;
223         }
224 #ifdef DEBUG
225         PRINT_KEY(klv.key);
226 #endif
227         if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
228             av_get_packet(&s->pb, pkt, klv.length);
229             pkt->stream_index = mxf_get_stream_index(s, &klv);
230             return pkt->stream_index == -1 ? -1 : 0;
231         } else
232             url_fskip(&s->pb, klv.length);
233     }
234     return AVERROR_IO;
235 }
236
237 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
238 {
239     mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
240     mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
241     mxf->metadata_sets_count++;
242     return 0;
243 }
244
245 static int mxf_read_metadata_preface(MXFContext *mxf, KLVPacket *klv)
246 {
247     ByteIOContext *pb = &mxf->fc->pb;
248     int bytes_read = 0;
249
250     while (bytes_read < klv->length) {
251         int tag = get_be16(pb);
252         int size = get_be16(pb); /* SMPTE 336M Table 8 KLV specified length, 0x53 */
253
254         switch (tag) {
255         case 0x3B03:
256             get_buffer(pb, mxf->content_storage_uid, 16);
257             break;
258         case 0x3B09:
259             get_buffer(pb, mxf->operational_pattern_ul, 16);
260             break;
261         case 0x3B0A:
262             mxf->essence_containers_uls_count = get_be32(pb);
263             if (mxf->essence_containers_uls_count >= UINT_MAX / sizeof(UID))
264                 return -1;
265             mxf->essence_containers_uls = av_malloc(mxf->essence_containers_uls_count * sizeof(UID));
266             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
267             get_buffer(pb, mxf->essence_containers_uls, mxf->essence_containers_uls_count * sizeof(UID));
268             break;
269         default:
270             url_fskip(pb, size);
271         }
272         bytes_read += size + 4;
273     }
274     return 0;
275 }
276
277 static int mxf_read_metadata_content_storage(MXFContext *mxf, KLVPacket *klv)
278 {
279     ByteIOContext *pb = &mxf->fc->pb;
280     int bytes_read = 0;
281
282     while (bytes_read < klv->length) {
283         int tag = get_be16(pb);
284         int size = get_be16(pb); /* SMPTE 336M Table 8 KLV specified length, 0x53 */
285
286         dprintf("tag 0x%04X, size %d\n", tag, size);
287         switch (tag) {
288         case 0x1901:
289             mxf->packages_count = get_be32(pb);
290             if (mxf->packages_count >= UINT_MAX / sizeof(UID))
291                 return -1;
292             mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
293             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
294             get_buffer(pb, mxf->packages_refs, mxf->packages_count * sizeof(UID));
295             break;
296         case 0x1902:
297             mxf->essence_container_data_sets_count = get_be32(pb);
298             if (mxf->essence_container_data_sets_count >= UINT_MAX / sizeof(UID))
299                 return -1;
300             mxf->essence_container_data_sets_refs = av_malloc(mxf->essence_container_data_sets_count * sizeof(UID));
301             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
302             get_buffer(pb, mxf->essence_container_data_sets_refs, mxf->essence_container_data_sets_count * sizeof(UID));
303             break;
304         default:
305             url_fskip(pb, size);
306         }
307         bytes_read += size + 4;
308     }
309     return 0;
310 }
311
312 static int mxf_read_metadata_source_clip(MXFContext *mxf, KLVPacket *klv)
313 {
314     ByteIOContext *pb = &mxf->fc->pb;
315     MXFStructuralComponent *source_clip = av_mallocz(sizeof(*source_clip));
316     int bytes_read = 0;
317
318     while (bytes_read < klv->length) {
319         int tag = get_be16(pb);
320         int size = get_be16(pb); /* SMPTE 336M Table 8 KLV specified length, 0x53 */
321
322         dprintf("tag 0x%04X, size %d\n", tag, size);
323         switch (tag) {
324         case 0x3C0A:
325             get_buffer(pb, source_clip->uid, 16);
326             break;
327         case 0x0202:
328             source_clip->duration = get_be64(pb);
329             break;
330         case 0x1201:
331             source_clip->start_position = get_be64(pb);
332             break;
333         case 0x1101:
334             /* UMID, only get last 16 bytes */
335             url_fskip(pb, 16);
336             get_buffer(pb, source_clip->source_package_uid, 16);
337             break;
338         case 0x1102:
339             source_clip->source_track_id = get_be32(pb);
340             break;
341         default:
342             url_fskip(pb, size);
343         }
344         bytes_read += size + 4;
345     }
346     source_clip->type = SourceClip;
347     return mxf_add_metadata_set(mxf, source_clip);
348 }
349
350 static int mxf_read_metadata_material_package(MXFContext *mxf, KLVPacket *klv)
351 {
352     ByteIOContext *pb = &mxf->fc->pb;
353     MXFPackage *package = av_mallocz(sizeof(*package));
354     int bytes_read = 0;
355
356     while (bytes_read < klv->length) {
357         int tag = get_be16(pb);
358         int size = get_be16(pb); /* KLV specified by 0x53 */
359
360         switch (tag) {
361         case 0x3C0A:
362             get_buffer(pb, package->uid, 16);
363             break;
364         case 0x4403:
365             package->tracks_count = get_be32(pb);
366             if (package->tracks_count >= UINT_MAX / sizeof(UID))
367                 return -1;
368             package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
369             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
370             get_buffer(pb, package->tracks_refs, package->tracks_count * sizeof(UID));
371             break;
372         default:
373             url_fskip(pb, size);
374         }
375         bytes_read += size + 4;
376     }
377     package->type = MaterialPackage;
378     return mxf_add_metadata_set(mxf, package);
379 }
380
381 static int mxf_read_metadata_track(MXFContext *mxf, KLVPacket *klv)
382 {
383     ByteIOContext *pb = &mxf->fc->pb;
384     MXFTrack *track = av_mallocz(sizeof(*track));
385     int bytes_read = 0;
386
387     while (bytes_read < klv->length) {
388         int tag = get_be16(pb);
389         int size = get_be16(pb); /* KLV specified by 0x53 */
390
391         dprintf("tag 0x%04X, size %d\n", tag, size);
392         switch (tag) {
393         case 0x3C0A:
394             get_buffer(pb, track->uid, 16);
395             break;
396         case 0x4801:
397             track->track_id = get_be32(pb);
398             break;
399         case 0x4804:
400             get_buffer(pb, track->track_number, 4);
401             break;
402         case 0x4B01:
403             track->edit_rate.den = get_be32(pb);
404             track->edit_rate.num = get_be32(pb);
405             break;
406         case 0x4803:
407             get_buffer(pb, track->sequence_ref, 16);
408             break;
409         default:
410             url_fskip(pb, size);
411         }
412         bytes_read += size + 4;
413     }
414     track->type = Track;
415     return mxf_add_metadata_set(mxf, track);
416 }
417
418 static int mxf_read_metadata_sequence(MXFContext *mxf, KLVPacket *klv)
419 {
420     ByteIOContext *pb = &mxf->fc->pb;
421     MXFSequence *sequence = av_mallocz(sizeof(*sequence));
422     int bytes_read = 0;
423
424     while (bytes_read < klv->length) {
425         int tag = get_be16(pb);
426         int size = get_be16(pb); /* KLV specified by 0x53 */
427
428         dprintf("tag 0x%04X, size %d\n", tag, size);
429         switch (tag) {
430         case 0x3C0A:
431             get_buffer(pb, sequence->uid, 16);
432             break;
433         case 0x0202:
434             sequence->duration = get_be64(pb);
435             break;
436         case 0x0201:
437             get_buffer(pb, sequence->data_definition_ul, 16);
438             break;
439         case 0x1001:
440             sequence->structural_components_count = get_be32(pb);
441             if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
442                 return -1;
443             sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
444             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
445             get_buffer(pb, sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
446             break;
447         default:
448             url_fskip(pb, size);
449         }
450         bytes_read += size + 4;
451     }
452     sequence->type = Sequence;
453     return mxf_add_metadata_set(mxf, sequence);
454 }
455
456 static int mxf_read_metadata_source_package(MXFContext *mxf, KLVPacket *klv)
457 {
458     ByteIOContext *pb = &mxf->fc->pb;
459     MXFPackage *package = av_mallocz(sizeof(*package));
460     int bytes_read = 0;
461
462     while (bytes_read < klv->length) {
463         int tag = get_be16(pb);
464         int size = get_be16(pb); /* KLV specified by 0x53 */
465
466         dprintf("tag 0x%04X, size %d\n", tag, size);
467         switch (tag) {
468         case 0x3C0A:
469             get_buffer(pb, package->uid, 16);
470             break;
471         case 0x4403:
472             package->tracks_count = get_be32(pb);
473             if (package->tracks_count >= UINT_MAX / sizeof(UID))
474                 return -1;
475             package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
476             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
477             get_buffer(pb, package->tracks_refs, package->tracks_count * sizeof(UID));
478             break;
479         case 0x4401:
480             /* UMID, only get last 16 bytes */
481             url_fskip(pb, 16);
482             get_buffer(pb, package->package_uid, 16);
483             break;
484         case 0x4701:
485             get_buffer(pb, package->descriptor_ref, 16);
486             break;
487         default:
488             url_fskip(pb, size);
489         }
490         bytes_read += size + 4;
491     }
492     package->type = SourcePackage;
493     return mxf_add_metadata_set(mxf, package);
494 }
495
496 static int mxf_read_metadata_multiple_descriptor(MXFContext *mxf, KLVPacket *klv)
497 {
498     ByteIOContext *pb = &mxf->fc->pb;
499     MXFDescriptor *descriptor = av_mallocz(sizeof(*descriptor));
500     int bytes_read = 0;
501
502     while (bytes_read < klv->length) {
503         int tag = get_be16(pb);
504         int size = get_be16(pb); /* KLV specified by 0x53 */
505
506         dprintf("tag 0x%04X, size %d\n", tag, size);
507         switch (tag) {
508         case 0x3C0A:
509             get_buffer(pb, descriptor->uid, 16);
510             break;
511         case 0x3F01:
512             descriptor->sub_descriptors_count = get_be32(pb);
513             if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
514                 return -1;
515             descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
516             url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */
517             get_buffer(pb, descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
518             break;
519         default:
520             url_fskip(pb, size);
521         }
522         bytes_read += size + 4;
523     }
524     descriptor->type = MultipleDescriptor;
525     return mxf_add_metadata_set(mxf, descriptor);
526 }
527
528 static void mxf_read_metadata_pixel_layout(ByteIOContext *pb, MXFDescriptor *descriptor)
529 {
530     int code;
531
532     do {
533         code = get_byte(pb);
534         dprintf("pixel layout: code 0x%x\n", code);
535         switch (code) {
536         case 0x52: /* R */
537             descriptor->bits_per_sample += get_byte(pb);
538             break;
539         case 0x47: /* G */
540             descriptor->bits_per_sample += get_byte(pb);
541             break;
542         case 0x42: /* B */
543             descriptor->bits_per_sample += get_byte(pb);
544             break;
545         default:
546             get_byte(pb);
547         }
548     } while (code != 0); /* SMPTE 377M E.2.46 */
549 }
550
551 static int mxf_read_metadata_generic_descriptor(MXFContext *mxf, KLVPacket *klv)
552 {
553     ByteIOContext *pb = &mxf->fc->pb;
554     MXFDescriptor *descriptor = av_mallocz(sizeof(*descriptor));
555     int bytes_read = 0;
556
557     while (bytes_read < klv->length) {
558         int tag = get_be16(pb);
559         int size = get_be16(pb); /* KLV specified by 0x53 */
560
561         dprintf("tag 0x%04X, size %d\n", tag, size);
562         switch (tag) {
563         case 0x3C0A:
564             get_buffer(pb, descriptor->uid, 16);
565             break;
566         case 0x3004:
567             get_buffer(pb, descriptor->essence_container_ul, 16);
568             break;
569         case 0x3006:
570             descriptor->linked_track_id = get_be32(pb);
571             break;
572         case 0x3201: /* PictureEssenceCoding */
573             get_buffer(pb, descriptor->essence_codec_ul, 16);
574             break;
575         case 0x3203:
576             descriptor->width = get_be32(pb);
577             break;
578         case 0x3202:
579             descriptor->height = get_be32(pb);
580             break;
581         case 0x320E:
582             descriptor->aspect_ratio.num = get_be32(pb);
583             descriptor->aspect_ratio.den = get_be32(pb);
584             break;
585         case 0x3D03:
586             descriptor->sample_rate.num = get_be32(pb);
587             descriptor->sample_rate.den = get_be32(pb);
588             break;
589         case 0x3D06: /* SoundEssenceCompression */
590             get_buffer(pb, descriptor->essence_codec_ul, 16);
591             break;
592         case 0x3D07:
593             descriptor->channels = get_be32(pb);
594             break;
595         case 0x3D01:
596             descriptor->bits_per_sample = get_be32(pb);
597             break;
598         case 0x3401:
599             mxf_read_metadata_pixel_layout(pb, descriptor);
600             break;
601         case 0x8201: /* Private tag used by SONY C0023S01.mxf */
602             descriptor->extradata = av_malloc(size);
603             descriptor->extradata_size = size;
604             get_buffer(pb, descriptor->extradata, size);
605             break;
606         default:
607             url_fskip(pb, size);
608         }
609         bytes_read += size + 4;
610     }
611     descriptor->type = Descriptor;
612     return mxf_add_metadata_set(mxf, descriptor);
613 }
614
615 /* SMPTE RP224 http://www.smpte-ra.org/mdd/index.html */
616 static const UID picture_essence_track_ul = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x01,0x03,0x02,0x02,0x01,0x00,0x00,0x00 };
617 static const UID sound_essence_track_ul   = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x01,0x03,0x02,0x02,0x02,0x00,0x00,0x00 };
618
619 static const MXFCodecUL mxf_codec_uls[] = {
620     /* PictureEssenceCoding */
621     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* 422P@ML I-Frame */
622     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* 422P@HL Long GoP */
623     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* MP@ML Long GoP */
624     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* 422P@ML Long GoP */
625     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, CODEC_ID_MPEG2VIDEO, Frame }, /* MP@HL Long GoP */
626     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x20,0x02,0x03 },      CODEC_ID_MPEG4, Frame }, /* XDCAM proxy_pal030926.mxf */
627     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x20,0x02,0x04 },      CODEC_ID_MPEG4, Frame }, /* XDCAM Proxy C0023S01.mxf */
628     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x05 }, CODEC_ID_MPEG2VIDEO, Frame }, /* D-10 30Mbps PAL */
629     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 }, CODEC_ID_MPEG2VIDEO, Frame }, /* D-10 50Mbps PAL */
630     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x04,0x00 },    CODEC_ID_DVVIDEO, Frame }, /* DVCPRO50 PAL */
631     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x02,0x00 },    CODEC_ID_DVVIDEO, Frame }, /* DVCPRO25 PAL */
632     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x02,0x00 },    CODEC_ID_DVVIDEO, Frame }, /* DV25 IEC PAL */
633   //{ { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 },     CODEC_ID_JPEG2K, Frame }, /* JPEG2000 Codestream */
634     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x01,0x7F,0x00,0x00,0x00 },   CODEC_ID_RAWVIDEO, Frame }, /* Uncompressed */
635     /* SoundEssenceCompression */
636     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },  CODEC_ID_PCM_S16LE, Frame }, /* Uncompressed */
637     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x7F,0x00,0x00,0x00 },  CODEC_ID_PCM_S16LE, Frame },
638     { { 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 */
639     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x01,0x01,0x00 },   CODEC_ID_PCM_ALAW, Frame },
640     { { 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 */
641     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x01,0x00 },        CODEC_ID_AC3, Frame },
642     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x05,0x00 },        CODEC_ID_MP2, Frame }, /* MP2 or MP3 */
643   //{ { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x02,0x03,0x02,0x1C,0x00 },    CODEC_ID_DOLBY_E, Frame }, /* Dolby-E */
644     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },       CODEC_ID_NONE, Frame },
645 };
646
647 static const MXFCodecUL mxf_picture_essence_container_uls[] = {
648     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, CODEC_ID_MPEG2VIDEO, Frame }, /* MPEG-ES Frame wrapped */
649     { { 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 */
650     { { 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 */
651     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },       CODEC_ID_NONE, Frame },
652 };
653
654 static const MXFCodecUL mxf_sound_essence_container_uls[] = {
655     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },  CODEC_ID_PCM_S16LE, Frame }, /* BWF Frame wrapped */
656     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },  CODEC_ID_PCM_S16LE, Frame }, /* AES Frame wrapped */
657     { { 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 */
658     { { 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 */
659     { { 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 */
660   //{ { 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 */
661     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },       CODEC_ID_NONE, Frame },
662 };
663
664 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
665 {
666     while (uls->id != CODEC_ID_NONE) {
667         if(!memcmp(uls->uid, *uid, 16))
668             break;
669         uls++;
670     }
671     return uls;
672 }
673
674 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref)
675 {
676     int i;
677
678     if (!strong_ref)
679         return NULL;
680     for (i = 0; i < mxf->metadata_sets_count; i++) {
681         if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16)) {
682             return mxf->metadata_sets[i];
683         }
684     }
685     return NULL;
686 }
687
688 static int mxf_parse_structural_metadata(MXFContext *mxf)
689 {
690     MXFPackage *material_package = NULL;
691     MXFPackage *source_package = NULL;
692     MXFPackage *temp_package = NULL;
693     int i, j, k;
694
695     dprintf("metadata sets count %d\n", mxf->metadata_sets_count);
696     /* TODO: handle multiple material packages (OP3x) */
697     for (i = 0; i < mxf->packages_count; i++) {
698         if (!(temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i]))) {
699             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve package strong ref\n");
700             return -1;
701         }
702         if (temp_package->type == MaterialPackage) {
703             material_package = temp_package;
704             break;
705         }
706     }
707     if (!material_package) {
708         av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
709         return -1;
710     }
711
712     for (i = 0; i < material_package->tracks_count; i++) {
713         MXFTrack *material_track = NULL;
714         MXFTrack *source_track = NULL;
715         MXFTrack *temp_track = NULL;
716         MXFDescriptor *descriptor = NULL;
717         MXFStructuralComponent *component = NULL;
718         const MXFCodecUL *codec_ul = NULL;
719         const MXFCodecUL *container_ul = NULL;
720         AVStream *st;
721
722         if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i]))) {
723             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
724             continue;
725         }
726
727         if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref))) {
728             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
729             return -1;
730         }
731
732         /* TODO: handle multiple source clips */
733         for (j = 0; j < material_track->sequence->structural_components_count; j++) {
734             /* TODO: handle timecode component */
735             component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j]);
736             if (!component || component->type != SourceClip)
737                 continue;
738
739             for (k = 0; k < mxf->packages_count; k++) {
740                 if (!(temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k]))) {
741                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
742                     return -1;
743                 }
744                 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
745                     source_package = temp_package;
746                     break;
747                 }
748             }
749             if (!source_package) {
750                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source package found\n", material_track->track_id);
751                 break;
752             }
753             for (k = 0; k < source_package->tracks_count; k++) {
754                 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k]))) {
755                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
756                     return -1;
757                 }
758                 if (temp_track->track_id == component->source_track_id) {
759                     source_track = temp_track;
760                     break;
761                 }
762             }
763             if (!source_track) {
764                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
765                 break;
766             }
767         }
768         if (!source_track)
769             continue;
770
771         st = av_new_stream(mxf->fc, source_track->track_id);
772         st->priv_data = source_track;
773         st->duration = component->duration;
774         if (st->duration == -1)
775             st->duration = AV_NOPTS_VALUE;
776         st->start_time = component->start_position;
777         av_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
778
779         if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref))) {
780             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
781             return -1;
782         }
783
784 #ifdef DEBUG
785         PRINT_KEY(source_track->sequence->data_definition_ul);
786 #endif
787         if (!memcmp(source_track->sequence->data_definition_ul, picture_essence_track_ul, 16))
788             st->codec->codec_type = CODEC_TYPE_VIDEO;
789         else if (!memcmp(source_track->sequence->data_definition_ul, sound_essence_track_ul, 16))
790             st->codec->codec_type = CODEC_TYPE_AUDIO;
791         else
792             st->codec->codec_type = CODEC_TYPE_DATA;
793
794         source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref);
795         if (source_package->descriptor) {
796             if (source_package->descriptor->type == MultipleDescriptor) {
797                 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
798                     MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j]);
799
800                     if (!sub_descriptor) {
801                         av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
802                         continue;
803                     }
804                     if (sub_descriptor->linked_track_id == source_track->track_id) {
805                         descriptor = sub_descriptor;
806                         break;
807                     }
808                 }
809             } else
810                 descriptor = source_package->descriptor;
811         }
812         if (!descriptor) {
813             av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
814             continue;
815         }
816 #ifdef DEBUG
817         PRINT_KEY(descriptor->essence_codec_ul);
818         PRINT_KEY(descriptor->essence_container_ul);
819 #endif
820         /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
821         codec_ul = mxf_get_codec_ul(mxf_codec_uls, &descriptor->essence_codec_ul);
822         st->codec->codec_id = codec_ul->id;
823         if (descriptor->extradata) {
824             st->codec->extradata = descriptor->extradata;
825             st->codec->extradata_size = descriptor->extradata_size;
826         }
827         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
828             container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, &descriptor->essence_container_ul);
829             if (st->codec->codec_id == CODEC_ID_NONE)
830                 st->codec->codec_id = container_ul->id;
831             st->codec->width = descriptor->width;
832             st->codec->height = descriptor->height;
833             st->codec->bits_per_sample = descriptor->bits_per_sample; /* Uncompressed */
834         } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
835             container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, &descriptor->essence_container_ul);
836             if (st->codec->codec_id == CODEC_ID_NONE)
837                 st->codec->codec_id = container_ul->id;
838             st->codec->channels = descriptor->channels;
839             st->codec->bits_per_sample = descriptor->bits_per_sample;
840             st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
841             /* TODO: implement CODEC_ID_RAWAUDIO */
842             if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
843                 if (descriptor->bits_per_sample == 24)
844                     st->codec->codec_id = CODEC_ID_PCM_S24LE;
845                 else if (descriptor->bits_per_sample == 32)
846                     st->codec->codec_id = CODEC_ID_PCM_S32LE;
847             } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
848                 if (descriptor->bits_per_sample == 24)
849                     st->codec->codec_id = CODEC_ID_PCM_S24BE;
850                 else if (descriptor->bits_per_sample == 32)
851                     st->codec->codec_id = CODEC_ID_PCM_S32BE;
852             }
853         }
854         if (container_ul && container_ul->wrapping == Clip) {
855             dprintf("stream %d: clip wrapped essence\n", st->index);
856             st->need_parsing = 1;
857         }
858     }
859     return 0;
860 }
861
862 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
863     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2F,0x00 }, mxf_read_metadata_preface },
864     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_metadata_content_storage },
865     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_metadata_source_package },
866     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_metadata_material_package },
867     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_metadata_sequence },
868     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_metadata_source_clip },
869     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_metadata_multiple_descriptor },
870     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_metadata_generic_descriptor }, /* Generic Sound */
871     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_metadata_generic_descriptor }, /* CDCI */
872     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_metadata_generic_descriptor }, /* RGBA */
873     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_metadata_generic_descriptor }, /* MPEG 2 Video */
874     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_metadata_generic_descriptor }, /* Wave */
875     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_metadata_generic_descriptor }, /* AES3 */
876     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_metadata_track }, /* Static Track */
877     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_metadata_track }, /* Generic Track */
878     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL },
879 };
880
881 static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
882 {
883     MXFContext *mxf = s->priv_data;
884     KLVPacket klv;
885
886     mxf->fc = s;
887     while (!url_feof(&s->pb)) {
888         const MXFMetadataReadTableEntry *function;
889
890         if (klv_read_packet(&klv, &s->pb) < 0) {
891             av_log(s, AV_LOG_ERROR, "error reading KLV packet\n");
892             return -1;
893         }
894 #ifdef DEBUG
895         PRINT_KEY(klv.key);
896 #endif
897         if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
898             /* FIXME avoid seek */
899             url_fseek(&s->pb, klv.offset, SEEK_SET);
900             break;
901         }
902
903         for (function = mxf_metadata_read_table; function->read; function++) {
904             if (IS_KLV_KEY(klv.key, function->key)) {
905                 if (function->read(mxf, &klv) < 0) {
906                     av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
907                     return -1;
908                 }
909                 break;
910             }
911         }
912         if (!function->read)
913             url_fskip(&s->pb, klv.length);
914     }
915     return mxf_parse_structural_metadata(mxf);
916 }
917
918 static int mxf_read_close(AVFormatContext *s)
919 {
920     MXFContext *mxf = s->priv_data;
921     int i;
922
923     av_freep(&mxf->packages_refs);
924     av_freep(&mxf->essence_container_data_sets_refs);
925     av_freep(&mxf->essence_containers_uls);
926     for (i = 0; i < mxf->metadata_sets_count; i++) {
927         switch (mxf->metadata_sets[i]->type) {
928         case MultipleDescriptor:
929             av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
930             break;
931         case Sequence:
932             av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
933             break;
934         case SourcePackage:
935         case MaterialPackage:
936             av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
937             break;
938         default:
939             break;
940         }
941         av_freep(&mxf->metadata_sets[i]);
942     }
943     av_freep(&mxf->metadata_sets);
944     return 0;
945 }
946
947 static int mxf_probe(AVProbeData *p) {
948     uint8_t *bufp = p->buf;
949     uint8_t *end = p->buf + p->buf_size;
950
951     if (p->buf_size < sizeof(mxf_header_partition_pack_key))
952         return 0;
953
954     /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
955     end -= sizeof(mxf_header_partition_pack_key);
956     for (; bufp < end; bufp++) {
957         if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
958             return AVPROBE_SCORE_MAX;
959     }
960     return 0;
961 }
962
963
964 AVInputFormat mxf_demuxer = {
965     "mxf",
966     "MXF format",
967     sizeof(MXFContext),
968     mxf_probe,
969     mxf_read_header,
970     mxf_read_packet,
971     mxf_read_close,
972     NULL,
973 };