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