FFmpeg
mxfdec.c
Go to the documentation of this file.
1 /*
2  * MXF demuxer.
3  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 /*
23  * References
24  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
25  * SMPTE 377M MXF File Format Specifications
26  * SMPTE 378M Operational Pattern 1a
27  * SMPTE 379M MXF Generic Container
28  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29  * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
30  * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
31  * SMPTE 2067-21 Interoperable Master Format — Application #2E
32  *
33  * Principle
34  * Search for Track numbers which will identify essence element KLV packets.
35  * Search for SourcePackage which define tracks which contains Track numbers.
36  * Material Package contains tracks with reference to SourcePackage tracks.
37  * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
38  * Assign Descriptors to correct Tracks.
39  *
40  * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
41  * Metadata parsing resolves Strong References to objects.
42  *
43  * Simple demuxer, only OP1A supported and some files might not work at all.
44  * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
45  */
46 
47 #include <inttypes.h>
48 
49 #include "libavutil/aes.h"
50 #include "libavutil/avstring.h"
52 #include "libavutil/mathematics.h"
53 #include "libavcodec/bytestream.h"
54 #include "libavutil/intreadwrite.h"
55 #include "libavutil/parseutils.h"
56 #include "libavutil/timecode.h"
57 #include "libavutil/opt.h"
58 #include "avformat.h"
59 #include "internal.h"
60 #include "mxf.h"
61 
62 #define MXF_MAX_CHUNK_SIZE (32 << 20)
63 
64 typedef enum {
69 
70 typedef enum {
71  OP1a = 1,
81  OPSONYOpt, /* FATE sample, violates the spec in places */
82 } MXFOP;
83 
84 typedef enum {
89 
90 typedef struct MXFPartition {
91  int closed;
92  int complete;
95  int index_sid;
96  int body_sid;
97  int64_t this_partition;
98  int64_t essence_offset; ///< absolute offset of essence
99  int64_t essence_length;
104  int64_t pack_ofs; ///< absolute offset of pack in file, including run-in
105  int64_t body_offset;
107 } MXFPartition;
108 
109 typedef struct MXFMetadataSet {
111  uint64_t partition_score;
114 
115 typedef struct MXFCryptoContext {
119 
120 typedef struct MXFStructuralComponent {
125  int64_t duration;
126  int64_t start_position;
129 
130 typedef struct MXFSequence {
135  int64_t duration;
136  uint8_t origin;
137 } MXFSequence;
138 
139 typedef struct MXFTimecodeComponent {
143  struct AVRational rate;
146 
147 typedef struct {
151 
152 typedef struct {
156  int64_t duration;
158 
159 typedef struct {
161  char *name;
162  char *value;
164 
165 typedef struct {
167  MXFSequence *sequence; /* mandatory, and only one */
169  int track_id;
170  char *name;
171  uint8_t track_number[4];
174  uint64_t sample_count;
175  int64_t original_duration; /* st->duration in SampleRate/EditRate units */
177  int body_sid;
179  int edit_units_per_packet; /* how many edit units to read at a time (PCM, ClipWrapped) */
180 } MXFTrack;
181 
182 typedef struct MXFDescriptor {
189  int width;
190  int height; /* Field height, not frame height */
191  int frame_layout; /* See MXFFrameLayout enum */
193 #define MXF_FIELD_DOMINANCE_DEFAULT 0
194 #define MXF_FIELD_DOMINANCE_FF 1 /* coded first, displayed first */
195 #define MXF_FIELD_DOMINANCE_FL 2 /* coded first, displayed last */
197  int channels;
199  int64_t duration; /* ContainerDuration optional property */
200  unsigned int component_depth;
201  unsigned int black_ref_level;
202  unsigned int white_ref_level;
203  unsigned int color_range;
204  unsigned int horiz_subsampling;
205  unsigned int vert_subsampling;
209  uint8_t *extradata;
217  size_t coll_size;
218 } MXFDescriptor;
219 
220 typedef struct MXFIndexTableSegment {
224  int body_sid;
227  uint64_t index_duration;
233 
234 typedef struct MXFPackage {
240  MXFDescriptor *descriptor; /* only one */
242  char *name;
245 } MXFPackage;
246 
247 typedef struct MXFEssenceContainerData {
252  int body_sid;
254 
255 /* decoded index table */
256 typedef struct MXFIndexTable {
258  int body_sid;
259  int nb_ptses; /* number of PTSes or total duration of index */
260  int64_t first_dts; /* DTS = EditUnit + first_dts */
261  int64_t *ptses; /* maps EditUnit -> PTS */
263  MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */
264  AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */
265  int8_t *offsets; /* temporal offsets for display order to stored order conversion */
266 } MXFIndexTable;
267 
268 typedef struct MXFContext {
269  const AVClass *class; /**< Class for private options. */
280  struct AVAES *aesc;
281  uint8_t *local_tags;
285  int run_in;
293 } MXFContext;
294 
295 /* NOTE: klv_offset is not set (-1) for local keys */
296 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
297 
299  const UID key;
301  int ctx_size;
304 
305 /* partial keys to match */
306 static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
307 static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
308 static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
309 static const uint8_t mxf_canopus_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x0a,0x0e,0x0f,0x03,0x01 };
310 static const uint8_t mxf_system_item_key_cp[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x03,0x01,0x04 };
311 static const uint8_t mxf_system_item_key_gc[] = { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x03,0x01,0x14 };
312 static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
313 static const uint8_t mxf_apple_coll_prefix[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x0e,0x20,0x04,0x01,0x05,0x03,0x01 };
314 /* complete keys to match */
315 static const uint8_t mxf_crypto_source_container_ul[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x02,0x02,0x00,0x00,0x00 };
316 static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
317 static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
318 static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
319 static const uint8_t mxf_avid_project_name[] = { 0xa5,0xfb,0x7b,0x25,0xf6,0x15,0x94,0xb9,0x62,0xfc,0x37,0x17,0x49,0x2d,0x42,0xbf };
320 static const uint8_t mxf_jp2k_rsiz[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0a,0x04,0x01,0x06,0x03,0x01,0x00,0x00,0x00 };
321 static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
322 static const uint8_t mxf_indirect_value_utf16be[] = { 0x42,0x01,0x10,0x02,0x00,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
323 static const uint8_t mxf_apple_coll_max_cll[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x0e,0x20,0x04,0x01,0x05,0x03,0x01,0x01 };
324 static const uint8_t mxf_apple_coll_max_fall[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x0e,0x20,0x04,0x01,0x05,0x03,0x01,0x02 };
325 
327 static const uint8_t mxf_mastering_display_uls[4][16] = {
332 };
333 
334 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
335 
336 static void mxf_free_metadataset(MXFMetadataSet **ctx, int freectx)
337 {
339  switch ((*ctx)->type) {
340  case Descriptor:
341  case MultipleDescriptor:
342  av_freep(&((MXFDescriptor *)*ctx)->extradata);
343  av_freep(&((MXFDescriptor *)*ctx)->mastering);
344  av_freep(&((MXFDescriptor *)*ctx)->coll);
345  av_freep(&((MXFDescriptor *)*ctx)->file_descriptors_refs);
346  break;
347  case Sequence:
348  av_freep(&((MXFSequence *)*ctx)->structural_components_refs);
349  break;
350  case EssenceGroup:
351  av_freep(&((MXFEssenceGroup *)*ctx)->structural_components_refs);
352  break;
353  case SourcePackage:
354  case MaterialPackage:
355  av_freep(&((MXFPackage *)*ctx)->tracks_refs);
356  av_freep(&((MXFPackage *)*ctx)->name);
357  av_freep(&((MXFPackage *)*ctx)->comment_refs);
358  break;
359  case TaggedValue:
360  av_freep(&((MXFTaggedValue *)*ctx)->name);
361  av_freep(&((MXFTaggedValue *)*ctx)->value);
362  break;
363  case Track:
364  av_freep(&((MXFTrack *)*ctx)->name);
365  break;
366  case IndexTableSegment:
367  seg = (MXFIndexTableSegment *)*ctx;
369  av_freep(&seg->flag_entries);
371  default:
372  break;
373  }
374  if (freectx) {
375  av_freep(ctx);
376  }
377 }
378 
380 {
381  uint64_t size = avio_r8(pb);
382  if (size & 0x80) { /* long form */
383  int bytes_num = size & 0x7f;
384  /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
385  if (bytes_num > 8)
386  return AVERROR_INVALIDDATA;
387  size = 0;
388  while (bytes_num--)
389  size = size << 8 | avio_r8(pb);
390  }
391  if (size > INT64_MAX)
392  return AVERROR_INVALIDDATA;
393  return size;
394 }
395 
396 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
397 {
398  int i, b;
399  for (i = 0; i < size && !avio_feof(pb); i++) {
400  b = avio_r8(pb);
401  if (b == key[0])
402  i = 0;
403  else if (b != key[i])
404  i = -1;
405  }
406  return i == size;
407 }
408 
409 static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
410 {
411  int64_t length, pos;
412  if (!mxf_read_sync(pb, mxf_klv_key, 4))
413  return AVERROR_INVALIDDATA;
414  klv->offset = avio_tell(pb) - 4;
415  memcpy(klv->key, mxf_klv_key, 4);
416  avio_read(pb, klv->key + 4, 12);
417  length = klv_decode_ber_length(pb);
418  if (length < 0)
419  return length;
420  klv->length = length;
421  pos = avio_tell(pb);
422  if (pos > INT64_MAX - length)
423  return AVERROR_INVALIDDATA;
424  klv->next_klv = pos + length;
425  return 0;
426 }
427 
428 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv, int body_sid)
429 {
430  int i;
431 
432  for (i = 0; i < s->nb_streams; i++) {
433  MXFTrack *track = s->streams[i]->priv_data;
434  /* SMPTE 379M 7.3 */
435  if (track && (!body_sid || !track->body_sid || track->body_sid == body_sid) && !memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
436  return i;
437  }
438  /* return 0 if only one stream, for OP Atom files with 0 as track number */
439  return s->nb_streams == 1 && s->streams[0]->priv_data ? 0 : -1;
440 }
441 
443 {
444  // we look for partition where the offset is placed
445  int a, b, m;
446  int64_t pack_ofs;
447 
448  a = -1;
449  b = mxf->partitions_count;
450 
451  while (b - a > 1) {
452  m = (a + b) >> 1;
453  pack_ofs = mxf->partitions[m].pack_ofs;
454  if (pack_ofs <= offset)
455  a = m;
456  else
457  b = m;
458  }
459 
460  if (a == -1)
461  return 0;
462  return mxf->partitions[a].body_sid;
463 }
464 
465 static int mxf_get_eia608_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt, int64_t length)
466 {
467  int count = avio_rb16(s->pb);
468  int cdp_identifier, cdp_length, cdp_footer_id, ccdata_id, cc_count;
469  int line_num, sample_coding, sample_count;
470  int did, sdid, data_length;
471  int i, ret;
472 
473  if (count != 1)
474  av_log(s, AV_LOG_WARNING, "unsupported multiple ANC packets (%d) per KLV packet\n", count);
475 
476  for (i = 0; i < count; i++) {
477  if (length < 6) {
478  av_log(s, AV_LOG_ERROR, "error reading s436m packet %"PRId64"\n", length);
479  return AVERROR_INVALIDDATA;
480  }
481  line_num = avio_rb16(s->pb);
482  avio_r8(s->pb); // wrapping type
483  sample_coding = avio_r8(s->pb);
484  sample_count = avio_rb16(s->pb);
485  length -= 6 + 8 + sample_count;
486  if (line_num != 9 && line_num != 11)
487  continue;
488  if (sample_coding == 7 || sample_coding == 8 || sample_coding == 9) {
489  av_log(s, AV_LOG_WARNING, "unsupported s436m 10 bit sample coding\n");
490  continue;
491  }
492  if (length < 0)
493  return AVERROR_INVALIDDATA;
494 
495  avio_rb32(s->pb); // array count
496  avio_rb32(s->pb); // array elem size
497  did = avio_r8(s->pb);
498  sdid = avio_r8(s->pb);
499  data_length = avio_r8(s->pb);
500  if (did != 0x61 || sdid != 1) {
501  av_log(s, AV_LOG_WARNING, "unsupported did or sdid: %x %x\n", did, sdid);
502  continue;
503  }
504  cdp_identifier = avio_rb16(s->pb); // cdp id
505  if (cdp_identifier != 0x9669) {
506  av_log(s, AV_LOG_ERROR, "wrong cdp identifier %x\n", cdp_identifier);
507  return AVERROR_INVALIDDATA;
508  }
509  cdp_length = avio_r8(s->pb);
510  avio_r8(s->pb); // cdp_frame_rate
511  avio_r8(s->pb); // cdp_flags
512  avio_rb16(s->pb); // cdp_hdr_sequence_cntr
513  ccdata_id = avio_r8(s->pb); // ccdata_id
514  if (ccdata_id != 0x72) {
515  av_log(s, AV_LOG_ERROR, "wrong cdp data section %x\n", ccdata_id);
516  return AVERROR_INVALIDDATA;
517  }
518  cc_count = avio_r8(s->pb) & 0x1f;
519  ret = av_get_packet(s->pb, pkt, cc_count * 3);
520  if (ret < 0)
521  return ret;
522  if (cdp_length - 9 - 4 < cc_count * 3) {
523  av_log(s, AV_LOG_ERROR, "wrong cdp size %d cc count %d\n", cdp_length, cc_count);
524  return AVERROR_INVALIDDATA;
525  }
526  avio_skip(s->pb, data_length - 9 - 4 - cc_count * 3);
527  cdp_footer_id = avio_r8(s->pb);
528  if (cdp_footer_id != 0x74) {
529  av_log(s, AV_LOG_ERROR, "wrong cdp footer section %x\n", cdp_footer_id);
530  return AVERROR_INVALIDDATA;
531  }
532  avio_rb16(s->pb); // cdp_ftr_sequence_cntr
533  avio_r8(s->pb); // packet_checksum
534  break;
535  }
536 
537  return 0;
538 }
539 
540 /* XXX: use AVBitStreamFilter */
541 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
542 {
543  const uint8_t *buf_ptr, *end_ptr;
544  uint8_t *data_ptr;
545  int i;
546 
547  if (length > 61444) /* worst case PAL 1920 samples 8 channels */
548  return AVERROR_INVALIDDATA;
549  length = av_get_packet(pb, pkt, length);
550  if (length < 0)
551  return length;
552  data_ptr = pkt->data;
553  end_ptr = pkt->data + length;
554  buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
555 
556  if (st->codecpar->channels > 8)
557  return AVERROR_INVALIDDATA;
558 
559  for (; end_ptr - buf_ptr >= st->codecpar->channels * 4; ) {
560  for (i = 0; i < st->codecpar->channels; i++) {
561  uint32_t sample = bytestream_get_le32(&buf_ptr);
562  if (st->codecpar->bits_per_coded_sample == 24)
563  bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
564  else
565  bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
566  }
567  buf_ptr += 32 - st->codecpar->channels*4; // always 8 channels stored SMPTE 331M
568  }
569  av_shrink_packet(pkt, data_ptr - pkt->data);
570  return 0;
571 }
572 
574 {
575  static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
576  MXFContext *mxf = s->priv_data;
577  AVIOContext *pb = s->pb;
578  int64_t end = avio_tell(pb) + klv->length;
579  int64_t size;
580  uint64_t orig_size;
581  uint64_t plaintext_size;
582  uint8_t ivec[16];
583  uint8_t tmpbuf[16];
584  int index;
585  int body_sid;
586 
587  if (!mxf->aesc && s->key && s->keylen == 16) {
588  mxf->aesc = av_aes_alloc();
589  if (!mxf->aesc)
590  return AVERROR(ENOMEM);
591  av_aes_init(mxf->aesc, s->key, 128, 1);
592  }
593  // crypto context
595  if (size < 0)
596  return size;
597  avio_skip(pb, size);
598  // plaintext offset
600  plaintext_size = avio_rb64(pb);
601  // source klv key
603  avio_read(pb, klv->key, 16);
605  return AVERROR_INVALIDDATA;
606 
607  body_sid = find_body_sid_by_absolute_offset(mxf, klv->offset);
608  index = mxf_get_stream_index(s, klv, body_sid);
609  if (index < 0)
610  return AVERROR_INVALIDDATA;
611  // source size
613  orig_size = avio_rb64(pb);
614  if (orig_size < plaintext_size)
615  return AVERROR_INVALIDDATA;
616  // enc. code
618  if (size < 32 || size - 32 < orig_size || (int)orig_size != orig_size)
619  return AVERROR_INVALIDDATA;
620  avio_read(pb, ivec, 16);
621  avio_read(pb, tmpbuf, 16);
622  if (mxf->aesc)
623  av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
624  if (memcmp(tmpbuf, checkv, 16))
625  av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
626  size -= 32;
627  size = av_get_packet(pb, pkt, size);
628  if (size < 0)
629  return size;
630  else if (size < plaintext_size)
631  return AVERROR_INVALIDDATA;
632  size -= plaintext_size;
633  if (mxf->aesc)
634  av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
635  &pkt->data[plaintext_size], size >> 4, ivec, 1);
636  av_shrink_packet(pkt, orig_size);
638  avio_skip(pb, end - avio_tell(pb));
639  return 0;
640 }
641 
642 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
643 {
644  MXFContext *mxf = arg;
645  int item_num = avio_rb32(pb);
646  int item_len = avio_rb32(pb);
647 
648  if (item_len != 18) {
649  avpriv_request_sample(pb, "Primer pack item length %d", item_len);
650  return AVERROR_PATCHWELCOME;
651  }
652  if (item_num > 65536 || item_num < 0) {
653  av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num);
654  return AVERROR_INVALIDDATA;
655  }
656  if (mxf->local_tags)
657  av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n");
658  av_free(mxf->local_tags);
659  mxf->local_tags_count = 0;
660  mxf->local_tags = av_calloc(item_num, item_len);
661  if (!mxf->local_tags)
662  return AVERROR(ENOMEM);
663  mxf->local_tags_count = item_num;
664  avio_read(pb, mxf->local_tags, item_num*item_len);
665  return 0;
666 }
667 
668 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
669 {
670  MXFContext *mxf = arg;
671  AVFormatContext *s = mxf->fc;
672  MXFPartition *partition, *tmp_part;
673  UID op;
674  uint64_t footer_partition;
675  uint32_t nb_essence_containers;
676 
677  if (mxf->partitions_count >= INT_MAX / 2)
678  return AVERROR_INVALIDDATA;
679 
680  tmp_part = av_realloc_array(mxf->partitions, mxf->partitions_count + 1, sizeof(*mxf->partitions));
681  if (!tmp_part)
682  return AVERROR(ENOMEM);
683  mxf->partitions = tmp_part;
684 
685  if (mxf->parsing_backward) {
686  /* insert the new partition pack in the middle
687  * this makes the entries in mxf->partitions sorted by offset */
688  memmove(&mxf->partitions[mxf->last_forward_partition+1],
690  (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
691  partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
692  } else {
693  mxf->last_forward_partition++;
694  partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
695  }
696 
697  memset(partition, 0, sizeof(*partition));
698  mxf->partitions_count++;
699  partition->pack_length = avio_tell(pb) - klv_offset + size;
700  partition->pack_ofs = klv_offset;
701 
702  switch(uid[13]) {
703  case 2:
704  partition->type = Header;
705  break;
706  case 3:
707  partition->type = BodyPartition;
708  break;
709  case 4:
710  partition->type = Footer;
711  break;
712  default:
713  av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
714  return AVERROR_INVALIDDATA;
715  }
716 
717  /* consider both footers to be closed (there is only Footer and CompleteFooter) */
718  partition->closed = partition->type == Footer || !(uid[14] & 1);
719  partition->complete = uid[14] > 2;
720  avio_skip(pb, 4);
721  partition->kag_size = avio_rb32(pb);
722  partition->this_partition = avio_rb64(pb);
723  partition->previous_partition = avio_rb64(pb);
724  footer_partition = avio_rb64(pb);
725  partition->header_byte_count = avio_rb64(pb);
726  partition->index_byte_count = avio_rb64(pb);
727  partition->index_sid = avio_rb32(pb);
728  partition->body_offset = avio_rb64(pb);
729  partition->body_sid = avio_rb32(pb);
730  if (avio_read(pb, op, sizeof(UID)) != sizeof(UID)) {
731  av_log(mxf->fc, AV_LOG_ERROR, "Failed reading UID\n");
732  return AVERROR_INVALIDDATA;
733  }
734  nb_essence_containers = avio_rb32(pb);
735 
736  if (partition->type == Header) {
737  char str[36];
738  snprintf(str, sizeof(str), "%08x.%08x.%08x.%08x", AV_RB32(&op[0]), AV_RB32(&op[4]), AV_RB32(&op[8]), AV_RB32(&op[12]));
739  av_dict_set(&s->metadata, "operational_pattern_ul", str, 0);
740  }
741 
742  if (partition->this_partition &&
743  partition->previous_partition == partition->this_partition) {
744  av_log(mxf->fc, AV_LOG_ERROR,
745  "PreviousPartition equal to ThisPartition %"PRIx64"\n",
746  partition->previous_partition);
747  /* override with the actual previous partition offset */
748  if (!mxf->parsing_backward && mxf->last_forward_partition > 1) {
749  MXFPartition *prev =
750  mxf->partitions + mxf->last_forward_partition - 2;
751  partition->previous_partition = prev->this_partition;
752  }
753  /* if no previous body partition are found point to the header
754  * partition */
755  if (partition->previous_partition == partition->this_partition)
756  partition->previous_partition = 0;
757  av_log(mxf->fc, AV_LOG_ERROR,
758  "Overriding PreviousPartition with %"PRIx64"\n",
759  partition->previous_partition);
760  }
761 
762  /* some files don't have FooterPartition set in every partition */
763  if (footer_partition) {
764  if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
765  av_log(mxf->fc, AV_LOG_ERROR,
766  "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",
767  mxf->footer_partition, footer_partition);
768  } else {
769  mxf->footer_partition = footer_partition;
770  }
771  }
772 
773  av_log(mxf->fc, AV_LOG_TRACE,
774  "PartitionPack: ThisPartition = 0x%"PRIX64
775  ", PreviousPartition = 0x%"PRIX64", "
776  "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",
777  partition->this_partition,
778  partition->previous_partition, footer_partition,
779  partition->index_sid, partition->body_sid);
780 
781  /* sanity check PreviousPartition if set */
782  //NOTE: this isn't actually enough, see mxf_seek_to_previous_partition()
783  if (partition->previous_partition &&
784  mxf->run_in + partition->previous_partition >= klv_offset) {
785  av_log(mxf->fc, AV_LOG_ERROR,
786  "PreviousPartition points to this partition or forward\n");
787  return AVERROR_INVALIDDATA;
788  }
789 
790  if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
791  else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
792  else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
793  else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
794  else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
795  else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
796  else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
797  else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
798  else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
799  else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
800  else if (op[12] == 0x10) {
801  /* SMPTE 390m: "There shall be exactly one essence container"
802  * The following block deals with files that violate this, namely:
803  * 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a
804  * abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */
805  if (nb_essence_containers != 1) {
806  MXFOP op = nb_essence_containers ? OP1a : OPAtom;
807 
808  /* only nag once */
809  if (!mxf->op)
810  av_log(mxf->fc, AV_LOG_WARNING,
811  "\"OPAtom\" with %"PRIu32" ECs - assuming %s\n",
812  nb_essence_containers,
813  op == OP1a ? "OP1a" : "OPAtom");
814 
815  mxf->op = op;
816  } else
817  mxf->op = OPAtom;
818  } else {
819  av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
820  mxf->op = OP1a;
821  }
822 
823  if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
824  av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %"PRId32" - guessing ",
825  partition->kag_size);
826 
827  if (mxf->op == OPSONYOpt)
828  partition->kag_size = 512;
829  else
830  partition->kag_size = 1;
831 
832  av_log(mxf->fc, AV_LOG_WARNING, "%"PRId32"\n", partition->kag_size);
833  }
834 
835  return 0;
836 }
837 
838 static uint64_t partition_score(MXFPartition *p)
839 {
840  uint64_t score;
841  if (!p)
842  return 0;
843  if (p->type == Footer)
844  score = 5;
845  else if (p->complete)
846  score = 4;
847  else if (p->closed)
848  score = 3;
849  else
850  score = 1;
851  return (score << 60) | ((uint64_t)p->this_partition >> 4);
852 }
853 
854 static int mxf_add_metadata_set(MXFContext *mxf, MXFMetadataSet **metadata_set)
855 {
857  enum MXFMetadataSetType type = (*metadata_set)->type;
858 
859  // Index Table is special because it might be added manually without
860  // partition and we iterate thorugh all instances of them. Also some files
861  // use the same Instance UID for different index tables...
862  if (type != IndexTableSegment) {
863  for (int i = 0; i < mxf->metadata_sets_count; i++) {
864  if (!memcmp((*metadata_set)->uid, mxf->metadata_sets[i]->uid, 16) && type == mxf->metadata_sets[i]->type) {
865  uint64_t old_s = mxf->metadata_sets[i]->partition_score;
866  uint64_t new_s = (*metadata_set)->partition_score;
867  if (old_s > new_s) {
868  mxf_free_metadataset(metadata_set, 1);
869  return 0;
870  }
871  }
872  }
873  }
874  tmp = av_realloc_array(mxf->metadata_sets, mxf->metadata_sets_count + 1, sizeof(*mxf->metadata_sets));
875  if (!tmp) {
876  mxf_free_metadataset(metadata_set, 1);
877  return AVERROR(ENOMEM);
878  }
879  mxf->metadata_sets = tmp;
880  mxf->metadata_sets[mxf->metadata_sets_count] = *metadata_set;
881  mxf->metadata_sets_count++;
882  return 0;
883 }
884 
885 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
886 {
887  MXFCryptoContext *cryptocontext = arg;
888  if (size != 16)
889  return AVERROR_INVALIDDATA;
891  avio_read(pb, cryptocontext->source_container_ul, 16);
892  return 0;
893 }
894 
895 static int mxf_read_strong_ref_array(AVIOContext *pb, UID **refs, int *count)
896 {
897  *count = avio_rb32(pb);
898  av_free(*refs);
899  *refs = av_calloc(*count, sizeof(UID));
900  if (!*refs) {
901  *count = 0;
902  return AVERROR(ENOMEM);
903  }
904  avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
905  avio_read(pb, (uint8_t *)*refs, *count * sizeof(UID));
906  return 0;
907 }
908 
909 static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, int be)
910 {
911  int ret;
912  size_t buf_size;
913 
914  if (size < 0 || size > INT_MAX/2)
915  return AVERROR(EINVAL);
916 
917  buf_size = size + size / 2 + 1;
918  av_free(*str);
919  *str = av_malloc(buf_size);
920  if (!*str)
921  return AVERROR(ENOMEM);
922 
923  if (be)
924  ret = avio_get_str16be(pb, size, *str, buf_size);
925  else
926  ret = avio_get_str16le(pb, size, *str, buf_size);
927 
928  if (ret < 0) {
929  av_freep(str);
930  return ret;
931  }
932 
933  return ret;
934 }
935 
936 #define READ_STR16(type, big_endian) \
937 static int mxf_read_utf16 ## type ##_string(AVIOContext *pb, int size, char** str) \
938 { \
939 return mxf_read_utf16_string(pb, size, str, big_endian); \
940 }
941 READ_STR16(be, 1)
942 READ_STR16(le, 0)
943 #undef READ_STR16
944 
945 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
946 {
947  MXFContext *mxf = arg;
948  switch (tag) {
949  case 0x1901:
950  if (mxf->packages_refs)
951  av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple packages_refs\n");
952  return mxf_read_strong_ref_array(pb, &mxf->packages_refs, &mxf->packages_count);
953  case 0x1902:
955  }
956  return 0;
957 }
958 
959 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
960 {
961  MXFStructuralComponent *source_clip = arg;
962  switch(tag) {
963  case 0x0202:
964  source_clip->duration = avio_rb64(pb);
965  break;
966  case 0x1201:
967  source_clip->start_position = avio_rb64(pb);
968  break;
969  case 0x1101:
970  /* UMID, only get last 16 bytes */
971  avio_read(pb, source_clip->source_package_ul, 16);
972  avio_read(pb, source_clip->source_package_uid, 16);
973  break;
974  case 0x1102:
975  source_clip->source_track_id = avio_rb32(pb);
976  break;
977  }
978  return 0;
979 }
980 
981 static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
982 {
983  MXFTimecodeComponent *mxf_timecode = arg;
984  switch(tag) {
985  case 0x1501:
986  mxf_timecode->start_frame = avio_rb64(pb);
987  break;
988  case 0x1502:
989  mxf_timecode->rate = (AVRational){avio_rb16(pb), 1};
990  break;
991  case 0x1503:
992  mxf_timecode->drop_frame = avio_r8(pb);
993  break;
994  }
995  return 0;
996 }
997 
998 static int mxf_read_pulldown_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
999 {
1000  MXFPulldownComponent *mxf_pulldown = arg;
1001  switch(tag) {
1002  case 0x0d01:
1003  avio_read(pb, mxf_pulldown->input_segment_ref, 16);
1004  break;
1005  }
1006  return 0;
1007 }
1008 
1009 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1010 {
1011  MXFTrack *track = arg;
1012  switch(tag) {
1013  case 0x4801:
1014  track->track_id = avio_rb32(pb);
1015  break;
1016  case 0x4804:
1017  avio_read(pb, track->track_number, 4);
1018  break;
1019  case 0x4802:
1020  mxf_read_utf16be_string(pb, size, &track->name);
1021  break;
1022  case 0x4b01:
1023  track->edit_rate.num = avio_rb32(pb);
1024  track->edit_rate.den = avio_rb32(pb);
1025  break;
1026  case 0x4803:
1027  avio_read(pb, track->sequence_ref, 16);
1028  break;
1029  }
1030  return 0;
1031 }
1032 
1033 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1034 {
1035  MXFSequence *sequence = arg;
1036  switch(tag) {
1037  case 0x0202:
1038  sequence->duration = avio_rb64(pb);
1039  break;
1040  case 0x0201:
1041  avio_read(pb, sequence->data_definition_ul, 16);
1042  break;
1043  case 0x4b02:
1044  sequence->origin = avio_r8(pb);
1045  break;
1046  case 0x1001:
1048  &sequence->structural_components_count);
1049  }
1050  return 0;
1051 }
1052 
1053 static int mxf_read_essence_group(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1054 {
1055  MXFEssenceGroup *essence_group = arg;
1056  switch (tag) {
1057  case 0x0202:
1058  essence_group->duration = avio_rb64(pb);
1059  break;
1060  case 0x0501:
1061  return mxf_read_strong_ref_array(pb, &essence_group->structural_components_refs,
1062  &essence_group->structural_components_count);
1063  }
1064  return 0;
1065 }
1066 
1067 static int mxf_read_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1068 {
1069  MXFPackage *package = arg;
1070  switch(tag) {
1071  case 0x4403:
1072  return mxf_read_strong_ref_array(pb, &package->tracks_refs,
1073  &package->tracks_count);
1074  case 0x4401:
1075  /* UMID */
1076  avio_read(pb, package->package_ul, 16);
1077  avio_read(pb, package->package_uid, 16);
1078  break;
1079  case 0x4701:
1080  avio_read(pb, package->descriptor_ref, 16);
1081  break;
1082  case 0x4402:
1083  return mxf_read_utf16be_string(pb, size, &package->name);
1084  case 0x4406:
1085  return mxf_read_strong_ref_array(pb, &package->comment_refs,
1086  &package->comment_count);
1087  }
1088  return 0;
1089 }
1090 
1091 static int mxf_read_essence_container_data(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1092 {
1093  MXFEssenceContainerData *essence_data = arg;
1094  switch(tag) {
1095  case 0x2701:
1096  /* linked package umid UMID */
1097  avio_read(pb, essence_data->package_ul, 16);
1098  avio_read(pb, essence_data->package_uid, 16);
1099  break;
1100  case 0x3f06:
1101  essence_data->index_sid = avio_rb32(pb);
1102  break;
1103  case 0x3f07:
1104  essence_data->body_sid = avio_rb32(pb);
1105  break;
1106  }
1107  return 0;
1108 }
1109 
1111 {
1112  int i, length;
1113 
1114  segment->nb_index_entries = avio_rb32(pb);
1115 
1116  length = avio_rb32(pb);
1117  if(segment->nb_index_entries && length < 11)
1118  return AVERROR_INVALIDDATA;
1119 
1120  if (!FF_ALLOC_TYPED_ARRAY(segment->temporal_offset_entries, segment->nb_index_entries) ||
1121  !FF_ALLOC_TYPED_ARRAY(segment->flag_entries , segment->nb_index_entries) ||
1122  !FF_ALLOC_TYPED_ARRAY(segment->stream_offset_entries , segment->nb_index_entries)) {
1123  av_freep(&segment->temporal_offset_entries);
1124  av_freep(&segment->flag_entries);
1125  return AVERROR(ENOMEM);
1126  }
1127 
1128  for (i = 0; i < segment->nb_index_entries; i++) {
1129  if(avio_feof(pb))
1130  return AVERROR_INVALIDDATA;
1131  segment->temporal_offset_entries[i] = avio_r8(pb);
1132  avio_r8(pb); /* KeyFrameOffset */
1133  segment->flag_entries[i] = avio_r8(pb);
1134  segment->stream_offset_entries[i] = avio_rb64(pb);
1135  avio_skip(pb, length - 11);
1136  }
1137  return 0;
1138 }
1139 
1140 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1141 {
1143  switch(tag) {
1144  case 0x3F05:
1145  segment->edit_unit_byte_count = avio_rb32(pb);
1146  av_log(NULL, AV_LOG_TRACE, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
1147  break;
1148  case 0x3F06:
1149  segment->index_sid = avio_rb32(pb);
1150  av_log(NULL, AV_LOG_TRACE, "IndexSID %d\n", segment->index_sid);
1151  break;
1152  case 0x3F07:
1153  segment->body_sid = avio_rb32(pb);
1154  av_log(NULL, AV_LOG_TRACE, "BodySID %d\n", segment->body_sid);
1155  break;
1156  case 0x3F0A:
1157  av_log(NULL, AV_LOG_TRACE, "IndexEntryArray found\n");
1158  return mxf_read_index_entry_array(pb, segment);
1159  case 0x3F0B:
1160  segment->index_edit_rate.num = avio_rb32(pb);
1161  segment->index_edit_rate.den = avio_rb32(pb);
1162  av_log(NULL, AV_LOG_TRACE, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
1163  segment->index_edit_rate.den);
1164  break;
1165  case 0x3F0C:
1166  segment->index_start_position = avio_rb64(pb);
1167  av_log(NULL, AV_LOG_TRACE, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
1168  break;
1169  case 0x3F0D:
1170  segment->index_duration = avio_rb64(pb);
1171  av_log(NULL, AV_LOG_TRACE, "IndexDuration %"PRId64"\n", segment->index_duration);
1172  break;
1173  }
1174  return 0;
1175 }
1176 
1177 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
1178 {
1179  int code, value, ofs = 0;
1180  char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */
1181 
1182  do {
1183  code = avio_r8(pb);
1184  value = avio_r8(pb);
1185  av_log(NULL, AV_LOG_TRACE, "pixel layout: code %#x\n", code);
1186 
1187  if (ofs <= 14) {
1188  layout[ofs++] = code;
1189  layout[ofs++] = value;
1190  } else
1191  break; /* don't read byte by byte on sneaky files filled with lots of non-zeroes */
1192  } while (code != 0); /* SMPTE 377M E.2.46 */
1193 
1194  ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
1195 }
1196 
1197 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1198 {
1199  MXFDescriptor *descriptor = arg;
1200  int entry_count, entry_size;
1201 
1202  switch(tag) {
1203  case 0x3F01:
1204  return mxf_read_strong_ref_array(pb, &descriptor->file_descriptors_refs,
1205  &descriptor->file_descriptors_count);
1206  case 0x3002: /* ContainerDuration */
1207  descriptor->duration = avio_rb64(pb);
1208  break;
1209  case 0x3004:
1210  avio_read(pb, descriptor->essence_container_ul, 16);
1211  break;
1212  case 0x3005:
1213  avio_read(pb, descriptor->codec_ul, 16);
1214  break;
1215  case 0x3006:
1216  descriptor->linked_track_id = avio_rb32(pb);
1217  break;
1218  case 0x3201: /* PictureEssenceCoding */
1219  avio_read(pb, descriptor->essence_codec_ul, 16);
1220  break;
1221  case 0x3203:
1222  descriptor->width = avio_rb32(pb);
1223  break;
1224  case 0x3202:
1225  descriptor->height = avio_rb32(pb);
1226  break;
1227  case 0x320C:
1228  descriptor->frame_layout = avio_r8(pb);
1229  break;
1230  case 0x320D:
1231  entry_count = avio_rb32(pb);
1232  entry_size = avio_rb32(pb);
1233  if (entry_size == 4) {
1234  if (entry_count > 0)
1235  descriptor->video_line_map[0] = avio_rb32(pb);
1236  else
1237  descriptor->video_line_map[0] = 0;
1238  if (entry_count > 1)
1239  descriptor->video_line_map[1] = avio_rb32(pb);
1240  else
1241  descriptor->video_line_map[1] = 0;
1242  } else
1243  av_log(NULL, AV_LOG_WARNING, "VideoLineMap element size %d currently not supported\n", entry_size);
1244  break;
1245  case 0x320E:
1246  descriptor->aspect_ratio.num = avio_rb32(pb);
1247  descriptor->aspect_ratio.den = avio_rb32(pb);
1248  break;
1249  case 0x3210:
1250  avio_read(pb, descriptor->color_trc_ul, 16);
1251  break;
1252  case 0x3212:
1253  descriptor->field_dominance = avio_r8(pb);
1254  break;
1255  case 0x3219:
1256  avio_read(pb, descriptor->color_primaries_ul, 16);
1257  break;
1258  case 0x321A:
1259  avio_read(pb, descriptor->color_space_ul, 16);
1260  break;
1261  case 0x3301:
1262  descriptor->component_depth = avio_rb32(pb);
1263  break;
1264  case 0x3302:
1265  descriptor->horiz_subsampling = avio_rb32(pb);
1266  break;
1267  case 0x3304:
1268  descriptor->black_ref_level = avio_rb32(pb);
1269  break;
1270  case 0x3305:
1271  descriptor->white_ref_level = avio_rb32(pb);
1272  break;
1273  case 0x3306:
1274  descriptor->color_range = avio_rb32(pb);
1275  break;
1276  case 0x3308:
1277  descriptor->vert_subsampling = avio_rb32(pb);
1278  break;
1279  case 0x3D03:
1280  descriptor->sample_rate.num = avio_rb32(pb);
1281  descriptor->sample_rate.den = avio_rb32(pb);
1282  break;
1283  case 0x3D06: /* SoundEssenceCompression */
1284  avio_read(pb, descriptor->essence_codec_ul, 16);
1285  break;
1286  case 0x3D07:
1287  descriptor->channels = avio_rb32(pb);
1288  break;
1289  case 0x3D01:
1290  descriptor->bits_per_sample = avio_rb32(pb);
1291  break;
1292  case 0x3401:
1293  mxf_read_pixel_layout(pb, descriptor);
1294  break;
1295  default:
1296  /* Private uid used by SONY C0023S01.mxf */
1298  if (descriptor->extradata)
1299  av_log(NULL, AV_LOG_WARNING, "Duplicate sony_mpeg4_extradata\n");
1300  av_free(descriptor->extradata);
1301  descriptor->extradata_size = 0;
1302  descriptor->extradata = av_malloc(size);
1303  if (!descriptor->extradata)
1304  return AVERROR(ENOMEM);
1305  descriptor->extradata_size = size;
1306  avio_read(pb, descriptor->extradata, size);
1307  }
1308  if (IS_KLV_KEY(uid, mxf_jp2k_rsiz)) {
1309  uint32_t rsiz = avio_rb16(pb);
1310  if (rsiz == FF_PROFILE_JPEG2000_DCINEMA_2K ||
1312  descriptor->pix_fmt = AV_PIX_FMT_XYZ12;
1313  }
1315  if (!descriptor->mastering) {
1317  if (!descriptor->mastering)
1318  return AVERROR(ENOMEM);
1319  }
1321  for (int i = 0; i < 3; i++) {
1322  /* Order: large x, large y, other (i.e. RGB) */
1325  }
1326  /* Check we have seen mxf_mastering_display_white_point_chromaticity */
1327  if (descriptor->mastering->white_point[0].den != 0)
1328  descriptor->mastering->has_primaries = 1;
1329  }
1333  /* Check we have seen mxf_mastering_display_primaries */
1334  if (descriptor->mastering->display_primaries[0][0].den != 0)
1335  descriptor->mastering->has_primaries = 1;
1336  }
1339  /* Check we have seen mxf_mastering_display_minimum_luminance */
1340  if (descriptor->mastering->min_luminance.den != 0)
1341  descriptor->mastering->has_luminance = 1;
1342  }
1345  /* Check we have seen mxf_mastering_display_maximum_luminance */
1346  if (descriptor->mastering->max_luminance.den != 0)
1347  descriptor->mastering->has_luminance = 1;
1348  }
1349  }
1351  if (!descriptor->coll) {
1352  descriptor->coll = av_content_light_metadata_alloc(&descriptor->coll_size);
1353  if (!descriptor->coll)
1354  return AVERROR(ENOMEM);
1355  }
1357  descriptor->coll->MaxCLL = avio_rb16(pb);
1358  }
1360  descriptor->coll->MaxFALL = avio_rb16(pb);
1361  }
1362  }
1363  break;
1364  }
1365  return 0;
1366 }
1367 
1368 static int mxf_read_indirect_value(void *arg, AVIOContext *pb, int size)
1369 {
1370  MXFTaggedValue *tagged_value = arg;
1371  uint8_t key[17];
1372 
1373  if (size <= 17)
1374  return 0;
1375 
1376  avio_read(pb, key, 17);
1377  /* TODO: handle other types of of indirect values */
1378  if (memcmp(key, mxf_indirect_value_utf16le, 17) == 0) {
1379  return mxf_read_utf16le_string(pb, size - 17, &tagged_value->value);
1380  } else if (memcmp(key, mxf_indirect_value_utf16be, 17) == 0) {
1381  return mxf_read_utf16be_string(pb, size - 17, &tagged_value->value);
1382  }
1383  return 0;
1384 }
1385 
1386 static int mxf_read_tagged_value(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1387 {
1388  MXFTaggedValue *tagged_value = arg;
1389  switch (tag){
1390  case 0x5001:
1391  return mxf_read_utf16be_string(pb, size, &tagged_value->name);
1392  case 0x5003:
1393  return mxf_read_indirect_value(tagged_value, pb, size);
1394  }
1395  return 0;
1396 }
1397 
1398 /*
1399  * Match an uid independently of the version byte and up to len common bytes
1400  * Returns: boolean
1401  */
1402 static int mxf_match_uid(const UID key, const UID uid, int len)
1403 {
1404  int i;
1405  for (i = 0; i < len; i++) {
1406  if (i != 7 && key[i] != uid[i])
1407  return 0;
1408  }
1409  return 1;
1410 }
1411 
1412 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
1413 {
1414  while (uls->uid[0]) {
1415  if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
1416  break;
1417  uls++;
1418  }
1419  return uls;
1420 }
1421 
1422 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
1423 {
1424  int i;
1425 
1426  if (!strong_ref)
1427  return NULL;
1428  for (i = mxf->metadata_sets_count - 1; i >= 0; i--) {
1429  if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
1430  (type == AnyType || mxf->metadata_sets[i]->type == type)) {
1431  return mxf->metadata_sets[i];
1432  }
1433  }
1434  return NULL;
1435 }
1436 
1438  // video essence container uls
1439  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000, NULL, 14, J2KWrap },
1440  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x10,0x60,0x01 }, 14, AV_CODEC_ID_H264, NULL, 15 }, /* H.264 */
1441  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x11,0x01,0x00 }, 14, AV_CODEC_ID_DNXHD, NULL, 14 }, /* VC-3 */
1442  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x12,0x01,0x00 }, 14, AV_CODEC_ID_VC1, NULL, 14 }, /* VC-1 */
1443  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x14,0x01,0x00 }, 14, AV_CODEC_ID_TIFF, NULL, 14 }, /* TIFF */
1444  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x15,0x01,0x00 }, 14, AV_CODEC_ID_DIRAC, NULL, 14 }, /* VC-2 */
1445  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x1b,0x01,0x00 }, 14, AV_CODEC_ID_CFHD, NULL, 14 }, /* VC-5 */
1446  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x1c,0x01,0x00 }, 14, AV_CODEC_ID_PRORES, NULL, 14 }, /* ProRes */
1447  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO, NULL, 15 }, /* MPEG-ES */
1448  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x04,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO, NULL, 15, D10D11Wrap }, /* SMPTE D-10 mapping */
1449  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, AV_CODEC_ID_DVVIDEO, NULL, 15 }, /* DV 625 25mbps */
1450  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14, AV_CODEC_ID_RAWVIDEO, NULL, 15, RawVWrap }, /* uncompressed picture */
1451  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x01,0x01 }, 15, AV_CODEC_ID_HQ_HQA },
1452  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x02,0x01 }, 15, AV_CODEC_ID_HQX },
1453  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x15,0x00,0x04,0x02,0x10,0x00,0x01 }, 16, AV_CODEC_ID_HEVC, NULL, 15 }, /* Canon XF-HEVC */
1454  { { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4f }, 14, AV_CODEC_ID_RAWVIDEO }, /* Legacy ?? Uncompressed Picture */
1455  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1456 };
1457 
1458 /* EC ULs for intra-only formats */
1460  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x00,0x00 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MXF-GC SMPTE D-10 mappings */
1461  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1462 };
1463 
1464 /* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */
1466  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x00,0x00 }, 14, AV_CODEC_ID_H264 }, /* H.264/MPEG-4 AVC Intra Profiles */
1467  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, /* JPEG 2000 code stream */
1468  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1469 };
1470 
1471 /* actual coded width for AVC-Intra to allow selecting correct SPS/PPS */
1473  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 16, 1440 },
1474  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 16, 1440 },
1475  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 16, 1440 },
1476  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 16, 1440 },
1477  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, 0 },
1478 };
1479 
1481  // sound essence container uls
1482  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, AV_CODEC_ID_PCM_S16LE, NULL, 14, RawAWrap }, /* BWF */
1483  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, AV_CODEC_ID_MP2, NULL, 15 }, /* MPEG-ES */
1484  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, AV_CODEC_ID_PCM_S16LE, NULL, 13 }, /* D-10 Mapping 50Mbps PAL Extended Template */
1485  { { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4F }, 14, AV_CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */
1486  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x03,0x04,0x02,0x02,0x02,0x03,0x03,0x01,0x00 }, 14, AV_CODEC_ID_AAC }, /* MPEG-2 AAC ADTS (legacy) */
1487  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1488 };
1489 
1491  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0d,0x00,0x00 }, 16, AV_CODEC_ID_NONE, "vbi_smpte_436M", 11 },
1492  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 }, 16, AV_CODEC_ID_NONE, "vbi_vanc_smpte_436M", 11 },
1493  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x13,0x01,0x01 }, 16, AV_CODEC_ID_TTML },
1494  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1495 };
1496 
1497 static MXFWrappingScheme mxf_get_wrapping_kind(UID *essence_container_ul)
1498 {
1499  int val;
1500  const MXFCodecUL *codec_ul;
1501 
1503  if (!codec_ul->uid[0])
1505  if (!codec_ul->uid[0])
1506  codec_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul);
1507  if (!codec_ul->uid[0] || !codec_ul->wrapping_indicator_pos)
1508  return UnknownWrapped;
1509 
1510  val = (*essence_container_ul)[codec_ul->wrapping_indicator_pos];
1511  switch (codec_ul->wrapping_indicator_type) {
1512  case RawVWrap:
1513  val = val % 4;
1514  break;
1515  case RawAWrap:
1516  if (val == 0x03 || val == 0x04)
1517  val -= 0x02;
1518  break;
1519  case D10D11Wrap:
1520  if (val == 0x02)
1521  val = 0x01;
1522  break;
1523  case J2KWrap:
1524  if (val != 0x02)
1525  val = 0x01;
1526  break;
1527  }
1528  if (val == 0x01)
1529  return FrameWrapped;
1530  if (val == 0x02)
1531  return ClipWrapped;
1532  return UnknownWrapped;
1533 }
1534 
1535 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
1536 {
1537  int i, j, nb_segments = 0;
1538  MXFIndexTableSegment **unsorted_segments;
1539  int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
1540 
1541  /* count number of segments, allocate arrays and copy unsorted segments */
1542  for (i = 0; i < mxf->metadata_sets_count; i++)
1543  if (mxf->metadata_sets[i]->type == IndexTableSegment)
1544  nb_segments++;
1545 
1546  if (!nb_segments)
1547  return AVERROR_INVALIDDATA;
1548 
1549  if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
1550  !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
1551  av_freep(sorted_segments);
1552  av_free(unsorted_segments);
1553  return AVERROR(ENOMEM);
1554  }
1555 
1556  for (i = nb_segments = 0; i < mxf->metadata_sets_count; i++) {
1557  if (mxf->metadata_sets[i]->type == IndexTableSegment) {
1559  if (s->edit_unit_byte_count || s->nb_index_entries)
1560  unsorted_segments[nb_segments++] = s;
1561  else
1562  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
1563  s->index_sid, s->index_start_position);
1564  }
1565  }
1566 
1567  if (!nb_segments) {
1568  av_freep(sorted_segments);
1569  av_free(unsorted_segments);
1570  return AVERROR_INVALIDDATA;
1571  }
1572 
1573  *nb_sorted_segments = 0;
1574 
1575  /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
1576  for (i = 0; i < nb_segments; i++) {
1577  int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
1578  uint64_t best_index_duration = 0;
1579 
1580  for (j = 0; j < nb_segments; j++) {
1581  MXFIndexTableSegment *s = unsorted_segments[j];
1582 
1583  /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
1584  * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
1585  * If we come across an entry with the same IndexStartPosition but larger IndexDuration, then we'll prefer it over the one we currently have.
1586  */
1587  if ((i == 0 ||
1588  s->body_sid > last_body_sid ||
1589  s->body_sid == last_body_sid && s->index_sid > last_index_sid ||
1590  s->body_sid == last_body_sid && s->index_sid == last_index_sid && s->index_start_position > last_index_start) &&
1591  (best == -1 ||
1592  s->body_sid < best_body_sid ||
1593  s->body_sid == best_body_sid && s->index_sid < best_index_sid ||
1594  s->body_sid == best_body_sid && s->index_sid == best_index_sid && s->index_start_position < best_index_start ||
1595  s->body_sid == best_body_sid && s->index_sid == best_index_sid && s->index_start_position == best_index_start && s->index_duration > best_index_duration)) {
1596  best = j;
1597  best_body_sid = s->body_sid;
1598  best_index_sid = s->index_sid;
1599  best_index_start = s->index_start_position;
1600  best_index_duration = s->index_duration;
1601  }
1602  }
1603 
1604  /* no suitable entry found -> we're done */
1605  if (best == -1)
1606  break;
1607 
1608  (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
1609  last_body_sid = best_body_sid;
1610  last_index_sid = best_index_sid;
1611  last_index_start = best_index_start;
1612  }
1613 
1614  av_free(unsorted_segments);
1615 
1616  return 0;
1617 }
1618 
1619 /**
1620  * Computes the absolute file offset of the given essence container offset
1621  */
1622 static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out, MXFPartition **partition_out)
1623 {
1624  MXFPartition *last_p = NULL;
1625  int a, b, m, m0;
1626 
1627  if (offset < 0)
1628  return AVERROR(EINVAL);
1629 
1630  a = -1;
1631  b = mxf->partitions_count;
1632 
1633  while (b - a > 1) {
1634  m0 = m = (a + b) >> 1;
1635 
1636  while (m < b && mxf->partitions[m].body_sid != body_sid)
1637  m++;
1638 
1639  if (m < b && mxf->partitions[m].body_offset <= offset)
1640  a = m;
1641  else
1642  b = m0;
1643  }
1644 
1645  if (a >= 0)
1646  last_p = &mxf->partitions[a];
1647 
1648  if (last_p && (!last_p->essence_length || last_p->essence_length > (offset - last_p->body_offset))) {
1649  *offset_out = last_p->essence_offset + (offset - last_p->body_offset);
1650  if (partition_out)
1651  *partition_out = last_p;
1652  return 0;
1653  }
1654 
1655  av_log(mxf->fc, AV_LOG_ERROR,
1656  "failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n",
1657  offset, body_sid);
1658 
1659  return AVERROR_INVALIDDATA;
1660 }
1661 
1662 /**
1663  * Returns the end position of the essence container with given BodySID, or zero if unknown
1664  */
1665 static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
1666 {
1667  for (int x = mxf->partitions_count - 1; x >= 0; x--) {
1668  MXFPartition *p = &mxf->partitions[x];
1669 
1670  if (p->body_sid != body_sid)
1671  continue;
1672 
1673  if (!p->essence_length)
1674  return 0;
1675 
1676  return p->essence_offset + p->essence_length;
1677  }
1678 
1679  return 0;
1680 }
1681 
1682 /* EditUnit -> absolute offset */
1683 static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, AVRational edit_rate, int64_t *edit_unit_out, int64_t *offset_out, MXFPartition **partition_out, int nag)
1684 {
1685  int i;
1686  int64_t offset_temp = 0;
1687 
1688  edit_unit = av_rescale_q(edit_unit, index_table->segments[0]->index_edit_rate, edit_rate);
1689 
1690  for (i = 0; i < index_table->nb_segments; i++) {
1691  MXFIndexTableSegment *s = index_table->segments[i];
1692 
1693  edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */
1694 
1695  if (edit_unit < s->index_start_position + s->index_duration) {
1696  int64_t index = edit_unit - s->index_start_position;
1697 
1698  if (s->edit_unit_byte_count)
1699  offset_temp += s->edit_unit_byte_count * index;
1700  else {
1701  if (s->nb_index_entries == 2 * s->index_duration + 1)
1702  index *= 2; /* Avid index */
1703 
1704  if (index < 0 || index >= s->nb_index_entries) {
1705  av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
1706  index_table->index_sid, s->index_start_position);
1707  return AVERROR_INVALIDDATA;
1708  }
1709 
1710  offset_temp = s->stream_offset_entries[index];
1711  }
1712 
1713  if (edit_unit_out)
1714  *edit_unit_out = av_rescale_q(edit_unit, edit_rate, s->index_edit_rate);
1715 
1716  return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out, partition_out);
1717  } else {
1718  /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
1719  offset_temp += s->edit_unit_byte_count * s->index_duration;
1720  }
1721  }
1722 
1723  if (nag)
1724  av_log(mxf->fc, AV_LOG_ERROR, "failed to map EditUnit %"PRId64" in IndexSID %i to an offset\n", edit_unit, index_table->index_sid);
1725 
1726  return AVERROR_INVALIDDATA;
1727 }
1728 
1730 {
1731  int i, j, x;
1732  int8_t max_temporal_offset = -128;
1733  uint8_t *flags;
1734 
1735  /* first compute how many entries we have */
1736  for (i = 0; i < index_table->nb_segments; i++) {
1737  MXFIndexTableSegment *s = index_table->segments[i];
1738 
1739  if (!s->nb_index_entries) {
1740  index_table->nb_ptses = 0;
1741  return 0; /* no TemporalOffsets */
1742  }
1743 
1744  if (s->index_duration > INT_MAX - index_table->nb_ptses) {
1745  index_table->nb_ptses = 0;
1746  av_log(mxf->fc, AV_LOG_ERROR, "ignoring IndexSID %d, duration is too large\n", s->index_sid);
1747  return 0;
1748  }
1749 
1750  index_table->nb_ptses += s->index_duration;
1751  }
1752 
1753  /* paranoid check */
1754  if (index_table->nb_ptses <= 0)
1755  return 0;
1756 
1757  if (!(index_table->ptses = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
1758  !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry))) ||
1759  !(index_table->offsets = av_calloc(index_table->nb_ptses, sizeof(int8_t))) ||
1760  !(flags = av_calloc(index_table->nb_ptses, sizeof(uint8_t)))) {
1761  av_freep(&index_table->ptses);
1762  av_freep(&index_table->fake_index);
1763  av_freep(&index_table->offsets);
1764  return AVERROR(ENOMEM);
1765  }
1766 
1767  /* we may have a few bad TemporalOffsets
1768  * make sure the corresponding PTSes don't have the bogus value 0 */
1769  for (x = 0; x < index_table->nb_ptses; x++)
1770  index_table->ptses[x] = AV_NOPTS_VALUE;
1771 
1772  /**
1773  * We have this:
1774  *
1775  * x TemporalOffset
1776  * 0: 0
1777  * 1: 1
1778  * 2: 1
1779  * 3: -2
1780  * 4: 1
1781  * 5: 1
1782  * 6: -2
1783  *
1784  * We want to transform it into this:
1785  *
1786  * x DTS PTS
1787  * 0: -1 0
1788  * 1: 0 3
1789  * 2: 1 1
1790  * 3: 2 2
1791  * 4: 3 6
1792  * 5: 4 4
1793  * 6: 5 5
1794  *
1795  * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
1796  * then settings ffstream(mxf)->first_dts = -max(TemporalOffset[x]).
1797  * The latter makes DTS <= PTS.
1798  */
1799  for (i = x = 0; i < index_table->nb_segments; i++) {
1800  MXFIndexTableSegment *s = index_table->segments[i];
1801  int index_delta = 1;
1802  int n = s->nb_index_entries;
1803 
1804  if (s->nb_index_entries == 2 * s->index_duration + 1) {
1805  index_delta = 2; /* Avid index */
1806  /* ignore the last entry - it's the size of the essence container */
1807  n--;
1808  }
1809 
1810  for (j = 0; j < n; j += index_delta, x++) {
1811  int offset = s->temporal_offset_entries[j] / index_delta;
1812  int index = x + offset;
1813 
1814  if (x >= index_table->nb_ptses) {
1815  av_log(mxf->fc, AV_LOG_ERROR,
1816  "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
1817  s->nb_index_entries, s->index_duration);
1818  break;
1819  }
1820 
1821  flags[x] = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
1822 
1823  if (index < 0 || index >= index_table->nb_ptses) {
1824  av_log(mxf->fc, AV_LOG_ERROR,
1825  "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
1826  x, offset, index);
1827  continue;
1828  }
1829 
1830  index_table->offsets[x] = offset;
1831  index_table->ptses[index] = x;
1832  max_temporal_offset = FFMAX(max_temporal_offset, offset);
1833  }
1834  }
1835 
1836  /* calculate the fake index table in display order */
1837  for (x = 0; x < index_table->nb_ptses; x++) {
1838  index_table->fake_index[x].timestamp = x;
1839  if (index_table->ptses[x] != AV_NOPTS_VALUE)
1840  index_table->fake_index[index_table->ptses[x]].flags = flags[x];
1841  }
1842  av_freep(&flags);
1843 
1844  index_table->first_dts = -max_temporal_offset;
1845 
1846  return 0;
1847 }
1848 
1849 /**
1850  * Sorts and collects index table segments into index tables.
1851  * Also computes PTSes if possible.
1852  */
1854 {
1855  int i, j, k, ret, nb_sorted_segments;
1856  MXFIndexTableSegment **sorted_segments = NULL;
1857 
1858  if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
1859  nb_sorted_segments <= 0) {
1860  av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
1861  return 0;
1862  }
1863 
1864  /* sanity check and count unique BodySIDs/IndexSIDs */
1865  for (i = 0; i < nb_sorted_segments; i++) {
1866  if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
1867  mxf->nb_index_tables++;
1868  else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
1869  av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
1871  goto finish_decoding_index;
1872  }
1873  }
1874 
1876  sizeof(*mxf->index_tables));
1877  if (!mxf->index_tables) {
1878  av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
1879  ret = AVERROR(ENOMEM);
1880  goto finish_decoding_index;
1881  }
1882 
1883  /* distribute sorted segments to index tables */
1884  for (i = j = 0; i < nb_sorted_segments; i++) {
1885  if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
1886  /* next IndexSID */
1887  j++;
1888  }
1889 
1890  mxf->index_tables[j].nb_segments++;
1891  }
1892 
1893  for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
1894  MXFIndexTable *t = &mxf->index_tables[j];
1895  MXFTrack *mxf_track = NULL;
1896 
1897  t->segments = av_calloc(t->nb_segments, sizeof(*t->segments));
1898  if (!t->segments) {
1899  av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment"
1900  " pointer array\n");
1901  ret = AVERROR(ENOMEM);
1902  goto finish_decoding_index;
1903  }
1904 
1905  if (sorted_segments[i]->index_start_position)
1906  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
1907  sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
1908 
1909  memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
1910  t->index_sid = sorted_segments[i]->index_sid;
1911  t->body_sid = sorted_segments[i]->body_sid;
1912 
1913  if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
1914  goto finish_decoding_index;
1915 
1916  for (k = 0; k < mxf->fc->nb_streams; k++) {
1917  MXFTrack *track = mxf->fc->streams[k]->priv_data;
1918  if (track && track->index_sid == t->index_sid) {
1919  mxf_track = track;
1920  break;
1921  }
1922  }
1923 
1924  /* fix zero IndexDurations */
1925  for (k = 0; k < t->nb_segments; k++) {
1926  if (!t->segments[k]->index_edit_rate.num || !t->segments[k]->index_edit_rate.den) {
1927  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has invalid IndexEditRate\n",
1928  t->index_sid, k);
1929  if (mxf_track)
1930  t->segments[k]->index_edit_rate = mxf_track->edit_rate;
1931  }
1932 
1933  if (t->segments[k]->index_duration)
1934  continue;
1935 
1936  if (t->nb_segments > 1)
1937  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
1938  t->index_sid, k);
1939 
1940  if (!mxf_track) {
1941  av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
1942  break;
1943  }
1944 
1945  /* assume the first stream's duration is reasonable
1946  * leave index_duration = 0 on further segments in case we have any (unlikely)
1947  */
1948  t->segments[k]->index_duration = mxf_track->original_duration;
1949  break;
1950  }
1951  }
1952 
1953  ret = 0;
1954 finish_decoding_index:
1955  av_free(sorted_segments);
1956  return ret;
1957 }
1958 
1959 static int mxf_is_intra_only(MXFDescriptor *descriptor)
1960 {
1962  &descriptor->essence_container_ul)->id != AV_CODEC_ID_NONE ||
1964  &descriptor->essence_codec_ul)->id != AV_CODEC_ID_NONE;
1965 }
1966 
1967 static int mxf_uid_to_str(UID uid, char **str)
1968 {
1969  int i;
1970  char *p;
1971  p = *str = av_mallocz(sizeof(UID) * 2 + 4 + 1);
1972  if (!p)
1973  return AVERROR(ENOMEM);
1974  for (i = 0; i < sizeof(UID); i++) {
1975  snprintf(p, 2 + 1, "%.2x", uid[i]);
1976  p += 2;
1977  if (i == 3 || i == 5 || i == 7 || i == 9) {
1978  snprintf(p, 1 + 1, "-");
1979  p++;
1980  }
1981  }
1982  return 0;
1983 }
1984 
1985 static int mxf_umid_to_str(UID ul, UID uid, char **str)
1986 {
1987  int i;
1988  char *p;
1989  p = *str = av_mallocz(sizeof(UID) * 4 + 2 + 1);
1990  if (!p)
1991  return AVERROR(ENOMEM);
1992  snprintf(p, 2 + 1, "0x");
1993  p += 2;
1994  for (i = 0; i < sizeof(UID); i++) {
1995  snprintf(p, 2 + 1, "%.2X", ul[i]);
1996  p += 2;
1997 
1998  }
1999  for (i = 0; i < sizeof(UID); i++) {
2000  snprintf(p, 2 + 1, "%.2X", uid[i]);
2001  p += 2;
2002  }
2003  return 0;
2004 }
2005 
2006 static int mxf_version_to_str(uint16_t major, uint16_t minor, uint16_t tertiary,
2007  uint16_t patch, uint16_t release, char **str)
2008 {
2009  *str = av_asprintf("%d.%d.%d.%d.%d", major, minor, tertiary, patch, release);
2010  if (!*str)
2011  return AVERROR(ENOMEM);
2012  return 0;
2013 }
2014 
2015 static int mxf_add_umid_metadata(AVDictionary **pm, const char *key, MXFPackage* package)
2016 {
2017  char *str;
2018  int ret;
2019  if (!package)
2020  return 0;
2021  if ((ret = mxf_umid_to_str(package->package_ul, package->package_uid, &str)) < 0)
2022  return ret;
2024  return 0;
2025 }
2026 
2027 static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
2028 {
2029  char buf[AV_TIMECODE_STR_SIZE];
2030  av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0);
2031 
2032  return 0;
2033 }
2034 
2036 {
2037  MXFStructuralComponent *component = NULL;
2038  MXFPulldownComponent *pulldown = NULL;
2039 
2040  component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
2041  if (!component)
2042  return NULL;
2043 
2044  switch (component->meta.type) {
2045  case TimecodeComponent:
2046  return (MXFTimecodeComponent*)component;
2047  case PulldownComponent: /* timcode component may be located on a pulldown component */
2048  pulldown = (MXFPulldownComponent*)component;
2050  default:
2051  break;
2052  }
2053  return NULL;
2054 }
2055 
2056 static MXFPackage* mxf_resolve_source_package(MXFContext *mxf, UID package_ul, UID package_uid)
2057 {
2058  MXFPackage *package = NULL;
2059  int i;
2060 
2061  for (i = 0; i < mxf->packages_count; i++) {
2062  package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], SourcePackage);
2063  if (!package)
2064  continue;
2065 
2066  if (!memcmp(package->package_ul, package_ul, 16) && !memcmp(package->package_uid, package_uid, 16))
2067  return package;
2068  }
2069  return NULL;
2070 }
2071 
2072 static MXFDescriptor* mxf_resolve_multidescriptor(MXFContext *mxf, MXFDescriptor *descriptor, int track_id)
2073 {
2074  MXFDescriptor *file_descriptor = NULL;
2075  int i;
2076 
2077  if (!descriptor)
2078  return NULL;
2079 
2080  if (descriptor->meta.type == MultipleDescriptor) {
2081  for (i = 0; i < descriptor->file_descriptors_count; i++) {
2082  file_descriptor = mxf_resolve_strong_ref(mxf, &descriptor->file_descriptors_refs[i], Descriptor);
2083 
2084  if (!file_descriptor) {
2085  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve file descriptor strong ref\n");
2086  continue;
2087  }
2088  if (file_descriptor->linked_track_id == track_id) {
2089  return file_descriptor;
2090  }
2091  }
2092  } else if (descriptor->meta.type == Descriptor)
2093  return descriptor;
2094 
2095  return NULL;
2096 }
2097 
2099 {
2100  MXFStructuralComponent *component = NULL;
2101  MXFPackage *package = NULL;
2102  MXFDescriptor *descriptor = NULL;
2103  int i;
2104 
2105  if (!essence_group || !essence_group->structural_components_count)
2106  return NULL;
2107 
2108  /* essence groups contains multiple representations of the same media,
2109  this return the first components with a valid Descriptor typically index 0 */
2110  for (i =0; i < essence_group->structural_components_count; i++){
2111  component = mxf_resolve_strong_ref(mxf, &essence_group->structural_components_refs[i], SourceClip);
2112  if (!component)
2113  continue;
2114 
2115  if (!(package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid)))
2116  continue;
2117 
2118  descriptor = mxf_resolve_strong_ref(mxf, &package->descriptor_ref, Descriptor);
2119  if (descriptor)
2120  return component;
2121  }
2122  return NULL;
2123 }
2124 
2126 {
2127  MXFStructuralComponent *component = NULL;
2128 
2129  component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
2130  if (!component)
2131  return NULL;
2132  switch (component->meta.type) {
2133  case SourceClip:
2134  return component;
2135  case EssenceGroup:
2136  return mxf_resolve_essence_group_choice(mxf, (MXFEssenceGroup*) component);
2137  default:
2138  break;
2139  }
2140  return NULL;
2141 }
2142 
2144 {
2146  int i;
2147  char *key = NULL;
2148 
2149  for (i = 0; i < package->comment_count; i++) {
2150  tag = mxf_resolve_strong_ref(mxf, &package->comment_refs[i], TaggedValue);
2151  if (!tag || !tag->name || !tag->value)
2152  continue;
2153 
2154  key = av_asprintf("comment_%s", tag->name);
2155  if (!key)
2156  return AVERROR(ENOMEM);
2157 
2159  }
2160  return 0;
2161 }
2162 
2164 {
2165  MXFPackage *physical_package = NULL;
2166  MXFTrack *physical_track = NULL;
2167  MXFStructuralComponent *sourceclip = NULL;
2168  MXFTimecodeComponent *mxf_tc = NULL;
2169  int i, j, k;
2170  AVTimecode tc;
2171  int flags;
2172  int64_t start_position;
2173 
2174  for (i = 0; i < source_track->sequence->structural_components_count; i++) {
2175  sourceclip = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip);
2176  if (!sourceclip)
2177  continue;
2178 
2179  if (!(physical_package = mxf_resolve_source_package(mxf, sourceclip->source_package_ul, sourceclip->source_package_uid)))
2180  break;
2181 
2182  mxf_add_umid_metadata(&st->metadata, "reel_umid", physical_package);
2183 
2184  /* the name of physical source package is name of the reel or tape */
2185  if (physical_package->name && physical_package->name[0])
2186  av_dict_set(&st->metadata, "reel_name", physical_package->name, 0);
2187 
2188  /* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track
2189  * to the start_frame of the timecode component located on one of the tracks of the physical source package.
2190  */
2191  for (j = 0; j < physical_package->tracks_count; j++) {
2192  if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) {
2193  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
2194  continue;
2195  }
2196 
2197  if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) {
2198  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
2199  continue;
2200  }
2201 
2202  if (physical_track->edit_rate.num <= 0 ||
2203  physical_track->edit_rate.den <= 0) {
2204  av_log(mxf->fc, AV_LOG_WARNING,
2205  "Invalid edit rate (%d/%d) found on structural"
2206  " component #%d, defaulting to 25/1\n",
2207  physical_track->edit_rate.num,
2208  physical_track->edit_rate.den, i);
2209  physical_track->edit_rate = (AVRational){25, 1};
2210  }
2211 
2212  for (k = 0; k < physical_track->sequence->structural_components_count; k++) {
2213  if (!(mxf_tc = mxf_resolve_timecode_component(mxf, &physical_track->sequence->structural_components_refs[k])))
2214  continue;
2215 
2216  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
2217  /* scale sourceclip start_position to match physical track edit rate */
2218  start_position = av_rescale_q(sourceclip->start_position,
2219  physical_track->edit_rate,
2220  source_track->edit_rate);
2221 
2222  if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) {
2223  mxf_add_timecode_metadata(&st->metadata, "timecode", &tc);
2224  return 0;
2225  }
2226  }
2227  }
2228  }
2229 
2230  return 0;
2231 }
2232 
2234 {
2235  MXFStructuralComponent *component = NULL;
2236  const MXFCodecUL *codec_ul = NULL;
2237  MXFPackage tmp_package;
2238  AVStream *st;
2239  int j;
2240 
2241  for (j = 0; j < track->sequence->structural_components_count; j++) {
2242  component = mxf_resolve_sourceclip(mxf, &track->sequence->structural_components_refs[j]);
2243  if (!component)
2244  continue;
2245  break;
2246  }
2247  if (!component)
2248  return 0;
2249 
2250  st = avformat_new_stream(mxf->fc, NULL);
2251  if (!st) {
2252  av_log(mxf->fc, AV_LOG_ERROR, "could not allocate metadata stream\n");
2253  return AVERROR(ENOMEM);
2254  }
2255 
2258  st->id = track->track_id;
2259 
2260  memcpy(&tmp_package.package_ul, component->source_package_ul, 16);
2261  memcpy(&tmp_package.package_uid, component->source_package_uid, 16);
2262  mxf_add_umid_metadata(&st->metadata, "file_package_umid", &tmp_package);
2263  if (track->name && track->name[0])
2264  av_dict_set(&st->metadata, "track_name", track->name, 0);
2265 
2267  av_dict_set(&st->metadata, "data_type", av_get_media_type_string(codec_ul->id), 0);
2268  return 0;
2269 }
2270 
2272 {
2273  if (descriptor->black_ref_level || descriptor->white_ref_level || descriptor->color_range) {
2274  /* CDCI range metadata */
2275  if (!descriptor->component_depth)
2276  return AVCOL_RANGE_UNSPECIFIED;
2277  if (descriptor->black_ref_level == 0 &&
2278  descriptor->white_ref_level == ((1<<descriptor->component_depth) - 1) &&
2279  (descriptor->color_range == (1<<descriptor->component_depth) ||
2280  descriptor->color_range == ((1<<descriptor->component_depth) - 1)))
2281  return AVCOL_RANGE_JPEG;
2282  if (descriptor->component_depth >= 8 &&
2283  descriptor->black_ref_level == (1 <<(descriptor->component_depth - 4)) &&
2284  descriptor->white_ref_level == (235<<(descriptor->component_depth - 8)) &&
2285  descriptor->color_range == ((14<<(descriptor->component_depth - 4)) + 1))
2286  return AVCOL_RANGE_MPEG;
2287  avpriv_request_sample(mxf->fc, "Unrecognized CDCI color range (color diff range %d, b %d, w %d, depth %d)",
2288  descriptor->color_range, descriptor->black_ref_level,
2289  descriptor->white_ref_level, descriptor->component_depth);
2290  }
2291 
2292  return AVCOL_RANGE_UNSPECIFIED;
2293 }
2294 
2296 {
2297  MXFPackage *material_package = NULL;
2298  int i, j, k, ret;
2299 
2300  av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count);
2301  /* TODO: handle multiple material packages (OP3x) */
2302  for (i = 0; i < mxf->packages_count; i++) {
2303  material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
2304  if (material_package) break;
2305  }
2306  if (!material_package) {
2307  av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
2308  return AVERROR_INVALIDDATA;
2309  }
2310 
2311  mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package);
2312  if (material_package->name && material_package->name[0])
2313  av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0);
2314  mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package);
2315 
2316  for (i = 0; i < material_package->tracks_count; i++) {
2317  MXFPackage *source_package = NULL;
2318  MXFTrack *material_track = NULL;
2319  MXFTrack *source_track = NULL;
2320  MXFTrack *temp_track = NULL;
2321  MXFDescriptor *descriptor = NULL;
2322  MXFStructuralComponent *component = NULL;
2323  MXFTimecodeComponent *mxf_tc = NULL;
2324  UID *essence_container_ul = NULL;
2325  const MXFCodecUL *codec_ul = NULL;
2326  const MXFCodecUL *container_ul = NULL;
2327  const MXFCodecUL *pix_fmt_ul = NULL;
2328  AVStream *st;
2329  FFStream *sti;
2330  AVTimecode tc;
2331  int flags;
2332 
2333  if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
2334  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
2335  continue;
2336  }
2337 
2338  if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
2339  mxf_tc = (MXFTimecodeComponent*)component;
2340  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
2341  if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
2342  mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
2343  }
2344  }
2345 
2346  if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
2347  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
2348  continue;
2349  }
2350 
2351  for (j = 0; j < material_track->sequence->structural_components_count; j++) {
2352  component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
2353  if (!component)
2354  continue;
2355 
2356  mxf_tc = (MXFTimecodeComponent*)component;
2357  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
2358  if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
2359  mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
2360  break;
2361  }
2362  }
2363 
2364  /* TODO: handle multiple source clips, only finds first valid source clip */
2365  if(material_track->sequence->structural_components_count > 1)
2366  av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n",
2367  material_track->track_id, material_track->sequence->structural_components_count);
2368 
2369  for (j = 0; j < material_track->sequence->structural_components_count; j++) {
2370  component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]);
2371  if (!component)
2372  continue;
2373 
2374  source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid);
2375  if (!source_package) {
2376  av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id);
2377  continue;
2378  }
2379  for (k = 0; k < source_package->tracks_count; k++) {
2380  if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
2381  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
2383  goto fail_and_free;
2384  }
2385  if (temp_track->track_id == component->source_track_id) {
2386  source_track = temp_track;
2387  break;
2388  }
2389  }
2390  if (!source_track) {
2391  av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
2392  break;
2393  }
2394 
2395  for (k = 0; k < mxf->essence_container_data_count; k++) {
2396  MXFEssenceContainerData *essence_data;
2397 
2398  if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) {
2399  av_log(mxf->fc, AV_LOG_TRACE, "could not resolve essence container data strong ref\n");
2400  continue;
2401  }
2402  if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) {
2403  source_track->body_sid = essence_data->body_sid;
2404  source_track->index_sid = essence_data->index_sid;
2405  break;
2406  }
2407  }
2408 
2409  if(source_track && component)
2410  break;
2411  }
2412  if (!source_track || !component || !source_package) {
2413  if((ret = mxf_add_metadata_stream(mxf, material_track)))
2414  goto fail_and_free;
2415  continue;
2416  }
2417 
2418  if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
2419  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
2421  goto fail_and_free;
2422  }
2423 
2424  /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
2425  * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
2426  if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
2427  av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
2428  continue;
2429  }
2430 
2431  st = avformat_new_stream(mxf->fc, NULL);
2432  if (!st) {
2433  av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
2434  ret = AVERROR(ENOMEM);
2435  goto fail_and_free;
2436  }
2437  sti = ffstream(st);
2438  st->id = material_track->track_id;
2439  st->priv_data = source_track;
2440 
2441  source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
2442  descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id);
2443 
2444  /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many
2445  * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */
2446  if (descriptor && descriptor->duration != AV_NOPTS_VALUE)
2447  source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration);
2448  else
2449  source_track->original_duration = st->duration = component->duration;
2450 
2451  if (st->duration == -1)
2452  st->duration = AV_NOPTS_VALUE;
2453  st->start_time = component->start_position;
2454  if (material_track->edit_rate.num <= 0 ||
2455  material_track->edit_rate.den <= 0) {
2456  av_log(mxf->fc, AV_LOG_WARNING,
2457  "Invalid edit rate (%d/%d) found on stream #%d, "
2458  "defaulting to 25/1\n",
2459  material_track->edit_rate.num,
2460  material_track->edit_rate.den, st->index);
2461  material_track->edit_rate = (AVRational){25, 1};
2462  }
2463  avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
2464 
2465  /* ensure SourceTrack EditRate == MaterialTrack EditRate since only
2466  * the former is accessible via st->priv_data */
2467  source_track->edit_rate = material_track->edit_rate;
2468 
2469  PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
2471  st->codecpar->codec_type = codec_ul->id;
2472 
2473  if (!descriptor) {
2474  av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
2475  continue;
2476  }
2477  PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
2478  PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
2479  essence_container_ul = &descriptor->essence_container_ul;
2480  source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul);
2481  if (source_track->wrapping == UnknownWrapped)
2482  av_log(mxf->fc, AV_LOG_INFO, "wrapping of stream %d is unknown\n", st->index);
2483  /* HACK: replacing the original key with mxf_encrypted_essence_container
2484  * is not allowed according to s429-6, try to find correct information anyway */
2485  if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
2486  av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
2487  for (k = 0; k < mxf->metadata_sets_count; k++) {
2488  MXFMetadataSet *metadata = mxf->metadata_sets[k];
2489  if (metadata->type == CryptoContext) {
2490  essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
2491  break;
2492  }
2493  }
2494  }
2495 
2496  /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
2498  st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
2499  if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
2501  st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
2502  }
2503 
2504  av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ",
2506  for (k = 0; k < 16; k++) {
2507  av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x",
2508  descriptor->essence_codec_ul[k]);
2509  if (!(k+1 & 19) || k == 5)
2510  av_log(mxf->fc, AV_LOG_VERBOSE, ".");
2511  }
2512  av_log(mxf->fc, AV_LOG_VERBOSE, "\n");
2513 
2514  mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package);
2515  if (source_package->name && source_package->name[0])
2516  av_dict_set(&st->metadata, "file_package_name", source_package->name, 0);
2517  if (material_track->name && material_track->name[0])
2518  av_dict_set(&st->metadata, "track_name", material_track->name, 0);
2519 
2520  mxf_parse_physical_source_package(mxf, source_track, st);
2521 
2522  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2523  source_track->intra_only = mxf_is_intra_only(descriptor);
2525  if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
2526  st->codecpar->codec_id = container_ul->id;
2527  st->codecpar->width = descriptor->width;
2528  st->codecpar->height = descriptor->height; /* Field height, not frame height */
2529  switch (descriptor->frame_layout) {
2530  case FullFrame:
2532  break;
2533  case OneField:
2534  /* Every other line is stored and needs to be duplicated. */
2535  av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n");
2536  break; /* The correct thing to do here is fall through, but by breaking we might be
2537  able to decode some streams at half the vertical resolution, rather than not al all.
2538  It's also for compatibility with the old behavior. */
2539  case MixedFields:
2540  break;
2541  case SegmentedFrame:
2543  case SeparateFields:
2544  av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n",
2545  descriptor->video_line_map[0], descriptor->video_line_map[1],
2546  descriptor->field_dominance);
2547  if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) {
2548  /* Detect coded field order from VideoLineMap:
2549  * (even, even) => bottom field coded first
2550  * (even, odd) => top field coded first
2551  * (odd, even) => top field coded first
2552  * (odd, odd) => bottom field coded first
2553  */
2554  if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) {
2555  switch (descriptor->field_dominance) {
2559  break;
2562  break;
2563  default:
2565  "Field dominance %d support",
2566  descriptor->field_dominance);
2567  }
2568  } else {
2569  switch (descriptor->field_dominance) {
2573  break;
2576  break;
2577  default:
2579  "Field dominance %d support",
2580  descriptor->field_dominance);
2581  }
2582  }
2583  }
2584  /* Turn field height into frame height. */
2585  st->codecpar->height *= 2;
2586  break;
2587  default:
2588  av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout);
2589  }
2590 
2591  if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
2592  switch (descriptor->essence_codec_ul[14]) {
2593  case 1: st->codecpar->codec_tag = MKTAG('a','p','c','o'); break;
2594  case 2: st->codecpar->codec_tag = MKTAG('a','p','c','s'); break;
2595  case 3: st->codecpar->codec_tag = MKTAG('a','p','c','n'); break;
2596  case 4: st->codecpar->codec_tag = MKTAG('a','p','c','h'); break;
2597  case 5: st->codecpar->codec_tag = MKTAG('a','p','4','h'); break;
2598  case 6: st->codecpar->codec_tag = MKTAG('a','p','4','x'); break;
2599  }
2600  }
2601 
2602  if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
2603  st->codecpar->format = descriptor->pix_fmt;
2604  if (st->codecpar->format == AV_PIX_FMT_NONE) {
2606  &descriptor->essence_codec_ul);
2607  st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id;
2608  if (st->codecpar->format== AV_PIX_FMT_NONE) {
2610  &descriptor->essence_codec_ul)->id;
2611  if (!st->codecpar->codec_tag) {
2612  /* support files created before RP224v10 by defaulting to UYVY422
2613  if subsampling is 4:2:2 and component depth is 8-bit */
2614  if (descriptor->horiz_subsampling == 2 &&
2615  descriptor->vert_subsampling == 1 &&
2616  descriptor->component_depth == 8) {
2618  }
2619  }
2620  }
2621  }
2622  }
2624  if (material_track->sequence->origin) {
2625  av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0);
2626  }
2627  if (source_track->sequence->origin) {
2628  av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0);
2629  }
2630  if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den)
2631  sti->display_aspect_ratio = descriptor->aspect_ratio;
2632  st->codecpar->color_range = mxf_get_color_range(mxf, descriptor);
2636  if (descriptor->mastering) {
2638  (uint8_t *)descriptor->mastering,
2639  sizeof(*descriptor->mastering));
2640  if (ret < 0)
2641  goto fail_and_free;
2642  descriptor->mastering = NULL;
2643  }
2644  if (descriptor->coll) {
2646  (uint8_t *)descriptor->coll,
2647  descriptor->coll_size);
2648  if (ret < 0)
2649  goto fail_and_free;
2650  descriptor->coll = NULL;
2651  }
2652  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2654  /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */
2656  st->codecpar->codec_id = (enum AVCodecID)container_ul->id;
2657  st->codecpar->channels = descriptor->channels;
2658 
2659  if (descriptor->sample_rate.den > 0) {
2660  st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
2661  avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
2662  } else {
2663  av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) "
2664  "found for stream #%d, time base forced to 1/48000\n",
2665  descriptor->sample_rate.num, descriptor->sample_rate.den,
2666  st->index);
2667  avpriv_set_pts_info(st, 64, 1, 48000);
2668  }
2669 
2670  /* if duration is set, rescale it from EditRate to SampleRate */
2671  if (st->duration != AV_NOPTS_VALUE)
2672  st->duration = av_rescale_q(st->duration,
2673  av_inv_q(material_track->edit_rate),
2674  st->time_base);
2675 
2676  /* TODO: implement AV_CODEC_ID_RAWAUDIO */
2677  if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) {
2678  if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
2680  else if (descriptor->bits_per_sample == 32)
2682  } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) {
2683  if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
2685  else if (descriptor->bits_per_sample == 32)
2687  } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
2689  }
2691  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
2692  enum AVMediaType type;
2694  if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
2695  st->codecpar->codec_id = container_ul->id;
2697  if (type == AVMEDIA_TYPE_SUBTITLE)
2698  st->codecpar->codec_type = type;
2699  if (container_ul->desc)
2700  av_dict_set(&st->metadata, "data_type", container_ul->desc, 0);
2701  if (mxf->eia608_extract &&
2702  !strcmp(container_ul->desc, "vbi_vanc_smpte_436M")) {
2705  }
2706  }
2707  if (descriptor->extradata) {
2708  if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) {
2709  memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size);
2710  }
2711  } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
2713  &descriptor->essence_codec_ul)->id;
2714  if (coded_width)
2715  st->codecpar->width = coded_width;
2717  if (ret < 0)
2718  return ret;
2719  }
2720  if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) {
2721  /* TODO: decode timestamps */
2723  }
2724  }
2725 
2726  for (int i = 0; i < mxf->fc->nb_streams; i++) {
2727  MXFTrack *track1 = mxf->fc->streams[i]->priv_data;
2728  if (track1 && track1->body_sid) {
2729  for (int j = i + 1; j < mxf->fc->nb_streams; j++) {
2730  MXFTrack *track2 = mxf->fc->streams[j]->priv_data;
2731  if (track2 && track1->body_sid == track2->body_sid && track1->wrapping != track2->wrapping) {
2732  if (track1->wrapping == UnknownWrapped)
2733  track1->wrapping = track2->wrapping;
2734  else if (track2->wrapping == UnknownWrapped)
2735  track2->wrapping = track1->wrapping;
2736  else
2737  av_log(mxf->fc, AV_LOG_ERROR, "stream %d and stream %d have the same BodySID (%d) "
2738  "with different wrapping\n", i, j, track1->body_sid);
2739  }
2740  }
2741  }
2742  }
2743 
2744  ret = 0;
2745 fail_and_free:
2746  return ret;
2747 }
2748 
2749 static int64_t mxf_timestamp_to_int64(uint64_t timestamp)
2750 {
2751  struct tm time = { 0 };
2752  int msecs;
2753  time.tm_year = (timestamp >> 48) - 1900;
2754  time.tm_mon = (timestamp >> 40 & 0xFF) - 1;
2755  time.tm_mday = (timestamp >> 32 & 0xFF);
2756  time.tm_hour = (timestamp >> 24 & 0xFF);
2757  time.tm_min = (timestamp >> 16 & 0xFF);
2758  time.tm_sec = (timestamp >> 8 & 0xFF);
2759  msecs = (timestamp & 0xFF) * 4;
2760 
2761  /* Clip values for legacy reasons. Maybe we should return error instead? */
2762  time.tm_mon = av_clip(time.tm_mon, 0, 11);
2763  time.tm_mday = av_clip(time.tm_mday, 1, 31);
2764  time.tm_hour = av_clip(time.tm_hour, 0, 23);
2765  time.tm_min = av_clip(time.tm_min, 0, 59);
2766  time.tm_sec = av_clip(time.tm_sec, 0, 59);
2767  msecs = av_clip(msecs, 0, 999);
2768 
2769  return (int64_t)av_timegm(&time) * 1000000 + msecs * 1000;
2770 }
2771 
2772 #define SET_STR_METADATA(pb, name, str) do { \
2773  if ((ret = mxf_read_utf16be_string(pb, size, &str)) < 0) \
2774  return ret; \
2775  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
2776 } while (0)
2777 
2778 #define SET_VERSION_METADATA(pb, name, major, minor, tertiary, patch, release, str) do { \
2779  major = avio_rb16(pb); \
2780  minor = avio_rb16(pb); \
2781  tertiary = avio_rb16(pb); \
2782  patch = avio_rb16(pb); \
2783  release = avio_rb16(pb); \
2784  if ((ret = mxf_version_to_str(major, minor, tertiary, patch, release, &str)) < 0) \
2785  return ret; \
2786  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
2787 } while (0)
2788 
2789 #define SET_UID_METADATA(pb, name, var, str) do { \
2790  avio_read(pb, var, 16); \
2791  if ((ret = mxf_uid_to_str(var, &str)) < 0) \
2792  return ret; \
2793  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
2794 } while (0)
2795 
2796 #define SET_TS_METADATA(pb, name, var, str) do { \
2797  var = avio_rb64(pb); \
2798  if (var && (ret = avpriv_dict_set_timestamp(&s->metadata, name, mxf_timestamp_to_int64(var))) < 0) \
2799  return ret; \
2800 } while (0)
2801 
2802 static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset)
2803 {
2804  MXFContext *mxf = arg;
2805  AVFormatContext *s = mxf->fc;
2806  int ret;
2807  UID uid = { 0 };
2808  char *str = NULL;
2809  uint64_t ts;
2810  uint16_t major, minor, tertiary, patch, release;
2811  switch (tag) {
2812  case 0x3C01:
2813  SET_STR_METADATA(pb, "company_name", str);
2814  break;
2815  case 0x3C02:
2816  SET_STR_METADATA(pb, "product_name", str);
2817  break;
2818  case 0x3C03:
2819  SET_VERSION_METADATA(pb, "product_version_num", major, minor, tertiary, patch, release, str);
2820  break;
2821  case 0x3C04:
2822  SET_STR_METADATA(pb, "product_version", str);
2823  break;
2824  case 0x3C05:
2825  SET_UID_METADATA(pb, "product_uid", uid, str);
2826  break;
2827  case 0x3C06:
2828  SET_TS_METADATA(pb, "modification_date", ts, str);
2829  break;
2830  case 0x3C07:
2831  SET_VERSION_METADATA(pb, "toolkit_version_num", major, minor, tertiary, patch, release, str);
2832  break;
2833  case 0x3C08:
2834  SET_STR_METADATA(pb, "application_platform", str);
2835  break;
2836  case 0x3C09:
2837  SET_UID_METADATA(pb, "generation_uid", uid, str);
2838  break;
2839  case 0x3C0A:
2840  SET_UID_METADATA(pb, "uid", uid, str);
2841  break;
2842  }
2843  return 0;
2844 }
2845 
2846 static int mxf_read_preface_metadata(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
2847 {
2848  MXFContext *mxf = arg;
2849  AVFormatContext *s = mxf->fc;
2850  int ret;
2851  char *str = NULL;
2852 
2853  if (tag >= 0x8000 && (IS_KLV_KEY(uid, mxf_avid_project_name))) {
2854  SET_STR_METADATA(pb, "project_name", str);
2855  }
2856  return 0;
2857 }
2858 
2860  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
2861  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
2862  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
2863  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
2864  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
2865  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
2866  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
2867  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
2868  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
2869  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
2870  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
2871  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2f,0x00 }, mxf_read_preface_metadata },
2872  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x30,0x00 }, mxf_read_identification_metadata },
2873  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
2874  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_package, sizeof(MXFPackage), SourcePackage },
2875  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_package, sizeof(MXFPackage), MaterialPackage },
2876  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0f,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
2877  { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x05,0x00 }, mxf_read_essence_group, sizeof(MXFEssenceGroup), EssenceGroup},
2878  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
2879  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3f,0x00 }, mxf_read_tagged_value, sizeof(MXFTaggedValue), TaggedValue },
2880  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
2881  { { 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 */
2882  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
2883  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
2884  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
2885  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
2886  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2VideoDescriptor */
2887  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5b,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* VBI - SMPTE 436M */
2888  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5c,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* VANC/VBI - SMPTE 436M */
2889  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5e,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2AudioDescriptor */
2890  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x64,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* DC Timed Text Descriptor */
2891  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
2892  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
2893  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent },
2894  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0c,0x00 }, mxf_read_pulldown_component, sizeof(MXFPulldownComponent), PulldownComponent },
2895  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
2896  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
2897  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x23,0x00 }, mxf_read_essence_container_data, sizeof(MXFEssenceContainerData), EssenceContainerData },
2898  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
2899 };
2900 
2902 {
2903  ctx->type = type;
2904  ctx->partition_score = partition_score(partition);
2905  switch (type){
2906  case MultipleDescriptor:
2907  case Descriptor:
2908  ((MXFDescriptor*)ctx)->pix_fmt = AV_PIX_FMT_NONE;
2909  ((MXFDescriptor*)ctx)->duration = AV_NOPTS_VALUE;
2910  break;
2911  default:
2912  break;
2913  }
2914  return 0;
2915 }
2916 
2917 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
2918 {
2919  AVIOContext *pb = mxf->fc->pb;
2920  uint64_t klv_end = avio_tell(pb) + klv->length;
2921  MXFMetadataSet *meta;
2922  void *ctx;
2923 
2924  if (ctx_size) {
2925  meta = av_mallocz(ctx_size);
2926  if (!meta)
2927  return AVERROR(ENOMEM);
2928  ctx = meta;
2930  } else {
2931  meta = NULL;
2932  ctx = mxf;
2933  }
2934  while (avio_tell(pb) + 4ULL < klv_end && !avio_feof(pb)) {
2935  int ret;
2936  int tag = avio_rb16(pb);
2937  int size = avio_rb16(pb); /* KLV specified by 0x53 */
2938  int64_t next = avio_tell(pb);
2939  UID uid = {0};
2940  if (next < 0 || next > INT64_MAX - size) {
2941  if (meta) {
2942  mxf_free_metadataset(&meta, 1);
2943  }
2944  return next < 0 ? next : AVERROR_INVALIDDATA;
2945  }
2946  next += size;
2947 
2948  av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x size %d\n", tag, size);
2949  if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
2950  av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
2951  continue;
2952  }
2953  if (tag > 0x7FFF) { /* dynamic tag */
2954  int i;
2955  for (i = 0; i < mxf->local_tags_count; i++) {
2956  int local_tag = AV_RB16(mxf->local_tags+i*18);
2957  if (local_tag == tag) {
2958  memcpy(uid, mxf->local_tags+i*18+2, 16);
2959  av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x\n", local_tag);
2960  PRINT_KEY(mxf->fc, "uid", uid);
2961  }
2962  }
2963  }
2964  if (meta && tag == 0x3C0A) {
2965  avio_read(pb, meta->uid, 16);
2966  } else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0) {
2967  if (meta) {
2968  mxf_free_metadataset(&meta, 1);
2969  }
2970  return ret;
2971  }
2972 
2973  /* Accept the 64k local set limit being exceeded (Avid). Don't accept
2974  * it extending past the end of the KLV though (zzuf5.mxf). */
2975  if (avio_tell(pb) > klv_end) {
2976  if (meta) {
2977  mxf_free_metadataset(&meta, 1);
2978  }
2979 
2980  av_log(mxf->fc, AV_LOG_ERROR,
2981  "local tag %#04x extends past end of local set @ %#"PRIx64"\n",
2982  tag, klv->offset);
2983  return AVERROR_INVALIDDATA;
2984  } else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */
2985  avio_seek(pb, next, SEEK_SET);
2986  }
2987  return meta ? mxf_add_metadata_set(mxf, &meta) : 0;
2988 }
2989 
2990 /**
2991  * Matches any partition pack key, in other words:
2992  * - HeaderPartition
2993  * - BodyPartition
2994  * - FooterPartition
2995  * @return non-zero if the key is a partition pack key, zero otherwise
2996  */
2998 {
2999  //NOTE: this is a little lax since it doesn't constraint key[14]
3000  return !memcmp(key, mxf_header_partition_pack_key, 13) &&
3001  key[13] >= 2 && key[13] <= 4;
3002 }
3003 
3004 /**
3005  * Parses a metadata KLV
3006  * @return <0 on error, 0 otherwise
3007  */
3009  int ctx_size, enum MXFMetadataSetType type)
3010 {
3011  AVFormatContext *s = mxf->fc;
3012  int res;
3013  if (klv.key[5] == 0x53) {
3014  res = mxf_read_local_tags(mxf, &klv, read, ctx_size, type);
3015  } else {
3016  uint64_t next = avio_tell(s->pb) + klv.length;
3017  res = read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
3018 
3019  /* only seek forward, else this can loop for a long time */
3020  if (avio_tell(s->pb) > next) {
3021  av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
3022  klv.offset);
3023  return AVERROR_INVALIDDATA;
3024  }
3025 
3026  avio_seek(s->pb, next, SEEK_SET);
3027  }
3028  if (res < 0) {
3029  av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
3030  return res;
3031  }
3032  return 0;
3033 }
3034 
3035 /**
3036  * Seeks to the previous partition and parses it, if possible
3037  * @return <= 0 if we should stop parsing, > 0 if we should keep going
3038  */
3040 {
3041  AVIOContext *pb = mxf->fc->pb;
3042  KLVPacket klv;
3043  int64_t current_partition_ofs;
3044  int ret;
3045 
3046  if (!mxf->current_partition ||
3048  return 0; /* we've parsed all partitions */
3049 
3050  /* seek to previous partition */
3051  current_partition_ofs = mxf->current_partition->pack_ofs; //includes run-in
3052  avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
3053  mxf->current_partition = NULL;
3054 
3055  av_log(mxf->fc, AV_LOG_TRACE, "seeking to previous partition\n");
3056 
3057  /* Make sure this is actually a PartitionPack, and if so parse it.
3058  * See deadlock2.mxf
3059  */
3060  if ((ret = klv_read_packet(&klv, pb)) < 0) {
3061  av_log(mxf->fc, AV_LOG_ERROR, "failed to read PartitionPack KLV\n");
3062  return ret;
3063  }
3064 
3065  if (!mxf_is_partition_pack_key(klv.key)) {
3066  av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition @ %" PRIx64 " isn't a PartitionPack\n", klv.offset);
3067  return AVERROR_INVALIDDATA;
3068  }
3069 
3070  /* We can't just check ofs >= current_partition_ofs because PreviousPartition
3071  * can point to just before the current partition, causing klv_read_packet()
3072  * to sync back up to it. See deadlock3.mxf
3073  */
3074  if (klv.offset >= current_partition_ofs) {
3075  av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition for PartitionPack @ %"
3076  PRIx64 " indirectly points to itself\n", current_partition_ofs);
3077  return AVERROR_INVALIDDATA;
3078  }
3079 
3080  if ((ret = mxf_parse_klv(mxf, klv, mxf_read_partition_pack, 0, 0)) < 0)
3081  return ret;
3082 
3083  return 1;
3084 }
3085 
3086 /**
3087  * Called when essence is encountered
3088  * @return <= 0 if we should stop parsing, > 0 if we should keep going
3089  */
3091 {
3092  AVIOContext *pb = mxf->fc->pb;
3093  int64_t ret;
3094 
3095  if (mxf->parsing_backward) {
3096  return mxf_seek_to_previous_partition(mxf);
3097  } else {
3098  if (!mxf->footer_partition) {
3099  av_log(mxf->fc, AV_LOG_TRACE, "no FooterPartition\n");
3100  return 0;
3101  }
3102 
3103  av_log(mxf->fc, AV_LOG_TRACE, "seeking to FooterPartition\n");
3104 
3105  /* remember where we were so we don't end up seeking further back than this */
3106  mxf->last_forward_tell = avio_tell(pb);
3107 
3108  if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) {
3109  av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing FooterPartition\n");
3110  return -1;
3111  }
3112 
3113  /* seek to FooterPartition and parse backward */
3114  if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
3115  av_log(mxf->fc, AV_LOG_ERROR,
3116  "failed to seek to FooterPartition @ 0x%" PRIx64
3117  " (%"PRId64") - partial file?\n",
3118  mxf->run_in + mxf->footer_partition, ret);
3119  return ret;
3120  }
3121 
3122  mxf->current_partition = NULL;
3123  mxf->parsing_backward = 1;
3124  }
3125 
3126  return 1;
3127 }
3128 
3129 /**
3130  * Called when the next partition or EOF is encountered
3131  * @return <= 0 if we should stop parsing, > 0 if we should keep going
3132  */
3134 {
3135  return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
3136 }
3137 
3139 {
3140  for (int i = 0; i < s->nb_streams; i++) {
3141  MXFTrack *track = s->streams[i]->priv_data;
3142  if (track && track->body_sid == body_sid && track->wrapping != UnknownWrapped)
3143  return track->wrapping;
3144  }
3145  return UnknownWrapped;
3146 }
3147 
3148 /**
3149  * Figures out the proper offset and length of the essence container in each partition
3150  */
3152 {
3153  MXFContext *mxf = s->priv_data;
3154  int x;
3155 
3156  for (x = 0; x < mxf->partitions_count; x++) {
3157  MXFPartition *p = &mxf->partitions[x];
3158  MXFWrappingScheme wrapping;
3159 
3160  if (!p->body_sid)
3161  continue; /* BodySID == 0 -> no essence */
3162 
3163  /* for clip wrapped essences we point essence_offset after the KL (usually klv.offset + 20 or 25)
3164  * otherwise we point essence_offset at the key of the first essence KLV.
3165  */
3166 
3167  wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_by_body_sid(s, p->body_sid);
3168 
3169  if (wrapping == ClipWrapped) {
3172  } else {
3174 
3175  /* essence container spans to the next partition */
3176  if (x < mxf->partitions_count - 1)
3178 
3179  if (p->essence_length < 0) {
3180  /* next ThisPartition < essence_offset */
3181  p->essence_length = 0;
3182  av_log(mxf->fc, AV_LOG_ERROR,
3183  "partition %i: bad ThisPartition = %"PRIX64"\n",
3184  x+1, mxf->partitions[x+1].this_partition);
3185  }
3186  }
3187  }
3188 }
3189 
3190 static int is_pcm(enum AVCodecID codec_id)
3191 {
3192  /* we only care about "normal" PCM codecs until we get samples */
3194 }
3195 
3196 static MXFIndexTable *mxf_find_index_table(MXFContext *mxf, int index_sid)
3197 {
3198  int i;
3199  for (i = 0; i < mxf->nb_index_tables; i++)
3200  if (mxf->index_tables[i].index_sid == index_sid)
3201  return &mxf->index_tables[i];
3202  return NULL;
3203 }
3204 
3205 /**
3206  * Deal with the case where for some audio atoms EditUnitByteCount is
3207  * very small (2, 4..). In those cases we should read more than one
3208  * sample per call to mxf_read_packet().
3209  */
3211 {
3212  MXFTrack *track = st->priv_data;
3213  MXFIndexTable *t;
3214 
3215  if (!track)
3216  return;
3217  track->edit_units_per_packet = 1;
3218  if (track->wrapping != ClipWrapped)
3219  return;
3220 
3221  t = mxf_find_index_table(mxf, track->index_sid);
3222 
3223  /* expect PCM with exactly one index table segment and a small (< 32) EUBC */
3224  if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
3225  !is_pcm(st->codecpar->codec_id) ||
3226  !t ||
3227  t->nb_segments != 1 ||
3228  t->segments[0]->edit_unit_byte_count >= 32)
3229  return;
3230 
3231  /* arbitrarily default to 48 kHz PAL audio frame size */
3232  /* TODO: We could compute this from the ratio between the audio
3233  * and video edit rates for 48 kHz NTSC we could use the
3234  * 1802-1802-1802-1802-1801 pattern. */
3235  track->edit_units_per_packet = FFMAX(1, track->edit_rate.num / track->edit_rate.den / 25);
3236 }
3237 
3238 /**
3239  * Deal with the case where ClipWrapped essences does not have any IndexTableSegments.
3240  */
3242 {
3243  MXFTrack *track = st->priv_data;
3245  MXFPartition *p = NULL;
3246  int essence_partition_count = 0;
3247  int edit_unit_byte_count = 0;
3248  int i, ret;
3249 
3250  if (!track || track->wrapping != ClipWrapped)
3251  return 0;
3252 
3253  /* check if track already has an IndexTableSegment */
3254  for (i = 0; i < mxf->metadata_sets_count; i++) {
3255  if (mxf->metadata_sets[i]->type == IndexTableSegment) {
3257  if (s->body_sid == track->body_sid)
3258  return 0;
3259  }
3260  }
3261 
3262  /* find the essence partition */
3263  for (i = 0; i < mxf->partitions_count; i++) {
3264  /* BodySID == 0 -> no essence */
3265  if (mxf->partitions[i].body_sid != track->body_sid)
3266  continue;
3267 
3268  p = &mxf->partitions[i];
3269  essence_partition_count++;
3270  }
3271 
3272  /* only handle files with a single essence partition */
3273  if (essence_partition_count != 1)
3274  return 0;
3275 
3277  edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->channels) >> 3;
3278  } else if (st->duration > 0 && p->first_essence_klv.length > 0 && p->first_essence_klv.length % st->duration == 0) {
3279  edit_unit_byte_count = p->first_essence_klv.length / st->duration;
3280  }
3281 
3282  if (edit_unit_byte_count <= 0)
3283  return 0;
3284 
3285  av_log(mxf->fc, AV_LOG_WARNING, "guessing index for stream %d using edit unit byte count %d\n", st->index, edit_unit_byte_count);
3286 
3287  if (!(segment = av_mallocz(sizeof(*segment))))
3288  return AVERROR(ENOMEM);
3289 
3290  if ((ret = mxf_add_metadata_set(mxf, (MXFMetadataSet**)&segment)))
3291  return ret;
3292 
3293  /* Make sure we have nonzero unique index_sid, body_sid will be ok, because
3294  * using the same SID for index is forbidden in MXF. */
3295  if (!track->index_sid)
3296  track->index_sid = track->body_sid;
3297 
3298  segment->meta.type = IndexTableSegment;
3299  /* stream will be treated as small EditUnitByteCount */
3300  segment->edit_unit_byte_count = edit_unit_byte_count;
3301  segment->index_start_position = 0;
3302  segment->index_duration = st->duration;
3303  segment->index_edit_rate = av_inv_q(st->time_base);
3304  segment->index_sid = track->index_sid;
3305  segment->body_sid = p->body_sid;
3306  return 0;
3307 }
3308 
3310 {
3311  MXFContext *mxf = s->priv_data;
3312  uint32_t length;
3313  int64_t file_size, max_rip_length, min_rip_length;
3314  KLVPacket klv;
3315 
3316  if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL))
3317  return;
3318 
3319  file_size = avio_size(s->pb);
3320 
3321  /* S377m says to check the RIP length for "silly" values, without defining "silly".
3322  * The limit below assumes a file with nothing but partition packs and a RIP.
3323  * Before changing this, consider that a muxer may place each sample in its own partition.
3324  *
3325  * 105 is the size of the smallest possible PartitionPack
3326  * 12 is the size of each RIP entry
3327  * 28 is the size of the RIP header and footer, assuming an 8-byte BER
3328  */
3329  max_rip_length = ((file_size - mxf->run_in) / 105) * 12 + 28;
3330  max_rip_length = FFMIN(max_rip_length, INT_MAX); //2 GiB and up is also silly
3331 
3332  /* We're only interested in RIPs with at least two entries.. */
3333  min_rip_length = 16+1+24+4;
3334 
3335  /* See S377m section 11 */
3336  avio_seek(s->pb, file_size - 4, SEEK_SET);
3337  length = avio_rb32(s->pb);
3338 
3339  if (length < min_rip_length || length > max_rip_length)
3340  goto end;
3341  avio_seek(s->pb, file_size - length, SEEK_SET);
3342  if (klv_read_packet(&klv, s->pb) < 0 ||
3344  goto end;
3345  if (klv.next_klv != file_size || klv.length <= 4 || (klv.length - 4) % 12) {
3346  av_log(s, AV_LOG_WARNING, "Invalid RIP KLV length\n");
3347  goto end;
3348  }
3349 
3350  avio_skip(s->pb, klv.length - 12);
3351  mxf->footer_partition = avio_rb64(s->pb);
3352 
3353  /* sanity check */
3354  if (mxf->run_in + mxf->footer_partition >= file_size) {
3355  av_log(s, AV_LOG_WARNING, "bad FooterPartition in RIP - ignoring\n");
3356  mxf->footer_partition = 0;
3357  }
3358 
3359 end:
3360  avio_seek(s->pb, mxf->run_in, SEEK_SET);
3361 }
3362 
3364 {
3365  MXFContext *mxf = s->priv_data;
3366  KLVPacket klv;
3367  int64_t essence_offset = 0;
3368  int ret;
3369 
3370  mxf->last_forward_tell = INT64_MAX;
3371 
3373  av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
3374  return AVERROR_INVALIDDATA;
3375  }
3376  avio_seek(s->pb, -14, SEEK_CUR);
3377  mxf->fc = s;
3378  mxf->run_in = avio_tell(s->pb);
3379 
3381 
3382  while (!avio_feof(s->pb)) {
3383  const MXFMetadataReadTableEntry *metadata;
3384 
3385  if (klv_read_packet(&klv, s->pb) < 0) {
3386  /* EOF - seek to previous partition or stop */
3387  if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
3388  break;
3389  else
3390  continue;
3391  }
3392 
3393  PRINT_KEY(s, "read header", klv.key);
3394  av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
3401 
3402  if (!mxf->current_partition) {
3403  av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
3404  return AVERROR_INVALIDDATA;
3405  }
3406 
3409 
3410  if (!essence_offset)
3411  essence_offset = klv.offset;
3412 
3413  /* seek to footer, previous partition or stop */
3414  if (mxf_parse_handle_essence(mxf) <= 0)
3415  break;
3416  continue;
3417  } else if (mxf_is_partition_pack_key(klv.key) && mxf->current_partition) {
3418  /* next partition pack - keep going, seek to previous partition or stop */
3419  if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
3420  break;
3421  else if (mxf->parsing_backward)
3422  continue;
3423  /* we're still parsing forward. proceed to parsing this partition pack */
3424  }
3425 
3426  for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
3427  if (IS_KLV_KEY(klv.key, metadata->key)) {
3428  if ((ret = mxf_parse_klv(mxf, klv, metadata->read, metadata->ctx_size, metadata->type)) < 0)
3429  return ret;
3430  break;
3431  }
3432  }
3433  if (!metadata->read) {
3434  av_log(s, AV_LOG_VERBOSE, "Dark key " PRIxUID "\n",
3435  UID_ARG(klv.key));
3436  avio_skip(s->pb, klv.length);
3437  }
3438  }
3439  /* FIXME avoid seek */
3440  if (!essence_offset) {
3441  av_log(s, AV_LOG_ERROR, "no essence\n");
3442  return AVERROR_INVALIDDATA;
3443  }
3444  avio_seek(s->pb, essence_offset, SEEK_SET);
3445 
3446  /* we need to do this before computing the index tables
3447  * to be able to fill in zero IndexDurations with st->duration */
3448  if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
3449  return ret;
3450 
3451  for (int i = 0; i < s->nb_streams; i++)
3452  mxf_handle_missing_index_segment(mxf, s->streams[i]);
3453 
3454  if ((ret = mxf_compute_index_tables(mxf)) < 0)
3455  return ret;
3456 
3457  if (mxf->nb_index_tables > 1) {
3458  /* TODO: look up which IndexSID to use via EssenceContainerData */
3459  av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
3460  mxf->nb_index_tables, mxf->index_tables[0].index_sid);
3461  } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom && (s->error_recognition & AV_EF_EXPLODE)) {
3462  av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
3463  return AVERROR_INVALIDDATA;
3464  }
3465 
3467 
3468  for (int i = 0; i < s->nb_streams; i++)
3469  mxf_compute_edit_units_per_packet(mxf, s->streams[i]);
3470 
3471  return 0;
3472 }
3473 
3474 /* Get the edit unit of the next packet from current_offset in a track. The returned edit unit can be original_duration as well! */
3475 static int mxf_get_next_track_edit_unit(MXFContext *mxf, MXFTrack *track, int64_t current_offset, int64_t *edit_unit_out)
3476 {
3477  int64_t a, b, m, offset;
3478  MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
3479 
3480  if (!t || track->original_duration <= 0)
3481  return -1;
3482 
3483  a = -1;
3484  b = track->original_duration;
3485 
3486  while (b - a > 1) {
3487  m = (a + b) >> 1;
3488  if (mxf_edit_unit_absolute_offset(mxf, t, m, track->edit_rate, NULL, &offset, NULL, 0) < 0)
3489  return -1;
3490  if (offset < current_offset)
3491  a = m;
3492  else
3493  b = m;
3494  }
3495 
3496  *edit_unit_out = b;
3497 
3498  return 0;
3499 }
3500 
3502  int64_t edit_unit)
3503 {
3504  MXFTrack *track = st->priv_data;
3505  AVRational time_base = av_inv_q(track->edit_rate);
3507 
3508  // For non-audio sample_count equals current edit unit
3510  return edit_unit;
3511 
3512  if ((sample_rate.num / sample_rate.den) == 48000) {
3513  return av_rescale_q(edit_unit, sample_rate, track->edit_rate);
3514  } else {
3515  int remainder = (sample_rate.num * time_base.num) %
3516  (time_base.den * sample_rate.den);
3517  if (remainder)
3518  av_log(mxf->fc, AV_LOG_WARNING,
3519  "seeking detected on stream #%d with time base (%d/%d) and "
3520  "sample rate (%d/%d), audio pts won't be accurate.\n",
3521  st->index, time_base.num, time_base.den,
3522  sample_rate.num, sample_rate.den);
3523  return av_rescale_q(edit_unit, sample_rate, track->edit_rate);
3524  }
3525 }
3526 
3527 /**
3528  * Make sure track->sample_count is correct based on what offset we're currently at.
3529  * Also determine the next edit unit (or packet) offset.
3530  * @return next_ofs if OK, <0 on error
3531  */
3532 static int64_t mxf_set_current_edit_unit(MXFContext *mxf, AVStream *st, int64_t current_offset, int resync)
3533 {
3534  int64_t next_ofs = -1;
3535  MXFTrack *track = st->priv_data;
3536  int64_t edit_unit = av_rescale_q(track->sample_count, st->time_base, av_inv_q(track->edit_rate));
3537  int64_t new_edit_unit;
3538  MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
3539 
3540  if (!t || track->wrapping == UnknownWrapped)
3541  return -1;
3542 
3543  if (mxf_edit_unit_absolute_offset(mxf, t, edit_unit + track->edit_units_per_packet, track->edit_rate, NULL, &next_ofs, NULL, 0) < 0 &&
3544  (next_ofs = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
3545  av_log(mxf->fc, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
3546  return -1;
3547  }
3548 
3549  /* check if the next edit unit offset (next_ofs) starts ahead of current_offset */
3550  if (next_ofs > current_offset)
3551  return next_ofs;
3552 
3553  if (!resync) {
3554  av_log(mxf->fc, AV_LOG_ERROR, "cannot find current edit unit for stream %d, invalid index?\n", st->index);
3555  return -1;
3556  }
3557 
3558  if (mxf_get_next_track_edit_unit(mxf, track, current_offset + 1, &new_edit_unit) < 0 || new_edit_unit <= 0) {
3559  av_log(mxf->fc, AV_LOG_ERROR, "failed to find next track edit unit in stream %d\n", st->index);
3560  return -1;
3561  }
3562 
3563  new_edit_unit--;
3564  track->sample_count = mxf_compute_sample_count(mxf, st, new_edit_unit);
3565  av_log(mxf->fc, AV_LOG_WARNING, "edit unit sync lost on stream %d, jumping from %"PRId64" to %"PRId64"\n", st->index, edit_unit, new_edit_unit);
3566 
3567  return mxf_set_current_edit_unit(mxf, st, current_offset, 0);
3568 }
3569 
3571  AVPacket *pkt)
3572 {
3573  AVStream *st = mxf->fc->streams[pkt->stream_index];
3574  MXFTrack *track = st->priv_data;
3575  int64_t bits_per_sample = par->bits_per_coded_sample;
3576 
3577  if (!bits_per_sample)
3578  bits_per_sample = av_get_bits_per_sample(par->codec_id);
3579 
3580  pkt->pts = track->sample_count;
3581 
3582  if ( par->channels <= 0
3583  || bits_per_sample <= 0
3584  || par->channels * (int64_t)bits_per_sample < 8)
3585  track->sample_count = mxf_compute_sample_count(mxf, st, av_rescale_q(track->sample_count, st->time_base, av_inv_q(track->edit_rate)) + 1);
3586  else
3587  track->sample_count += pkt->size / (par->channels * (int64_t)bits_per_sample / 8);
3588 
3589  return 0;
3590 }
3591 
3592 static int mxf_set_pts(MXFContext *mxf, AVStream *st, AVPacket *pkt)
3593 {
3594  AVCodecParameters *par = st->codecpar;
3595  MXFTrack *track = st->priv_data;
3596 
3597  if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
3598  /* see if we have an index table to derive timestamps from */
3599  MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
3600 
3601  if (t && track->sample_count < t->nb_ptses) {
3602  pkt->dts = track->sample_count + t->first_dts;
3603  pkt->pts = t->ptses[track->sample_count];
3604  } else if (track->intra_only) {
3605  /* intra-only -> PTS = EditUnit.
3606  * let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */
3607  pkt->pts = track->sample_count;
3608  }
3609  track->sample_count++;
3610  } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
3611  int ret = mxf_set_audio_pts(mxf, par, pkt);
3612  if (ret < 0)
3613  return ret;
3614  } else if (track) {
3615  pkt->dts = pkt->pts = track->sample_count;
3616  pkt->duration = 1;
3617  track->sample_count++;
3618  }
3619  return 0;
3620 }
3621 
3623 {
3624  KLVPacket klv;
3625  MXFContext *mxf = s->priv_data;
3626  int ret;
3627 
3628  while (1) {
3629  int64_t max_data_size;
3630  int64_t pos = avio_tell(s->pb);
3631 
3632  if (pos < mxf->current_klv_data.next_klv - mxf->current_klv_data.length || pos >= mxf->current_klv_data.next_klv) {
3633  mxf->current_klv_data = (KLVPacket){{0}};
3634  ret = klv_read_packet(&klv, s->pb);
3635  if (ret < 0)
3636  break;
3637  max_data_size = klv.length;
3638  pos = klv.next_klv - klv.length;
3639  PRINT_KEY(s, "read packet", klv.key);
3640  av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
3642  ret = mxf_decrypt_triplet(s, pkt, &klv);
3643  if (ret < 0) {
3644  av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
3645  return ret;
3646  }
3647  return 0;
3648  }
3649  } else {
3650  klv = mxf->current_klv_data;
3651  max_data_size = klv.next_klv - pos;
3652  }
3656  int body_sid = find_body_sid_by_absolute_offset(mxf, klv.offset);
3657  int index = mxf_get_stream_index(s, &klv, body_sid);
3658  int64_t next_ofs;
3659  AVStream *st;
3660  MXFTrack *track;
3661 
3662  if (index < 0) {
3664  "error getting stream index %"PRIu32"\n",
3665  AV_RB32(klv.key + 12));
3666  goto skip;
3667  }
3668 
3669  st = s->streams[index];
3670  track = st->priv_data;
3671 
3672  if (s->streams[index]->discard == AVDISCARD_ALL)
3673  goto skip;
3674 
3675  next_ofs = mxf_set_current_edit_unit(mxf, st, pos, 1);
3676 
3677  if (track->wrapping != FrameWrapped) {
3678  int64_t size;
3679 
3680  if (next_ofs <= 0) {
3681  // If we have no way to packetize the data, then return it in chunks...
3682  if (klv.next_klv - klv.length == pos && max_data_size > MXF_MAX_CHUNK_SIZE) {
3684  avpriv_request_sample(s, "Huge KLV without proper index in non-frame wrapped essence");
3685  }
3686  size = FFMIN(max_data_size, MXF_MAX_CHUNK_SIZE);
3687  } else {
3688  if ((size = next_ofs - pos) <= 0) {
3689  av_log(s, AV_LOG_ERROR, "bad size: %"PRId64"\n", size);
3690  mxf->current_klv_data = (KLVPacket){{0}};
3691  return AVERROR_INVALIDDATA;
3692  }
3693  // We must not overread, because the next edit unit might be in another KLV
3694  if (size > max_data_size)
3695  size = max_data_size;
3696  }
3697 
3698  mxf->current_klv_data = klv;
3699  klv.offset = pos;
3700  klv.length = size;
3701  klv.next_klv = klv.offset + klv.length;
3702  }
3703 
3704  /* check for 8 channels AES3 element */
3705  if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
3706  ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index],
3707  pkt, klv.length);
3708  if (ret < 0) {
3709  av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
3710  mxf->current_klv_data = (KLVPacket){{0}};
3711  return ret;
3712  }
3713  } else if (mxf->eia608_extract &&
3714  s->streams[index]->codecpar->codec_id == AV_CODEC_ID_EIA_608) {
3715  ret = mxf_get_eia608_packet(s, s->streams[index], pkt, klv.length);
3716  if (ret < 0) {
3717  mxf->current_klv_data = (KLVPacket){{0}};
3718  return ret;
3719  }
3720  } else {
3721  ret = av_get_packet(s->pb, pkt, klv.length);
3722  if (ret < 0) {
3723  mxf->current_klv_data = (KLVPacket){{0}};
3724  return ret;
3725  }
3726  }
3727  pkt->stream_index = index;
3728  pkt->pos = klv.offset;
3729 
3730  ret = mxf_set_pts(mxf, st, pkt);
3731  if (ret < 0) {
3732  mxf->current_klv_data = (KLVPacket){{0}};
3733  return ret;
3734  }
3735 
3736  /* seek for truncated packets */
3737  avio_seek(s->pb, klv.next_klv, SEEK_SET);
3738 
3739  return 0;
3740  } else {
3741  skip:
3742  avio_skip(s->pb, max_data_size);
3743  mxf->current_klv_data = (KLVPacket){{0}};
3744  }
3745  }
3746  return avio_feof(s->pb) ? AVERROR_EOF : ret;
3747 }
3748 
3750 {
3751  MXFContext *mxf = s->priv_data;
3752  int i;
3753 
3754  av_freep(&mxf->packages_refs);
3756 
3757  for (i = 0; i < s->nb_streams; i++)
3758  s->streams[i]->priv_data = NULL;
3759 
3760  for (i = 0; i < mxf->metadata_sets_count; i++) {
3762  }
3763  mxf->metadata_sets_count = 0;
3764  av_freep(&mxf->partitions);
3765  av_freep(&mxf->metadata_sets);
3766  av_freep(&mxf->aesc);
3767  av_freep(&mxf->local_tags);
3768 
3769  if (mxf->index_tables) {
3770  for (i = 0; i < mxf->nb_index_tables; i++) {
3771  av_freep(&mxf->index_tables[i].segments);
3772  av_freep(&mxf->index_tables[i].ptses);
3774  av_freep(&mxf->index_tables[i].offsets);
3775  }
3776  }
3777  av_freep(&mxf->index_tables);
3778 
3779  return 0;
3780 }
3781 
3782 static int mxf_probe(const AVProbeData *p) {
3783  const uint8_t *bufp = p->buf;
3784  const uint8_t *end = p->buf + p->buf_size;
3785 
3786  if (p->buf_size < sizeof(mxf_header_partition_pack_key))
3787  return 0;
3788 
3789  /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
3790  end -= sizeof(mxf_header_partition_pack_key);
3791 
3792  for (; bufp < end;) {
3793  if (!((bufp[13] - 1) & 0xF2)){
3794  if (AV_RN32(bufp ) == AV_RN32(mxf_header_partition_pack_key ) &&
3795  AV_RN32(bufp+ 4) == AV_RN32(mxf_header_partition_pack_key+ 4) &&
3796  AV_RN32(bufp+ 8) == AV_RN32(mxf_header_partition_pack_key+ 8) &&
3798  return bufp == p->buf ? AVPROBE_SCORE_MAX : AVPROBE_SCORE_MAX - 1;
3799  bufp ++;
3800  } else
3801  bufp += 10;
3802  }
3803 
3804  return 0;
3805 }
3806 
3807 /* rudimentary byte seek */
3808 /* XXX: use MXF Index */
3809 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3810 {
3811  AVStream *st = s->streams[stream_index];
3812  int64_t seconds;
3813  MXFContext* mxf = s->priv_data;
3814  int64_t seekpos;
3815  int i, ret;
3816  MXFIndexTable *t;
3817  MXFTrack *source_track = st->priv_data;
3818 
3819  if (!source_track)
3820  return 0;
3821 
3822  /* if audio then truncate sample_time to EditRate */
3824  sample_time = av_rescale_q(sample_time, st->time_base,
3825  av_inv_q(source_track->edit_rate));
3826 
3827  if (mxf->nb_index_tables <= 0) {
3828  if (!s->bit_rate)
3829  return AVERROR_INVALIDDATA;
3830  if (sample_time < 0)
3831  sample_time = 0;
3832  seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
3833 
3834  seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);
3835  if (seekpos < 0)
3836  return seekpos;
3837 
3838  avpriv_update_cur_dts(s, st, sample_time);
3839  mxf->current_klv_data = (KLVPacket){{0}};
3840  } else {
3841  MXFPartition *partition;
3842 
3843  t = &mxf->index_tables[0];
3844  if (t->index_sid != source_track->index_sid) {
3845  /* If the first index table does not belong to the stream, then find a stream which does belong to the index table */
3846  for (i = 0; i < s->nb_streams; i++) {
3847  MXFTrack *new_source_track = s->streams[i]->priv_data;
3848  if (new_source_track && new_source_track->index_sid == t->index_sid) {
3849  sample_time = av_rescale_q(sample_time, new_source_track->edit_rate, source_track->edit_rate);
3850  source_track = new_source_track;
3851  st = s->streams[i];
3852  break;
3853  }
3854  }
3855  if (i == s->nb_streams)
3856  return AVERROR_INVALIDDATA;
3857  }
3858 
3859  /* clamp above zero, else ff_index_search_timestamp() returns negative
3860  * this also means we allow seeking before the start */
3861  sample_time = FFMAX(sample_time, 0);
3862 
3863  if (t->fake_index) {
3864  /* The first frames may not be keyframes in presentation order, so
3865  * we have to advance the target to be able to find the first
3866  * keyframe backwards... */
3867  if (!(flags & AVSEEK_FLAG_ANY) &&
3869  t->ptses[0] != AV_NOPTS_VALUE &&
3870  sample_time < t->ptses[0] &&
3871  (t->fake_index[t->ptses[0]].flags & AVINDEX_KEYFRAME))
3872  sample_time = t->ptses[0];
3873 
3874  /* behave as if we have a proper index */
3875  if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
3876  return sample_time;
3877  /* get the stored order index from the display order index */
3878  sample_time += t->offsets[sample_time];
3879  } else {
3880  /* no IndexEntryArray (one or more CBR segments)
3881  * make sure we don't seek past the end */
3882  sample_time = FFMIN(sample_time, source_track->original_duration - 1);
3883  }
3884 
3885  if (source_track->wrapping == UnknownWrapped)
3886  av_log(mxf->fc, AV_LOG_WARNING, "attempted seek in an UnknownWrapped essence\n");
3887 
3888  if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, source_track->edit_rate, &sample_time, &seekpos, &partition, 1)) < 0)
3889  return ret;
3890 
3891  avpriv_update_cur_dts(s, st, sample_time);
3892  if (source_track->wrapping == ClipWrapped) {
3893  KLVPacket klv = partition->first_essence_klv;
3894  if (seekpos < klv.next_klv - klv.length || seekpos >= klv.next_klv) {
3895  av_log(mxf->fc, AV_LOG_ERROR, "attempted seek out of clip wrapped KLV\n");
3896  return AVERROR_INVALIDDATA;
3897  }
3898  mxf->current_klv_data = klv;
3899  } else {
3900  mxf->current_klv_data = (KLVPacket){{0}};
3901  }
3902  avio_seek(s->pb, seekpos, SEEK_SET);
3903  }
3904 
3905  // Update all tracks sample count
3906  for (i = 0; i < s->nb_streams; i++) {
3907  AVStream *cur_st = s->streams[i];
3908  MXFTrack *cur_track = cur_st->priv_data;
3909  if (cur_track) {
3910  int64_t track_edit_unit = sample_time;
3911  if (st != cur_st)
3912  mxf_get_next_track_edit_unit(mxf, cur_track, seekpos, &track_edit_unit);
3913  cur_track->sample_count = mxf_compute_sample_count(mxf, cur_st, track_edit_unit);
3914  }
3915  }
3916  return 0;
3917 }
3918 
3919 static const AVOption options[] = {
3920  { "eia608_extract", "extract eia 608 captions from s436m track",
3921  offsetof(MXFContext, eia608_extract), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1,
3923  { NULL },
3924 };
3925 
3926 static const AVClass demuxer_class = {
3927  .class_name = "mxf",
3928  .item_name = av_default_item_name,
3929  .option = options,
3930  .version = LIBAVUTIL_VERSION_INT,
3931  .category = AV_CLASS_CATEGORY_DEMUXER,
3932 };
3933 
3935  .name = "mxf",
3936  .long_name = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
3937  .flags = AVFMT_SEEK_TO_PTS,
3938  .priv_data_size = sizeof(MXFContext),
3939  .flags_internal = FF_FMT_INIT_CLEANUP,
3940  .read_probe = mxf_probe,
3945  .priv_class = &demuxer_class,
3946 };
AV_CODEC_ID_PCM_S16LE
@ AV_CODEC_ID_PCM_S16LE
Definition: codec_id.h:314
mxf_read_generic_descriptor
static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:1197
AVMasteringDisplayMetadata::has_primaries
int has_primaries
Flag indicating whether the display primaries (and white point) are set.
Definition: mastering_display_metadata.h:62
mxf_read_header
static int mxf_read_header(AVFormatContext *s)
Definition: mxfdec.c:3363
AV_CODEC_ID_EIA_608
@ AV_CODEC_ID_EIA_608
Definition: codec_id.h:532
MXFMetadataSet::uid
UID uid
Definition: mxfdec.c:110
be
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it be(in the first position) for now. Options ------- Then comes the options array. This is what will define the user accessible options. For example
OPSONYOpt
@ OPSONYOpt
Definition: mxfdec.c:81
MXFContext::op
MXFOP op
Definition: mxfdec.c:272
MXFIndexTable::offsets
int8_t * offsets
Definition: mxfdec.c:265
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
AV_TIMECODE_STR_SIZE
#define AV_TIMECODE_STR_SIZE
Definition: timecode.h:33
av_aes_init
int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt)
Initialize an AVAES context.
Definition: aes.c:195
AVMasteringDisplayMetadata::max_luminance
AVRational max_luminance
Max luminance of mastering display (cd/m^2).
Definition: mastering_display_metadata.h:57
AVCodecParameters::extradata
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
name
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option name
Definition: writing_filters.txt:88
mxf_read_cryptographic_context
static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:885
mxf_read_timecode_component
static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:981
av_clip
#define av_clip
Definition: common.h:96
mxf_compute_essence_containers
static void mxf_compute_essence_containers(AVFormatContext *s)
Figures out the proper offset and length of the essence container in each partition.
Definition: mxfdec.c:3151
FF_FMT_INIT_CLEANUP
#define FF_FMT_INIT_CLEANUP
For an AVInputFormat with this flag set read_close() needs to be called by the caller upon read_heade...
Definition: internal.h:48
ff_mxf_color_primaries_uls
const MXFCodecUL ff_mxf_color_primaries_uls[]
Definition: mxf.c:92
mxf_set_audio_pts
static int mxf_set_audio_pts(MXFContext *mxf, AVCodecParameters *par, AVPacket *pkt)
Definition: mxfdec.c:3570
mxf_add_timecode_metadata
static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
Definition: mxfdec.c:2027
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
uid
UID uid
Definition: mxfenc.c:2197
opt.h
avformat_new_stream
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:760
OPAtom
@ OPAtom
Definition: mxfdec.c:80
Track
Definition: ismindex.c:69
mxf_read_sequence
static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:1033
AVCodecParameters::codec_type
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
MXFTrack::edit_rate
AVRational edit_rate
Definition: mxfdec.c:172
mxf_resolve_essence_group_choice
static MXFStructuralComponent * mxf_resolve_essence_group_choice(MXFContext *mxf, MXFEssenceGroup *essence_group)
Definition: mxfdec.c:2098
OP2b
@ OP2b
Definition: mxfdec.c:75
FF_MXF_MasteringDisplayMinimumLuminance
#define FF_MXF_MasteringDisplayMinimumLuminance
Definition: mxf.h:94
AVCodecParameters
This struct describes the properties of an encoded stream.
Definition: codec_par.h:52
MXFContext::index_tables
MXFIndexTable * index_tables
Definition: mxfdec.c:291
mxf_parse_package_comments
static int mxf_parse_package_comments(MXFContext *mxf, AVDictionary **pm, MXFPackage *package)
Definition: mxfdec.c:2143
MXFPartition::complete
int complete
Definition: mxfdec.c:92
AVCodecParameters::color_space
enum AVColorSpace color_space
Definition: codec_par.h:149
AVStream::priv_data
void * priv_data
Definition: avformat.h:944
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
avcodec_get_type
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: codec_desc.c:3546
RawVWrap
@ RawVWrap
Definition: mxf.h:79
AVMasteringDisplayMetadata::display_primaries
AVRational display_primaries[3][2]
CIE 1931 xy chromaticity coords of color primaries (r, g, b order).
Definition: mastering_display_metadata.h:42
TaggedValue
@ TaggedValue
Definition: mxf.h:50
AVMasteringDisplayMetadata::has_luminance
int has_luminance
Flag indicating whether the luminance (min_ and max_) have been set.
Definition: mastering_display_metadata.h:67
AV_CODEC_ID_DIRAC
@ AV_CODEC_ID_DIRAC
Definition: codec_id.h:166
mxf_read_primer_pack
static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:642
av_asprintf
char * av_asprintf(const char *fmt,...)
Definition: avstring.c:113
mxf_intra_only_picture_coded_width
static const MXFCodecUL mxf_intra_only_picture_coded_width[]
Definition: mxfdec.c:1472
AV_CODEC_ID_RAWVIDEO
@ AV_CODEC_ID_RAWVIDEO
Definition: codec_id.h:63
MXFPartition::kag_size
int32_t kag_size
Definition: mxfdec.c:100
MXFPartition::type
MXFPartitionType type
Definition: mxfdec.c:93
OP3b
@ OP3b
Definition: mxfdec.c:78
FF_MXF_MasteringDisplayPrimaries
#define FF_MXF_MasteringDisplayPrimaries
Definition: mxf.h:91
KLVPacket::offset
int64_t offset
Definition: mxf.h:70
AV_RN16
#define AV_RN16(p)
Definition: intreadwrite.h:360
AVContentLightMetadata::MaxCLL
unsigned MaxCLL
Max content light level (cd/m^2).
Definition: mastering_display_metadata.h:102
avio_get_str16be
int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen)
KLVPacket::key
UID key
Definition: mxf.h:69
tmp
static uint8_t tmp[11]
Definition: aes_ctr.c:26
AVFormatContext::streams
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1261
index
fg index
Definition: ffmpeg_filter.c:167
mxf_indirect_value_utf16be
static const uint8_t mxf_indirect_value_utf16be[]
Definition: mxfdec.c:322
AVCOL_RANGE_JPEG
@ AVCOL_RANGE_JPEG
Full range content.
Definition: pixfmt.h:597
MXFStructuralComponent::source_track_id
int source_track_id
Definition: mxfdec.c:127
MXFEssenceContainerData::package_ul
UID package_ul
Definition: mxfdec.c:250
AVPacket::data
uint8_t * data
Definition: packet.h:373
SourceClip
@ SourceClip
Definition: mxf.h:35
MXFWrappingScheme
MXFWrappingScheme
Definition: mxfdec.c:84
mxf_read_pixel_layout
static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
Definition: mxfdec.c:1177
AVOption
AVOption.
Definition: opt.h:247
b
#define b
Definition: input.c:40
mxf_resolve_strong_ref
static void * mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
Definition: mxfdec.c:1422
MXFTrack::index_sid
int index_sid
Definition: mxfdec.c:176
mxf_data_essence_container_uls
static const MXFCodecUL mxf_data_essence_container_uls[]
Definition: mxfdec.c:1490
MXFDescriptor::video_line_map
int video_line_map[2]
Definition: mxfdec.c:192
MXFDescriptor::field_dominance
int field_dominance
Definition: mxfdec.c:196
mxf_set_pts
static int mxf_set_pts(MXFContext *mxf, AVStream *st, AVPacket *pkt)
Definition: mxfdec.c:3592
MXFContext::packages_refs
UID * packages_refs
Definition: mxfdec.c:273
MXFStructuralComponent::source_package_uid
UID source_package_uid
Definition: mxfdec.c:123
MXFPartition
Definition: mxfdec.c:90
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:196
OP1a
@ OP1a
Definition: mxfdec.c:71
mxf_read_content_storage
static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:945
AVPacket::duration
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:391
MXFMetadataSet
Definition: mxfdec.c:109
AVCodecParameters::codec_tag
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:64
mxf_read_track
static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:1009
mxf_intra_only_essence_container_uls
static const MXFCodecUL mxf_intra_only_essence_container_uls[]
Definition: mxfdec.c:1459
MXFPartition::pack_length
int pack_length
Definition: mxfdec.c:103
mathematics.h
AVDictionary
Definition: dict.c:30
AVProbeData::buf_size
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:450
MXFIndexTableSegment::flag_entries
int * flag_entries
Definition: mxfdec.c:229
MXFContext::current_klv_data
KLVPacket current_klv_data
Definition: mxfdec.c:284
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
mxf_parse_handle_essence
static int mxf_parse_handle_essence(MXFContext *mxf)
Called when essence is encountered.
Definition: mxfdec.c:3090
MXFEssenceContainerData::package_uid
UID package_uid
Definition: mxfdec.c:249
MXFDescriptor::black_ref_level
unsigned int black_ref_level
Definition: mxfdec.c:201
MXFDescriptor::essence_container_ul
UID essence_container_ul
Definition: mxfdec.c:184
MXFPulldownComponent
Definition: mxfdec.c:147
MXFIndexTableSegment::index_edit_rate
AVRational index_edit_rate
Definition: mxfdec.c:225
MXFDescriptor::essence_codec_ul
UID essence_codec_ul
Definition: mxfdec.c:185
MXFIndexTableSegment::index_duration
uint64_t index_duration
Definition: mxfdec.c:227
MXFDescriptor::file_descriptors_count
int file_descriptors_count
Definition: mxfdec.c:207
mxf_header_partition_pack_key
static const uint8_t mxf_header_partition_pack_key[]
Definition: mxfdec.c:306
Footer
@ Footer
Definition: mxfdec.c:67
MXFPackage::comment_refs
UID * comment_refs
Definition: mxfdec.c:243
MXFContext
Definition: mxfdec.c:268
MXFTrack::sequence_ref
UID sequence_ref
Definition: mxfdec.c:168
ff_mxf_color_trc_uls
const MXFCodecUL ff_mxf_color_trc_uls[]
Definition: mxf.c:107
mxf_parse_structural_metadata
static int mxf_parse_structural_metadata(MXFContext *mxf)
Definition: mxfdec.c:2295
avio_size
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:352
TimecodeComponent
@ TimecodeComponent
Definition: mxf.h:36
MXFDescriptor::color_range
unsigned int color_range
Definition: mxfdec.c:203
sample_rate
sample_rate
Definition: ffmpeg_filter.c:153
FF_MXF_MasteringDisplay_PREFIX
#define FF_MXF_MasteringDisplay_PREFIX
Definition: mxf.h:90
SeparateFields
@ SeparateFields
Definition: mxf.h:57
AVIndexEntry
Definition: avformat.h:794
MXFCryptoContext::source_container_ul
UID source_container_ul
Definition: mxfdec.c:117
MXFDescriptor::width
int width
Definition: mxfdec.c:189
av_malloc
#define av_malloc(s)
Definition: tableprint_vlc.h:31
AVINDEX_KEYFRAME
#define AVINDEX_KEYFRAME
Definition: avformat.h:802
ff_mxf_codec_tag_uls
const MXFCodecUL ff_mxf_codec_tag_uls[]
Definition: mxf.c:87
MXFEssenceGroup
Definition: mxfdec.c:152
AVContentLightMetadata
Content light level needed by to transmit HDR over HDMI (CTA-861.3).
Definition: mastering_display_metadata.h:98
READ_STR16
#define READ_STR16(type, big_endian)
Definition: mxfdec.c:936
AVCodecParameters::color_primaries
enum AVColorPrimaries color_primaries
Definition: codec_par.h:147
AVPROBE_SCORE_MAX
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:459
MXFPackage::descriptor
MXFDescriptor * descriptor
Definition: mxfdec.c:240
mxf_find_index_table
static MXFIndexTable * mxf_find_index_table(MXFContext *mxf, int index_sid)
Definition: mxfdec.c:3196
MXFPartitionType
MXFPartitionType
Definition: mxfdec.c:64
mxf_read_essence_group
static int mxf_read_essence_group(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
Definition: mxfdec.c:1053
MXFEssenceContainerData::meta
MXFMetadataSet meta
Definition: mxfdec.c:248
MXFIndexTableSegment::nb_index_entries
int nb_index_entries
Definition: mxfdec.c:231
MXFTrack::edit_units_per_packet
int edit_units_per_packet
Definition: mxfdec.c:179
mxf.h
AVCodecParameters::channels
int channels
Audio only.
Definition: codec_par.h:166
mxf_set_current_edit_unit
static int64_t mxf_set_current_edit_unit(MXFContext *mxf, AVStream *st, int64_t current_offset, int resync)
Make sure track->sample_count is correct based on what offset we're currently at.
Definition: mxfdec.c:3532
AV_FIELD_TT
@ AV_FIELD_TT
Definition: codec_par.h:39
mxf_apple_coll_max_fall
static const uint8_t mxf_apple_coll_max_fall[]
Definition: mxfdec.c:324
MXFPartition::closed
int closed
Definition: mxfdec.c:91
ffstream
static av_always_inline FFStream * ffstream(AVStream *st)
Definition: internal.h:434
AVFMT_SEEK_TO_PTS
#define AVFMT_SEEK_TO_PTS
Seeking is based on PTS.
Definition: avformat.h:490
AV_CODEC_ID_PCM_S16BE
@ AV_CODEC_ID_PCM_S16BE
Definition: codec_id.h:315
AVSEEK_FLAG_ANY
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition: avformat.h:2257
read_seek
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:149
av_shrink_packet
void av_shrink_packet(AVPacket *pkt, int size)
Reduce packet size, correctly zeroing padding.
Definition: avpacket.c:114
MXFDescriptor::channels
int channels
Definition: mxfdec.c:197
timecode.h
mxf_get_next_track_edit_unit
static int mxf_get_next_track_edit_unit(MXFContext *mxf, MXFTrack *track, int64_t current_offset, int64_t *edit_unit_out)
Definition: mxfdec.c:3475
MXFDescriptor::coll_size
size_t coll_size
Definition: mxfdec.c:217
mxf_read_random_index_pack
static void mxf_read_random_index_pack(AVFormatContext *s)
Definition: mxfdec.c:3309
MXFCodecUL::id
int id
Definition: mxf.h:102
av_timecode_make_string
char * av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum)
Load timecode string in buf.
Definition: timecode.c:102
MXFMetadataReadTableEntry::key
const UID key
Definition: mxfdec.c:299
read_close
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:141
MXFTrack::original_duration
int64_t original_duration
Definition: mxfdec.c:175
avio_tell
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:504
mxf_handle_missing_index_segment
static int mxf_handle_missing_index_segment(MXFContext *mxf, AVStream *st)
Deal with the case where ClipWrapped essences does not have any IndexTableSegments.
Definition: mxfdec.c:3241
MXFSequence::structural_components_refs
UID * structural_components_refs
Definition: mxfdec.c:133
val
static double val(void *priv, double ch)
Definition: aeval.c:76
FF_ALLOC_TYPED_ARRAY
#define FF_ALLOC_TYPED_ARRAY(p, nelem)
Definition: internal.h:97
type
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
Definition: writing_filters.txt:86
av_timegm
time_t av_timegm(struct tm *tm)
Convert the decomposed UTC time in tm to a time_t value.
Definition: parseutils.c:570
MXFDescriptor::mastering
AVMasteringDisplayMetadata * mastering
Definition: mxfdec.c:215
MXFIndexTable::first_dts
int64_t first_dts
Definition: mxfdec.c:260
AVStream::duration
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:978
MXFDescriptor::horiz_subsampling
unsigned int horiz_subsampling
Definition: mxfdec.c:204
AV_FIELD_TB
@ AV_FIELD_TB
Definition: codec_par.h:41
MXFPackage::meta
MXFMetadataSet meta
Definition: mxfdec.c:235
AVRational::num
int num
Numerator.
Definition: rational.h:59
mxf_absolute_bodysid_offset
static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out, MXFPartition **partition_out)
Computes the absolute file offset of the given essence container offset.
Definition: mxfdec.c:1622
MXFTrack::meta
MXFMetadataSet meta
Definition: mxfdec.c:166
MXFContext::last_forward_partition
int last_forward_partition
Definition: mxfdec.c:289
AV_DICT_DONT_STRDUP_VAL
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition: dict.h:72
av_get_bits_per_sample
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:591
AVCodecParameters::color_trc
enum AVColorTransferCharacteristic color_trc
Definition: codec_par.h:148
mxf_version_to_str
static int mxf_version_to_str(uint16_t major, uint16_t minor, uint16_t tertiary, uint16_t patch, uint16_t release, char **str)
Definition: mxfdec.c:2006
MXFDescriptor::frame_layout
int frame_layout
Definition: mxfdec.c:191
mxf_timestamp_to_int64
static int64_t mxf_timestamp_to_int64(uint64_t timestamp)
Definition: mxfdec.c:2749
OneField
@ OneField
Definition: mxf.h:58
MXFDescriptor::linked_track_id
int linked_track_id
Definition: mxfdec.c:208
mxf_read_identification_metadata
static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset)
Definition: mxfdec.c:2802
mxf_add_metadata_set
static int mxf_add_metadata_set(MXFContext *mxf, MXFMetadataSet **metadata_set)
Definition: mxfdec.c:854
MXFPackage::tracks_refs
UID * tracks_refs
Definition: mxfdec.c:238
mxf_probe
static int mxf_probe(const AVProbeData *p)
Definition: mxfdec.c:3782
MXFMetadataReadTableEntry
Definition: mxfdec.c:298
avio_rb32
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:790
AV_LOG_TRACE
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:206
pkt
AVPacket * pkt
Definition: movenc.c:59
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
AVFormatContext::metadata
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1422
MXFEssenceGroup::structural_components_count
int structural_components_count
Definition: mxfdec.c:155
mxf_metadata_read_table
static const MXFMetadataReadTableEntry mxf_metadata_read_table[]
Definition: mxfdec.c:2859
AVInputFormat
Definition: avformat.h:643
mxf_compute_ptses_fake_index
static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
Definition: mxfdec.c:1729
MXFIndexTableSegment
Definition: mxfdec.c:220
MXFIndexTable::nb_segments
int nb_segments
Definition: mxfdec.c:262
PRINT_KEY
#define PRINT_KEY(pc, s, x)
Definition: mxf.h:149
MXFDescriptor::duration
int64_t duration
Definition: mxfdec.c:199
MXFPartit