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