]> git.sesse.net Git - ffmpeg/blob - libavformat/mxfdec.c
mxfdec: Parse ThisPartition
[ffmpeg] / libavformat / mxfdec.c
1 /*
2  * MXF demuxer.
3  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /*
23  * References
24  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
25  * SMPTE 377M MXF File Format Specifications
26  * SMPTE 378M Operational Pattern 1a
27  * SMPTE 379M MXF Generic Container
28  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29  * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
30  * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
31  *
32  * Principle
33  * Search for Track numbers which will identify essence element KLV packets.
34  * Search for SourcePackage which define tracks which contains Track numbers.
35  * Material Package contains tracks with reference to SourcePackage tracks.
36  * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
37  * Assign Descriptors to correct Tracks.
38  *
39  * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
40  * Metadata parsing resolves Strong References to objects.
41  *
42  * Simple demuxer, only OP1A supported and some files might not work at all.
43  * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
44  */
45
46 //#define DEBUG
47
48 #include "libavutil/aes.h"
49 #include "libavutil/mathematics.h"
50 #include "libavcodec/bytestream.h"
51 #include "avformat.h"
52 #include "internal.h"
53 #include "mxf.h"
54
55 typedef enum {
56     Header,
57     BodyPartition,
58     Footer
59 } MXFPartitionType;
60
61 typedef enum {
62     OP1a,
63     OP1b,
64     OP1c,
65     OP2a,
66     OP2b,
67     OP2c,
68     OP3a,
69     OP3b,
70     OP3c,
71     OPAtom,
72 } MXFOP;
73
74 typedef struct {
75     int closed;
76     int complete;
77     MXFPartitionType type;
78     uint64_t previous_partition;
79     int index_sid;
80     int body_sid;
81     int64_t this_partition;
82 } MXFPartition;
83
84 typedef struct {
85     UID uid;
86     enum MXFMetadataSetType type;
87     UID source_container_ul;
88 } MXFCryptoContext;
89
90 typedef struct {
91     UID uid;
92     enum MXFMetadataSetType type;
93     UID source_package_uid;
94     UID data_definition_ul;
95     int64_t duration;
96     int64_t start_position;
97     int source_track_id;
98 } MXFStructuralComponent;
99
100 typedef struct {
101     UID uid;
102     enum MXFMetadataSetType type;
103     UID data_definition_ul;
104     UID *structural_components_refs;
105     int structural_components_count;
106     int64_t duration;
107 } MXFSequence;
108
109 typedef struct {
110     UID uid;
111     enum MXFMetadataSetType type;
112     MXFSequence *sequence; /* mandatory, and only one */
113     UID sequence_ref;
114     int track_id;
115     uint8_t track_number[4];
116     AVRational edit_rate;
117 } MXFTrack;
118
119 typedef struct {
120     UID uid;
121     enum MXFMetadataSetType type;
122     UID essence_container_ul;
123     UID essence_codec_ul;
124     AVRational sample_rate;
125     AVRational aspect_ratio;
126     int width;
127     int height;
128     int channels;
129     int bits_per_sample;
130     UID *sub_descriptors_refs;
131     int sub_descriptors_count;
132     int linked_track_id;
133     uint8_t *extradata;
134     int extradata_size;
135     enum PixelFormat pix_fmt;
136 } MXFDescriptor;
137
138 typedef struct {
139     UID uid;
140     enum MXFMetadataSetType type;
141     int edit_unit_byte_count;
142     int index_sid;
143     int body_sid;
144     int slice_count;
145     AVRational index_edit_rate;
146     uint64_t index_start_position;
147     uint64_t index_duration;
148     int *slice;
149     int *element_delta;
150     int nb_delta_entries;
151     int *flag_entries;
152     uint64_t *stream_offset_entries;
153     uint32_t **slice_offset_entries;
154     int nb_index_entries;
155 } MXFIndexTableSegment;
156
157 typedef struct {
158     UID uid;
159     enum MXFMetadataSetType type;
160     UID package_uid;
161     UID *tracks_refs;
162     int tracks_count;
163     MXFDescriptor *descriptor; /* only one */
164     UID descriptor_ref;
165 } MXFPackage;
166
167 typedef struct {
168     UID uid;
169     enum MXFMetadataSetType type;
170 } MXFMetadataSet;
171
172 typedef struct {
173     MXFPartition *partitions;
174     unsigned partitions_count;
175     MXFOP op;
176     UID *packages_refs;
177     int packages_count;
178     MXFMetadataSet **metadata_sets;
179     int metadata_sets_count;
180     AVFormatContext *fc;
181     struct AVAES *aesc;
182     uint8_t *local_tags;
183     int local_tags_count;
184     uint64_t footer_partition;
185     int system_item;
186     int64_t essence_offset;
187     int first_essence_kl_length;
188     int64_t first_essence_length;
189     KLVPacket current_klv_data;
190     int current_klv_index;
191     int run_in;
192     MXFPartition *current_partition;
193     int parsing_backward;
194     int64_t last_forward_tell;
195 } MXFContext;
196
197 enum MXFWrappingScheme {
198     Frame,
199     Clip,
200 };
201
202 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid);
203
204 typedef struct {
205     const UID key;
206     MXFMetadataReadFunc *read;
207     int ctx_size;
208     enum MXFMetadataSetType type;
209 } MXFMetadataReadTableEntry;
210
211 /* partial keys to match */
212 static const uint8_t mxf_header_partition_pack_key[]       = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
213 static const uint8_t mxf_essence_element_key[]             = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
214 static const uint8_t mxf_system_item_key[]                 = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04 };
215 static const uint8_t mxf_klv_key[]                         = { 0x06,0x0e,0x2b,0x34 };
216 /* complete keys to match */
217 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 };
218 static const uint8_t mxf_encrypted_triplet_key[]           = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
219 static const uint8_t mxf_encrypted_essence_container[]     = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
220 static const uint8_t mxf_sony_mpeg4_extradata[]            = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
221
222 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
223
224 static int64_t klv_decode_ber_length(AVIOContext *pb)
225 {
226     uint64_t size = avio_r8(pb);
227     if (size & 0x80) { /* long form */
228         int bytes_num = size & 0x7f;
229         /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
230         if (bytes_num > 8)
231             return -1;
232         size = 0;
233         while (bytes_num--)
234             size = size << 8 | avio_r8(pb);
235     }
236     return size;
237 }
238
239 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
240 {
241     int i, b;
242     for (i = 0; i < size && !url_feof(pb); i++) {
243         b = avio_r8(pb);
244         if (b == key[0])
245             i = 0;
246         else if (b != key[i])
247             i = -1;
248     }
249     return i == size;
250 }
251
252 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
253 {
254     if (!mxf_read_sync(pb, mxf_klv_key, 4))
255         return -1;
256     klv->offset = avio_tell(pb) - 4;
257     memcpy(klv->key, mxf_klv_key, 4);
258     avio_read(pb, klv->key + 4, 12);
259     klv->length = klv_decode_ber_length(pb);
260     return klv->length == -1 ? -1 : 0;
261 }
262
263 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
264 {
265     int i;
266
267     for (i = 0; i < s->nb_streams; i++) {
268         MXFTrack *track = s->streams[i]->priv_data;
269         /* SMPTE 379M 7.3 */
270         if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
271             return i;
272     }
273     /* return 0 if only one stream, for OP Atom files with 0 as track number */
274     return s->nb_streams == 1 ? 0 : -1;
275 }
276
277 /* XXX: use AVBitStreamFilter */
278 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
279 {
280     const uint8_t *buf_ptr, *end_ptr;
281     uint8_t *data_ptr;
282     int i;
283
284     if (length > 61444) /* worst case PAL 1920 samples 8 channels */
285         return -1;
286     length = av_get_packet(pb, pkt, length);
287     if (length < 0)
288         return length;
289     data_ptr = pkt->data;
290     end_ptr = pkt->data + length;
291     buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
292     for (; buf_ptr + st->codec->channels*4 < end_ptr; ) {
293         for (i = 0; i < st->codec->channels; i++) {
294             uint32_t sample = bytestream_get_le32(&buf_ptr);
295             if (st->codec->bits_per_coded_sample == 24)
296                 bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
297             else
298                 bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
299         }
300         buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
301     }
302     av_shrink_packet(pkt, data_ptr - pkt->data);
303     return 0;
304 }
305
306 static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
307 {
308     static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
309     MXFContext *mxf = s->priv_data;
310     AVIOContext *pb = s->pb;
311     int64_t end = avio_tell(pb) + klv->length;
312     int64_t size;
313     uint64_t orig_size;
314     uint64_t plaintext_size;
315     uint8_t ivec[16];
316     uint8_t tmpbuf[16];
317     int index;
318
319     if (!mxf->aesc && s->key && s->keylen == 16) {
320         mxf->aesc = av_malloc(av_aes_size);
321         if (!mxf->aesc)
322             return -1;
323         av_aes_init(mxf->aesc, s->key, 128, 1);
324     }
325     // crypto context
326     avio_skip(pb, klv_decode_ber_length(pb));
327     // plaintext offset
328     klv_decode_ber_length(pb);
329     plaintext_size = avio_rb64(pb);
330     // source klv key
331     klv_decode_ber_length(pb);
332     avio_read(pb, klv->key, 16);
333     if (!IS_KLV_KEY(klv, mxf_essence_element_key))
334         return -1;
335     index = mxf_get_stream_index(s, klv);
336     if (index < 0)
337         return -1;
338     // source size
339     klv_decode_ber_length(pb);
340     orig_size = avio_rb64(pb);
341     if (orig_size < plaintext_size)
342         return -1;
343     // enc. code
344     size = klv_decode_ber_length(pb);
345     if (size < 32 || size - 32 < orig_size)
346         return -1;
347     avio_read(pb, ivec, 16);
348     avio_read(pb, tmpbuf, 16);
349     if (mxf->aesc)
350         av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
351     if (memcmp(tmpbuf, checkv, 16))
352         av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
353     size -= 32;
354     size = av_get_packet(pb, pkt, size);
355     if (size < 0)
356         return size;
357     else if (size < plaintext_size)
358         return AVERROR_INVALIDDATA;
359     size -= plaintext_size;
360     if (mxf->aesc)
361         av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
362                      &pkt->data[plaintext_size], size >> 4, ivec, 1);
363     av_shrink_packet(pkt, orig_size);
364     pkt->stream_index = index;
365     avio_skip(pb, end - avio_tell(pb));
366     return 0;
367 }
368
369 static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
370 {
371     KLVPacket klv;
372
373     while (!url_feof(s->pb)) {
374         if (klv_read_packet(&klv, s->pb) < 0)
375             return -1;
376         PRINT_KEY(s, "read packet", klv.key);
377         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
378         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
379             int res = mxf_decrypt_triplet(s, pkt, &klv);
380             if (res < 0) {
381                 av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
382                 return -1;
383             }
384             return 0;
385         }
386         if (IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
387             int index = mxf_get_stream_index(s, &klv);
388             if (index < 0) {
389                 av_log(s, AV_LOG_ERROR, "error getting stream index %d\n", AV_RB32(klv.key+12));
390                 goto skip;
391             }
392             if (s->streams[index]->discard == AVDISCARD_ALL)
393                 goto skip;
394             /* check for 8 channels AES3 element */
395             if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
396                 if (mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length) < 0) {
397                     av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
398                     return -1;
399                 }
400             } else {
401                 int ret = av_get_packet(s->pb, pkt, klv.length);
402                 if (ret < 0)
403                     return ret;
404             }
405             pkt->stream_index = index;
406             pkt->pos = klv.offset;
407             return 0;
408         } else
409         skip:
410             avio_skip(s->pb, klv.length);
411     }
412     return AVERROR_EOF;
413 }
414
415 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid)
416 {
417     MXFContext *mxf = arg;
418     int item_num = avio_rb32(pb);
419     int item_len = avio_rb32(pb);
420
421     if (item_len != 18) {
422         av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");
423         return -1;
424     }
425     if (item_num > UINT_MAX / item_len)
426         return -1;
427     mxf->local_tags_count = item_num;
428     mxf->local_tags = av_malloc(item_num*item_len);
429     if (!mxf->local_tags)
430         return -1;
431     avio_read(pb, mxf->local_tags, item_num*item_len);
432     return 0;
433 }
434
435 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid)
436 {
437     MXFContext *mxf = arg;
438     MXFPartition *partition;
439     UID op;
440     uint64_t footer_partition;
441
442     if (mxf->partitions_count+1 >= UINT_MAX / sizeof(*mxf->partitions))
443         return AVERROR(ENOMEM);
444
445     mxf->partitions = av_realloc(mxf->partitions, (mxf->partitions_count + 1) * sizeof(*mxf->partitions));
446     if (!mxf->partitions)
447         return AVERROR(ENOMEM);
448
449     partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count++];
450
451     switch(uid[13]) {
452     case 2:
453         partition->type = Header;
454         break;
455     case 3:
456         partition->type = BodyPartition;
457         break;
458     case 4:
459         partition->type = Footer;
460         break;
461     default:
462         av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
463         return AVERROR_INVALIDDATA;
464     }
465
466     /* consider both footers to be closed (there is only Footer and CompleteFooter) */
467     partition->closed = partition->type == Footer || !(uid[14] & 1);
468     partition->complete = uid[14] > 2;
469     avio_skip(pb, 8);
470     partition->this_partition = avio_rb64(pb);
471     partition->previous_partition = avio_rb64(pb);
472     footer_partition = avio_rb64(pb);
473     avio_skip(pb, 16);
474     partition->index_sid = avio_rb32(pb);
475     avio_skip(pb, 8);
476     partition->body_sid = avio_rb32(pb);
477     avio_read(pb, op, sizeof(UID));
478
479     /* some files don'thave FooterPartition set in every partition */
480     if (footer_partition) {
481         if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
482             av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %li != %li\n",
483                    mxf->footer_partition, footer_partition);
484         } else {
485             mxf->footer_partition = footer_partition;
486         }
487     }
488
489     av_dlog(mxf->fc, "PartitionPack: ThisPartition = 0x%lx, PreviousPartition = 0x%lx, "
490             "FooterPartition = 0x%lx, IndexSID = %i, BodySID = %i\n",
491             partition->this_partition,
492             partition->previous_partition, footer_partition,
493             partition->index_sid, partition->body_sid);
494
495     if      (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
496     else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
497     else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
498     else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
499     else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
500     else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
501     else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
502     else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
503     else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
504     else if (op[12] == 0x10)             mxf->op = OPAtom;
505     else
506         av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh\n", op[12], op[13]);
507
508     return 0;
509 }
510
511 static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
512 {
513     if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))
514         return AVERROR(ENOMEM);
515     mxf->metadata_sets = av_realloc(mxf->metadata_sets, (mxf->metadata_sets_count + 1) * sizeof(*mxf->metadata_sets));
516     if (!mxf->metadata_sets)
517         return -1;
518     mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
519     mxf->metadata_sets_count++;
520     return 0;
521 }
522
523 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid)
524 {
525     MXFCryptoContext *cryptocontext = arg;
526     if (size != 16)
527         return -1;
528     if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
529         avio_read(pb, cryptocontext->source_container_ul, 16);
530     return 0;
531 }
532
533 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid)
534 {
535     MXFContext *mxf = arg;
536     switch (tag) {
537     case 0x1901:
538         mxf->packages_count = avio_rb32(pb);
539         if (mxf->packages_count >= UINT_MAX / sizeof(UID))
540             return -1;
541         mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
542         if (!mxf->packages_refs)
543             return -1;
544         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
545         avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
546         break;
547     }
548     return 0;
549 }
550
551 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid)
552 {
553     MXFStructuralComponent *source_clip = arg;
554     switch(tag) {
555     case 0x0202:
556         source_clip->duration = avio_rb64(pb);
557         break;
558     case 0x1201:
559         source_clip->start_position = avio_rb64(pb);
560         break;
561     case 0x1101:
562         /* UMID, only get last 16 bytes */
563         avio_skip(pb, 16);
564         avio_read(pb, source_clip->source_package_uid, 16);
565         break;
566     case 0x1102:
567         source_clip->source_track_id = avio_rb32(pb);
568         break;
569     }
570     return 0;
571 }
572
573 static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
574 {
575     MXFPackage *package = arg;
576     switch(tag) {
577     case 0x4403:
578         package->tracks_count = avio_rb32(pb);
579         if (package->tracks_count >= UINT_MAX / sizeof(UID))
580             return -1;
581         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
582         if (!package->tracks_refs)
583             return -1;
584         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
585         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
586         break;
587     }
588     return 0;
589 }
590
591 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid)
592 {
593     MXFTrack *track = arg;
594     switch(tag) {
595     case 0x4801:
596         track->track_id = avio_rb32(pb);
597         break;
598     case 0x4804:
599         avio_read(pb, track->track_number, 4);
600         break;
601     case 0x4B01:
602         track->edit_rate.den = avio_rb32(pb);
603         track->edit_rate.num = avio_rb32(pb);
604         break;
605     case 0x4803:
606         avio_read(pb, track->sequence_ref, 16);
607         break;
608     }
609     return 0;
610 }
611
612 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid)
613 {
614     MXFSequence *sequence = arg;
615     switch(tag) {
616     case 0x0202:
617         sequence->duration = avio_rb64(pb);
618         break;
619     case 0x0201:
620         avio_read(pb, sequence->data_definition_ul, 16);
621         break;
622     case 0x1001:
623         sequence->structural_components_count = avio_rb32(pb);
624         if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
625             return -1;
626         sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
627         if (!sequence->structural_components_refs)
628             return -1;
629         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
630         avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
631         break;
632     }
633     return 0;
634 }
635
636 static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid)
637 {
638     MXFPackage *package = arg;
639     switch(tag) {
640     case 0x4403:
641         package->tracks_count = avio_rb32(pb);
642         if (package->tracks_count >= UINT_MAX / sizeof(UID))
643             return -1;
644         package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
645         if (!package->tracks_refs)
646             return -1;
647         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
648         avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
649         break;
650     case 0x4401:
651         /* UMID, only get last 16 bytes */
652         avio_skip(pb, 16);
653         avio_read(pb, package->package_uid, 16);
654         break;
655     case 0x4701:
656         avio_read(pb, package->descriptor_ref, 16);
657         break;
658     }
659     return 0;
660 }
661
662 static int mxf_read_delta_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
663 {
664     int i, length;
665
666     segment->nb_delta_entries = avio_rb32(pb);
667     length = avio_rb32(pb);
668
669     if (!(segment->slice         = av_calloc(segment->nb_delta_entries, sizeof(*segment->slice))) ||
670         !(segment->element_delta = av_calloc(segment->nb_delta_entries, sizeof(*segment->element_delta))))
671         return AVERROR(ENOMEM);
672
673     for (i = 0; i < segment->nb_delta_entries; i++) {
674         avio_r8(pb);    /* PosTableIndex */
675         segment->slice[i] = avio_r8(pb);
676         segment->element_delta[i] = avio_rb32(pb);
677     }
678     return 0;
679 }
680
681 static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
682 {
683     int i, j, length;
684
685     segment->nb_index_entries = avio_rb32(pb);
686     length = avio_rb32(pb);
687
688     if (!(segment->flag_entries          = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
689         !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries))))
690         return AVERROR(ENOMEM);
691
692     if (segment->slice_count &&
693         !(segment->slice_offset_entries  = av_calloc(segment->nb_index_entries, sizeof(*segment->slice_offset_entries))))
694         return AVERROR(ENOMEM);
695
696     for (i = 0; i < segment->nb_index_entries; i++) {
697         avio_rb16(pb);  /* TemporalOffset and KeyFrameOffset */
698         segment->flag_entries[i] = avio_r8(pb);
699         segment->stream_offset_entries[i] = avio_rb64(pb);
700         if (segment->slice_count) {
701             if (!(segment->slice_offset_entries[i] = av_calloc(segment->slice_count, sizeof(**segment->slice_offset_entries))))
702                 return AVERROR(ENOMEM);
703
704             for (j = 0; j < segment->slice_count; j++)
705                 segment->slice_offset_entries[i][j] = avio_rb32(pb);
706         }
707
708         avio_skip(pb, length - 11 - 4 * segment->slice_count);
709     }
710     return 0;
711 }
712
713 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid)
714 {
715     MXFIndexTableSegment *segment = arg;
716     switch(tag) {
717     case 0x3F05:
718         segment->edit_unit_byte_count = avio_rb32(pb);
719         av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
720         break;
721     case 0x3F06:
722         segment->index_sid = avio_rb32(pb);
723         av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
724         break;
725     case 0x3F07:
726         segment->body_sid = avio_rb32(pb);
727         av_dlog(NULL, "BodySID %d\n", segment->body_sid);
728         break;
729     case 0x3F08:
730         segment->slice_count = avio_r8(pb);
731         av_dlog(NULL, "SliceCount %d\n", segment->slice_count);
732         break;
733     case 0x3F09:
734         av_dlog(NULL, "DeltaEntryArray found\n");
735         return mxf_read_delta_entry_array(pb, segment);
736     case 0x3F0A:
737         av_dlog(NULL, "IndexEntryArray found\n");
738         return mxf_read_index_entry_array(pb, segment);
739     case 0x3F0B:
740         segment->index_edit_rate.num = avio_rb32(pb);
741         segment->index_edit_rate.den = avio_rb32(pb);
742         av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
743                 segment->index_edit_rate.den);
744         break;
745     case 0x3F0C:
746         segment->index_start_position = avio_rb64(pb);
747         av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
748         break;
749     case 0x3F0D:
750         segment->index_duration = avio_rb64(pb);
751         av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
752         break;
753     }
754     return 0;
755 }
756
757 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
758 {
759     int code, value, ofs = 0;
760     char layout[16] = {0};
761
762     do {
763         code = avio_r8(pb);
764         value = avio_r8(pb);
765         av_dlog(NULL, "pixel layout: code %#x\n", code);
766
767         if (ofs < 16) {
768             layout[ofs++] = code;
769             layout[ofs++] = value;
770         }
771     } while (code != 0); /* SMPTE 377M E.2.46 */
772
773     ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
774 }
775
776 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid)
777 {
778     MXFDescriptor *descriptor = arg;
779     switch(tag) {
780     case 0x3F01:
781         descriptor->sub_descriptors_count = avio_rb32(pb);
782         if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
783             return -1;
784         descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
785         if (!descriptor->sub_descriptors_refs)
786             return -1;
787         avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
788         avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
789         break;
790     case 0x3004:
791         avio_read(pb, descriptor->essence_container_ul, 16);
792         break;
793     case 0x3006:
794         descriptor->linked_track_id = avio_rb32(pb);
795         break;
796     case 0x3201: /* PictureEssenceCoding */
797         avio_read(pb, descriptor->essence_codec_ul, 16);
798         break;
799     case 0x3203:
800         descriptor->width = avio_rb32(pb);
801         break;
802     case 0x3202:
803         descriptor->height = avio_rb32(pb);
804         break;
805     case 0x320E:
806         descriptor->aspect_ratio.num = avio_rb32(pb);
807         descriptor->aspect_ratio.den = avio_rb32(pb);
808         break;
809     case 0x3D03:
810         descriptor->sample_rate.num = avio_rb32(pb);
811         descriptor->sample_rate.den = avio_rb32(pb);
812         break;
813     case 0x3D06: /* SoundEssenceCompression */
814         avio_read(pb, descriptor->essence_codec_ul, 16);
815         break;
816     case 0x3D07:
817         descriptor->channels = avio_rb32(pb);
818         break;
819     case 0x3D01:
820         descriptor->bits_per_sample = avio_rb32(pb);
821         break;
822     case 0x3401:
823         mxf_read_pixel_layout(pb, descriptor);
824         break;
825     default:
826         /* Private uid used by SONY C0023S01.mxf */
827         if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
828             descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
829             if (!descriptor->extradata)
830                 return -1;
831             descriptor->extradata_size = size;
832             avio_read(pb, descriptor->extradata, size);
833         }
834         break;
835     }
836     return 0;
837 }
838
839 /*
840  * Match an uid independently of the version byte and up to len common bytes
841  * Returns: boolean
842  */
843 static int mxf_match_uid(const UID key, const UID uid, int len)
844 {
845     int i;
846     for (i = 0; i < len; i++) {
847         if (i != 7 && key[i] != uid[i])
848             return 0;
849     }
850     return 1;
851 }
852
853 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
854 {
855     while (uls->uid[0]) {
856         if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
857             break;
858         uls++;
859     }
860     return uls;
861 }
862
863 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
864 {
865     int i;
866
867     if (!strong_ref)
868         return NULL;
869     for (i = 0; i < mxf->metadata_sets_count; i++) {
870         if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
871             (type == AnyType || mxf->metadata_sets[i]->type == type)) {
872             return mxf->metadata_sets[i];
873         }
874     }
875     return NULL;
876 }
877
878 static const MXFCodecUL mxf_essence_container_uls[] = {
879     // video essence container uls
880     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
881     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14,    CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
882     // sound essence container uls
883     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
884     { { 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 */
885     { { 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 */
886     { { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0xFF,0x4B,0x46,0x41,0x41,0x00,0x0D,0x4D,0x4F }, 14, CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */
887     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },  0,      CODEC_ID_NONE },
888 };
889
890 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
891 {
892     int i, j, nb_segments = 0;
893     MXFIndexTableSegment **unsorted_segments;
894     int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
895
896     /* count number of segments, allocate arrays and copy unsorted segments */
897     for (i = 0; i < mxf->metadata_sets_count; i++)
898         if (mxf->metadata_sets[i]->type == IndexTableSegment)
899             nb_segments++;
900
901     if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
902         !(*sorted_segments  = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
903         av_free(unsorted_segments);
904         return AVERROR(ENOMEM);
905     }
906
907     for (i = j = 0; i < mxf->metadata_sets_count; i++)
908         if (mxf->metadata_sets[i]->type == IndexTableSegment)
909             unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
910
911     *nb_sorted_segments = 0;
912
913     /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
914     for (i = 0; i < nb_segments; i++) {
915         int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
916
917         for (j = 0; j < nb_segments; j++) {
918             MXFIndexTableSegment *s = unsorted_segments[j];
919
920             /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
921              * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
922              */
923             if ((i == 0     || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
924                 (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start)) {
925                 best             = j;
926                 best_body_sid    = s->body_sid;
927                 best_index_sid   = s->index_sid;
928                 best_index_start = s->index_start_position;
929             }
930         }
931
932         /* no suitable entry found -> we're done */
933         if (best == -1)
934             break;
935
936         (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
937         last_body_sid    = best_body_sid;
938         last_index_sid   = best_index_sid;
939         last_index_start = best_index_start;
940     }
941
942     av_free(unsorted_segments);
943
944     return 0;
945 }
946
947 static int mxf_parse_index(MXFContext *mxf, int i, AVStream *st)
948 {
949     int64_t accumulated_offset = 0;
950     int j, k, ret, nb_sorted_segments;
951     MXFIndexTableSegment **sorted_segments;
952
953     if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)))
954         return ret;
955
956     for (j = 0; j < nb_sorted_segments; j++) {
957         int n_delta = i;
958         int duration, sample_duration = 1, last_sample_size = 0;
959         int64_t segment_size;
960         MXFIndexTableSegment *tableseg = sorted_segments[j];
961
962         /* reset accumulated_offset on BodySID change */
963         if (j > 0 && tableseg->body_sid != sorted_segments[j-1]->body_sid)
964             accumulated_offset = 0;
965
966         /* HACK: How to correctly link between streams and slices? */
967         if (i < mxf->system_item + st->index)
968             n_delta++;
969         if (n_delta >= tableseg->nb_delta_entries && st->index != 0)
970             continue;
971         duration = tableseg->index_duration > 0 ? tableseg->index_duration :
972             st->duration - st->nb_index_entries;
973         segment_size = tableseg->edit_unit_byte_count * duration;
974         /* check small EditUnitByteCount for audio */
975         if (tableseg->edit_unit_byte_count && tableseg->edit_unit_byte_count < 32
976             && !tableseg->index_duration) {
977             /* duration might be prime relative to the new sample_duration,
978              * which means we need to handle the last frame differently */
979             sample_duration = 8192;
980             last_sample_size = (duration % sample_duration) * tableseg->edit_unit_byte_count;
981             tableseg->edit_unit_byte_count *= sample_duration;
982             duration /= sample_duration;
983             if (last_sample_size) duration++;
984         }
985
986         for (k = 0; k < duration; k++) {
987             int64_t pos;
988             int size, flags = 0;
989
990             if (k < tableseg->nb_index_entries) {
991                 pos = tableseg->stream_offset_entries[k];
992                 if (n_delta < tableseg->nb_delta_entries) {
993                     if (n_delta < tableseg->nb_delta_entries - 1) {
994                         size =
995                             tableseg->slice_offset_entries[k][tableseg->slice[n_delta+1]-1] +
996                             tableseg->element_delta[n_delta+1] -
997                             tableseg->element_delta[n_delta];
998                         if (tableseg->slice[n_delta] > 0)
999                             size -= tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
1000                     } else if (k < duration - 1) {
1001                         size = tableseg->stream_offset_entries[k+1] -
1002                             tableseg->stream_offset_entries[k] -
1003                             tableseg->slice_offset_entries[k][tableseg->slice[tableseg->nb_delta_entries-1]-1] -
1004                             tableseg->element_delta[tableseg->nb_delta_entries-1];
1005                     } else
1006                         size = 0;
1007                     if (tableseg->slice[n_delta] > 0)
1008                         pos += tableseg->slice_offset_entries[k][tableseg->slice[n_delta]-1];
1009                     pos += tableseg->element_delta[n_delta];
1010                 } else
1011                     size = 0;
1012                 flags = !(tableseg->flag_entries[k] & 0x30) ? AVINDEX_KEYFRAME : 0;
1013             } else {
1014                 pos = (int64_t)k * tableseg->edit_unit_byte_count + accumulated_offset;
1015                 if (n_delta < tableseg->nb_delta_entries - 1)
1016                     size = tableseg->element_delta[n_delta+1] - tableseg->element_delta[n_delta];
1017                 else {
1018                     /* use smaller size for last sample if we should */
1019                     if (last_sample_size && k == duration - 1)
1020                         size = last_sample_size;
1021                     else
1022                         size = tableseg->edit_unit_byte_count;
1023                     if (tableseg->nb_delta_entries)
1024                         size -= tableseg->element_delta[tableseg->nb_delta_entries-1];
1025                 }
1026                 if (n_delta < tableseg->nb_delta_entries)
1027                     pos += tableseg->element_delta[n_delta];
1028                 flags = AVINDEX_KEYFRAME;
1029             }
1030
1031             if (k > 0 && pos < mxf->first_essence_length && accumulated_offset == 0)
1032                 pos += mxf->first_essence_kl_length;
1033
1034             pos += mxf->essence_offset;
1035
1036             av_dlog(mxf->fc, "Stream %d IndexEntry %d n_Delta %d Offset %"PRIx64" Timestamp %"PRId64"\n",
1037                     st->index, st->nb_index_entries, n_delta, pos, sample_duration * st->nb_index_entries);
1038
1039             if ((ret = av_add_index_entry(st, pos, sample_duration * st->nb_index_entries, size, 0, flags)) < 0)
1040                 return ret;
1041         }
1042         accumulated_offset += segment_size;
1043     }
1044
1045     av_free(sorted_segments);
1046
1047     return 0;
1048 }
1049
1050 static int mxf_parse_structural_metadata(MXFContext *mxf)
1051 {
1052     MXFPackage *material_package = NULL;
1053     MXFPackage *temp_package = NULL;
1054     int i, j, k, ret;
1055
1056     av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
1057     /* TODO: handle multiple material packages (OP3x) */
1058     for (i = 0; i < mxf->packages_count; i++) {
1059         material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
1060         if (material_package) break;
1061     }
1062     if (!material_package) {
1063         av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
1064         return -1;
1065     }
1066
1067     for (i = 0; i < material_package->tracks_count; i++) {
1068         MXFPackage *source_package = NULL;
1069         MXFTrack *material_track = NULL;
1070         MXFTrack *source_track = NULL;
1071         MXFTrack *temp_track = NULL;
1072         MXFDescriptor *descriptor = NULL;
1073         MXFStructuralComponent *component = NULL;
1074         UID *essence_container_ul = NULL;
1075         const MXFCodecUL *codec_ul = NULL;
1076         const MXFCodecUL *container_ul = NULL;
1077         AVStream *st;
1078
1079         if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
1080             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
1081             continue;
1082         }
1083
1084         if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
1085             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
1086             continue;
1087         }
1088
1089         /* TODO: handle multiple source clips */
1090         for (j = 0; j < material_track->sequence->structural_components_count; j++) {
1091             /* TODO: handle timecode component */
1092             component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
1093             if (!component)
1094                 continue;
1095
1096             for (k = 0; k < mxf->packages_count; k++) {
1097                 temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
1098                 if (!temp_package)
1099                     continue;
1100                 if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
1101                     source_package = temp_package;
1102                     break;
1103                 }
1104             }
1105             if (!source_package) {
1106                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source package found\n", material_track->track_id);
1107                 break;
1108             }
1109             for (k = 0; k < source_package->tracks_count; k++) {
1110                 if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
1111                     av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
1112                     return -1;
1113                 }
1114                 if (temp_track->track_id == component->source_track_id) {
1115                     source_track = temp_track;
1116                     break;
1117                 }
1118             }
1119             if (!source_track) {
1120                 av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
1121                 break;
1122             }
1123         }
1124         if (!source_track)
1125             continue;
1126
1127         if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
1128             av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
1129             return -1;
1130         }
1131
1132         /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
1133          * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
1134         if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
1135             av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
1136             continue;
1137         }
1138
1139         st = avformat_new_stream(mxf->fc, NULL);
1140         if (!st) {
1141             av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
1142             return -1;
1143         }
1144         st->id = source_track->track_id;
1145         st->priv_data = source_track;
1146         st->duration = component->duration;
1147         if (st->duration == -1)
1148             st->duration = AV_NOPTS_VALUE;
1149         st->start_time = component->start_position;
1150         avpriv_set_pts_info(st, 64, material_track->edit_rate.num, material_track->edit_rate.den);
1151
1152         PRINT_KEY(mxf->fc, "data definition   ul", source_track->sequence->data_definition_ul);
1153         codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
1154         st->codec->codec_type = codec_ul->id;
1155
1156         source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
1157         if (source_package->descriptor) {
1158             if (source_package->descriptor->type == MultipleDescriptor) {
1159                 for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
1160                     MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
1161
1162                     if (!sub_descriptor) {
1163                         av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
1164                         continue;
1165                     }
1166                     if (sub_descriptor->linked_track_id == source_track->track_id) {
1167                         descriptor = sub_descriptor;
1168                         break;
1169                     }
1170                 }
1171             } else if (source_package->descriptor->type == Descriptor)
1172                 descriptor = source_package->descriptor;
1173         }
1174         if (!descriptor) {
1175             av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
1176             continue;
1177         }
1178         PRINT_KEY(mxf->fc, "essence codec     ul", descriptor->essence_codec_ul);
1179         PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
1180         essence_container_ul = &descriptor->essence_container_ul;
1181         /* HACK: replacing the original key with mxf_encrypted_essence_container
1182          * is not allowed according to s429-6, try to find correct information anyway */
1183         if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
1184             av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
1185             for (k = 0; k < mxf->metadata_sets_count; k++) {
1186                 MXFMetadataSet *metadata = mxf->metadata_sets[k];
1187                 if (metadata->type == CryptoContext) {
1188                     essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
1189                     break;
1190                 }
1191             }
1192         }
1193         /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
1194         codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
1195         st->codec->codec_id = codec_ul->id;
1196         if (descriptor->extradata) {
1197             st->codec->extradata = descriptor->extradata;
1198             st->codec->extradata_size = descriptor->extradata_size;
1199         }
1200         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1201             container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
1202             if (st->codec->codec_id == CODEC_ID_NONE)
1203                 st->codec->codec_id = container_ul->id;
1204             st->codec->width = descriptor->width;
1205             st->codec->height = descriptor->height;
1206             if (st->codec->codec_id == CODEC_ID_RAWVIDEO)
1207                 st->codec->pix_fmt = descriptor->pix_fmt;
1208             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1209         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1210             container_ul = mxf_get_codec_ul(mxf_essence_container_uls, essence_container_ul);
1211             if (st->codec->codec_id == CODEC_ID_NONE)
1212                 st->codec->codec_id = container_ul->id;
1213             st->codec->channels = descriptor->channels;
1214             st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
1215             st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
1216             /* TODO: implement CODEC_ID_RAWAUDIO */
1217             if (st->codec->codec_id == CODEC_ID_PCM_S16LE) {
1218                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1219                     st->codec->codec_id = CODEC_ID_PCM_S24LE;
1220                 else if (descriptor->bits_per_sample == 32)
1221                     st->codec->codec_id = CODEC_ID_PCM_S32LE;
1222             } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
1223                 if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
1224                     st->codec->codec_id = CODEC_ID_PCM_S24BE;
1225                 else if (descriptor->bits_per_sample == 32)
1226                     st->codec->codec_id = CODEC_ID_PCM_S32BE;
1227             } else if (st->codec->codec_id == CODEC_ID_MP2) {
1228                 st->need_parsing = AVSTREAM_PARSE_FULL;
1229             }
1230         }
1231         if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
1232             av_log(mxf->fc, AV_LOG_WARNING, "only frame wrapped mappings are correctly supported\n");
1233             st->need_parsing = AVSTREAM_PARSE_FULL;
1234         }
1235
1236         if ((ret = mxf_parse_index(mxf, i, st)))
1237             return ret;
1238     }
1239     return 0;
1240 }
1241
1242 static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
1243     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
1244     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
1245     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
1246     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
1247     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
1248     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
1249     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
1250     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
1251     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
1252     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
1253     { { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
1254     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
1255     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
1256     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
1257     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
1258     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
1259     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
1260     { { 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 */
1261     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
1262     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
1263     { { 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 */
1264     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
1265     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
1266     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
1267     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
1268     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
1269     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
1270     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
1271 };
1272
1273 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
1274 {
1275     AVIOContext *pb = mxf->fc->pb;
1276     MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
1277     uint64_t klv_end = avio_tell(pb) + klv->length;
1278
1279     if (!ctx)
1280         return -1;
1281     while (avio_tell(pb) + 4 < klv_end) {
1282         int tag = avio_rb16(pb);
1283         int size = avio_rb16(pb); /* KLV specified by 0x53 */
1284         uint64_t next = avio_tell(pb) + size;
1285         UID uid = {0};
1286
1287         av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
1288         if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
1289             av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
1290             continue;
1291         }
1292         if (tag > 0x7FFF) { /* dynamic tag */
1293             int i;
1294             for (i = 0; i < mxf->local_tags_count; i++) {
1295                 int local_tag = AV_RB16(mxf->local_tags+i*18);
1296                 if (local_tag == tag) {
1297                     memcpy(uid, mxf->local_tags+i*18+2, 16);
1298                     av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
1299                     PRINT_KEY(mxf->fc, "uid", uid);
1300                 }
1301             }
1302         }
1303         if (ctx_size && tag == 0x3C0A)
1304             avio_read(pb, ctx->uid, 16);
1305         else if (read_child(ctx, pb, tag, size, uid) < 0)
1306             return -1;
1307
1308         avio_seek(pb, next, SEEK_SET);
1309     }
1310     if (ctx_size) ctx->type = type;
1311     return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
1312 }
1313
1314 /**
1315  * Seeks to the previous partition, if possible
1316  * @return <= 0 if we should stop parsing, > 0 if we should keep going
1317  */
1318 static int mxf_seek_to_previous_partition(MXFContext *mxf)
1319 {
1320     AVIOContext *pb = mxf->fc->pb;
1321
1322     if (!mxf->current_partition ||
1323         mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
1324         return 0;   /* we've parsed all partitions */
1325
1326     /* seek to previous partition */
1327     avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
1328     mxf->current_partition = NULL;
1329
1330     av_dlog(mxf->fc, "seeking to previous partition\n");
1331
1332     return 1;
1333 }
1334
1335 /**
1336  * Called when essence is encountered
1337  * @return <= 0 if we should stop parsing, > 0 if we should keep going
1338  */
1339 static int mxf_parse_handle_essence(MXFContext *mxf)
1340 {
1341     AVIOContext *pb = mxf->fc->pb;
1342     int64_t ret;
1343
1344     if (!mxf->current_partition) {
1345         av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to PartitionPack\n");
1346         return AVERROR_INVALIDDATA;
1347     }
1348
1349     if (mxf->parsing_backward) {
1350         return mxf_seek_to_previous_partition(mxf);
1351     } else {
1352         if (!mxf->footer_partition) {
1353             av_dlog(mxf->fc, "no footer\n");
1354             return 0;
1355         }
1356
1357         av_dlog(mxf->fc, "seeking to footer\n");
1358
1359         /* remember where we were so we don't end up seeking further back than this */
1360         mxf->last_forward_tell = avio_tell(pb);
1361
1362         if (!pb->seekable) {
1363             av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing footer\n");
1364             return -1;
1365         }
1366
1367         /* seek to footer partition and parse backward */
1368         if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
1369             av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to footer @ 0x%"PRIx64" (%"PRId64") - partial file?\n",
1370                    mxf->run_in + mxf->footer_partition, ret);
1371             return ret;
1372         }
1373
1374         mxf->current_partition = NULL;
1375         mxf->parsing_backward = 1;
1376     }
1377
1378     return 1;
1379 }
1380
1381 /**
1382  * Called when the next partition or EOF is encountered
1383  * @return <= 0 if we should stop parsing, > 0 if we should keep going
1384  */
1385 static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
1386 {
1387     return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
1388 }
1389
1390 static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)
1391 {
1392     MXFContext *mxf = s->priv_data;
1393     KLVPacket klv;
1394
1395     mxf->last_forward_tell = INT64_MAX;
1396
1397     if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
1398         av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
1399         return -1;
1400     }
1401     avio_seek(s->pb, -14, SEEK_CUR);
1402     mxf->fc = s;
1403     mxf->run_in = avio_tell(s->pb);
1404
1405     while (!url_feof(s->pb)) {
1406         const MXFMetadataReadTableEntry *metadata;
1407
1408         if (klv_read_packet(&klv, s->pb) < 0) {
1409             /* EOF - seek to previous partition or stop */
1410             if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
1411                 break;
1412             else
1413                 continue;
1414         }
1415
1416         PRINT_KEY(s, "read header", klv.key);
1417         av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
1418         if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
1419             IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
1420             IS_KLV_KEY(klv.key, mxf_system_item_key)) {
1421         if (IS_KLV_KEY(klv.key, mxf_system_item_key)) {
1422             mxf->system_item = 1;
1423         }
1424
1425             if (!mxf->essence_offset)
1426                 mxf->essence_offset = klv.offset;
1427
1428             if (!mxf->first_essence_kl_length && IS_KLV_KEY(klv.key, mxf_essence_element_key)) {
1429                 mxf->first_essence_kl_length = avio_tell(s->pb) - klv.offset;
1430                 mxf->first_essence_length = klv.length;
1431             }
1432
1433             /* seek to footer, previous partition or stop */
1434             if (mxf_parse_handle_essence(mxf) <= 0)
1435                 break;
1436             continue;
1437         } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
1438                    klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
1439             /* next partition pack - keep going, seek to previous partition or stop */
1440             if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
1441                 break;
1442         }
1443
1444         for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
1445             if (IS_KLV_KEY(klv.key, metadata->key)) {
1446                 int res;
1447                 if (klv.key[5] == 0x53) {
1448                     res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
1449                 } else {
1450                     uint64_t next = avio_tell(s->pb) + klv.length;
1451                     res = metadata->read(mxf, s->pb, 0, 0, klv.key);
1452                     avio_seek(s->pb, next, SEEK_SET);
1453                 }
1454                 if (res < 0) {
1455                     av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
1456                     return -1;
1457                 }
1458                 break;
1459             }
1460         }
1461         if (!metadata->read)
1462             avio_skip(s->pb, klv.length);
1463     }
1464     /* FIXME avoid seek */
1465     if (!mxf->essence_offset)  {
1466         av_log(s, AV_LOG_ERROR, "no essence\n");
1467         return AVERROR_INVALIDDATA;
1468     }
1469     avio_seek(s->pb, mxf->essence_offset, SEEK_SET);
1470     return mxf_parse_structural_metadata(mxf);
1471 }
1472
1473 static int mxf_read_close(AVFormatContext *s)
1474 {
1475     MXFContext *mxf = s->priv_data;
1476     MXFIndexTableSegment *seg;
1477     int i, j;
1478
1479     av_freep(&mxf->packages_refs);
1480
1481     for (i = 0; i < s->nb_streams; i++)
1482         s->streams[i]->priv_data = NULL;
1483
1484     for (i = 0; i < mxf->metadata_sets_count; i++) {
1485         switch (mxf->metadata_sets[i]->type) {
1486         case MultipleDescriptor:
1487             av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
1488             break;
1489         case Sequence:
1490             av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
1491             break;
1492         case SourcePackage:
1493         case MaterialPackage:
1494             av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
1495             break;
1496         case IndexTableSegment:
1497             seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
1498             for (j = 0; j < seg->nb_index_entries; j++)
1499                 av_freep(&seg->slice_offset_entries[j]);
1500             av_freep(&seg->slice);
1501             av_freep(&seg->element_delta);
1502             av_freep(&seg->flag_entries);
1503             av_freep(&seg->stream_offset_entries);
1504             av_freep(&seg->slice_offset_entries);
1505             break;
1506         default:
1507             break;
1508         }
1509         av_freep(&mxf->metadata_sets[i]);
1510     }
1511     av_freep(&mxf->partitions);
1512     av_freep(&mxf->metadata_sets);
1513     av_freep(&mxf->aesc);
1514     av_freep(&mxf->local_tags);
1515     return 0;
1516 }
1517
1518 static int mxf_probe(AVProbeData *p) {
1519     uint8_t *bufp = p->buf;
1520     uint8_t *end = p->buf + p->buf_size;
1521
1522     if (p->buf_size < sizeof(mxf_header_partition_pack_key))
1523         return 0;
1524
1525     /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
1526     end -= sizeof(mxf_header_partition_pack_key);
1527     for (; bufp < end; bufp++) {
1528         if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
1529             return AVPROBE_SCORE_MAX;
1530     }
1531     return 0;
1532 }
1533
1534 /* rudimentary byte seek */
1535 /* XXX: use MXF Index */
1536 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1537 {
1538     AVStream *st = s->streams[stream_index];
1539     int64_t seconds;
1540
1541     if (!s->bit_rate)
1542         return -1;
1543     if (sample_time < 0)
1544         sample_time = 0;
1545     seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
1546     if (avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET) < 0)
1547         return -1;
1548     ff_update_cur_dts(s, st, sample_time);
1549     return 0;
1550 }
1551
1552 AVInputFormat ff_mxf_demuxer = {
1553     .name           = "mxf",
1554     .long_name      = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1555     .priv_data_size = sizeof(MXFContext),
1556     .read_probe     = mxf_probe,
1557     .read_header    = mxf_read_header,
1558     .read_packet    = mxf_read_packet,
1559     .read_close     = mxf_read_close,
1560     .read_seek      = mxf_read_seek,
1561 };