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 #include <time.h>
49 
50 #include "libavutil/aes.h"
51 #include "libavutil/avstring.h"
53 #include "libavutil/mathematics.h"
54 #include "libavcodec/bytestream.h"
55 #include "libavcodec/defs.h"
56 #include "libavcodec/internal.h"
59 #include "libavutil/intreadwrite.h"
60 #include "libavutil/parseutils.h"
61 #include "libavutil/timecode.h"
62 #include "libavutil/opt.h"
63 #include "avformat.h"
64 #include "avlanguage.h"
65 #include "demux.h"
66 #include "internal.h"
67 #include "mxf.h"
68 
69 #define MXF_MAX_CHUNK_SIZE (32 << 20)
70 #define RUN_IN_MAX (65535+1) // S377m-2004 section 5.5 and S377-1-2009 section 6.5, the +1 is to be slightly more tolerant
71 
72 typedef enum {
77 
78 typedef enum {
79  OP1a = 1,
89  OPSONYOpt, /* FATE sample, violates the spec in places */
90 } MXFOP;
91 
92 typedef enum {
97 
98 typedef struct MXFPartition {
99  int closed;
100  int complete;
104  int body_sid;
105  int64_t essence_offset; ///< absolute offset of essence
106  int64_t essence_length;
111  int64_t pack_ofs; ///< absolute offset of pack in file, including run-in
112  int64_t body_offset;
114 } MXFPartition;
115 
116 typedef struct MXFMetadataSet {
118  uint64_t partition_score;
121 
122 typedef struct MXFCryptoContext {
126 
127 typedef struct MXFStructuralComponent {
132  int64_t duration;
133  int64_t start_position;
136 
137 typedef struct MXFSequence {
142  int64_t duration;
143  uint8_t origin;
144 } MXFSequence;
145 
146 typedef struct MXFTimecodeComponent {
150  struct AVRational rate;
153 
154 typedef struct {
158 
159 typedef struct {
163  int64_t duration;
165 
166 typedef struct {
168  char *name;
169  char *value;
171 
172 typedef struct {
174  MXFSequence *sequence; /* mandatory, and only one */
176  int track_id;
177  char *name;
178  uint8_t track_number[4];
181  uint64_t sample_count;
182  int64_t original_duration; /* st->duration in SampleRate/EditRate units */
184  int body_sid;
186  int edit_units_per_packet; /* how many edit units to read at a time (PCM, ClipWrapped) */
188  int channel_ordering[FF_SANE_NB_CHANNELS];
189 } MXFTrack;
190 
191 typedef struct MXFDescriptor {
198  int width;
199  int height; /* Field height, not frame height */
200  int frame_layout; /* See MXFFrameLayout enum */
202 #define MXF_FIELD_DOMINANCE_DEFAULT 0
203 #define MXF_FIELD_DOMINANCE_FF 1 /* coded first, displayed first */
204 #define MXF_FIELD_DOMINANCE_FL 2 /* coded first, displayed last */
206  int channels;
208  int64_t duration; /* ContainerDuration optional property */
209  unsigned int component_depth;
210  unsigned int black_ref_level;
211  unsigned int white_ref_level;
212  unsigned int color_range;
213  unsigned int horiz_subsampling;
214  unsigned int vert_subsampling;
220  uint8_t *extradata;
228  size_t coll_size;
229 } MXFDescriptor;
230 
231 typedef struct MXFMCASubDescriptor {
240  char *language;
242 
243 typedef struct MXFFFV1SubDescriptor {
245  uint8_t *extradata;
248 
249 typedef struct MXFIndexTableSegment {
253  int body_sid;
256  uint64_t index_duration;
262 
263 typedef struct MXFPackage {
270  char *name;
273 } MXFPackage;
274 
275 typedef struct MXFEssenceContainerData {
280  int body_sid;
282 
283 /* decoded index table */
284 typedef struct MXFIndexTable {
286  int body_sid;
287  int nb_ptses; /* number of PTSes or total duration of index */
288  int64_t first_dts; /* DTS = EditUnit + first_dts */
289  int64_t *ptses; /* maps EditUnit -> PTS */
291  MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */
292  AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */
293  int8_t *offsets; /* temporal offsets for display order to stored order conversion */
294 } MXFIndexTable;
295 
296 typedef struct MXFContext {
297  const AVClass *class; /**< Class for private options. */
308  struct AVAES *aesc;
309  uint8_t *local_tags;
313  int run_in;
321 } MXFContext;
322 
323 /* NOTE: klv_offset is not set (-1) for local keys */
324 typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
325 
327  const UID key;
329  int ctx_size;
332 
333 /* partial keys to match */
334 static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
335 static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
336 static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
337 static const uint8_t mxf_canopus_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x0a,0x0e,0x0f,0x03,0x01 };
338 static const uint8_t mxf_system_item_key_cp[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x03,0x01,0x04 };
339 static const uint8_t mxf_system_item_key_gc[] = { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x03,0x01,0x14 };
340 static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
341 static const uint8_t mxf_apple_coll_prefix[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x0e,0x20,0x04,0x01,0x05,0x03,0x01 };
342 
343 /* complete keys to match */
344 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 };
345 static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
346 static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
347 static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
348 static const uint8_t mxf_ffv1_extradata[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x04,0x01,0x06,0x0c,0x01,0x00,0x00,0x00 }; // FFV1InitializationMetadata
349 static const uint8_t mxf_avid_project_name[] = { 0xa5,0xfb,0x7b,0x25,0xf6,0x15,0x94,0xb9,0x62,0xfc,0x37,0x17,0x49,0x2d,0x42,0xbf };
350 static const uint8_t mxf_jp2k_rsiz[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0a,0x04,0x01,0x06,0x03,0x01,0x00,0x00,0x00 };
351 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 };
352 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 };
353 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 };
354 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 };
355 
356 static const uint8_t mxf_mca_label_dictionary_id[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x01,0x03,0x07,0x01,0x01,0x00,0x00,0x00 };
357 static const uint8_t mxf_mca_tag_symbol[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x01,0x03,0x07,0x01,0x02,0x00,0x00,0x00 };
358 static const uint8_t mxf_mca_tag_name[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x01,0x03,0x07,0x01,0x03,0x00,0x00,0x00 };
359 static const uint8_t mxf_group_of_soundfield_groups_link_id[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x01,0x03,0x07,0x01,0x04,0x00,0x00,0x00 };
360 static const uint8_t mxf_mca_link_id[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x01,0x03,0x07,0x01,0x05,0x00,0x00,0x00 };
361 static const uint8_t mxf_mca_channel_id[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x01,0x03,0x04,0x0a,0x00,0x00,0x00,0x00 };
362 static const uint8_t mxf_soundfield_group_link_id[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0e,0x01,0x03,0x07,0x01,0x06,0x00,0x00,0x00 };
363 static const uint8_t mxf_mca_rfc5646_spoken_language[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x0d,0x03,0x01,0x01,0x02,0x03,0x15,0x00,0x00 };
364 
365 static const uint8_t mxf_sub_descriptor[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x04,0x06,0x10,0x00,0x00 };
366 
368 static const uint8_t mxf_mastering_display_uls[4][16] = {
373 };
374 
375 #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
376 
377 static void mxf_free_metadataset(MXFMetadataSet **ctx, int freectx)
378 {
380  switch ((*ctx)->type) {
381  case Descriptor:
382  case MultipleDescriptor:
383  av_freep(&((MXFDescriptor *)*ctx)->extradata);
384  av_freep(&((MXFDescriptor *)*ctx)->mastering);
385  av_freep(&((MXFDescriptor *)*ctx)->coll);
386  av_freep(&((MXFDescriptor *)*ctx)->file_descriptors_refs);
387  av_freep(&((MXFDescriptor *)*ctx)->sub_descriptors_refs);
388  break;
389  case FFV1SubDescriptor:
390  av_freep(&((MXFFFV1SubDescriptor *)*ctx)->extradata);
391  break;
396  av_freep(&((MXFMCASubDescriptor *)*ctx)->group_of_soundfield_groups_link_id_refs);
397  break;
398  case Sequence:
399  av_freep(&((MXFSequence *)*ctx)->structural_components_refs);
400  break;
401  case EssenceGroup:
402  av_freep(&((MXFEssenceGroup *)*ctx)->structural_components_refs);
403  break;
404  case SourcePackage:
405  case MaterialPackage:
406  av_freep(&((MXFPackage *)*ctx)->tracks_refs);
407  av_freep(&((MXFPackage *)*ctx)->name);
408  av_freep(&((MXFPackage *)*ctx)->comment_refs);
409  break;
410  case TaggedValue:
411  av_freep(&((MXFTaggedValue *)*ctx)->name);
412  av_freep(&((MXFTaggedValue *)*ctx)->value);
413  break;
414  case Track:
415  av_freep(&((MXFTrack *)*ctx)->name);
416  break;
417  case IndexTableSegment:
418  seg = (MXFIndexTableSegment *)*ctx;
420  av_freep(&seg->flag_entries);
422  default:
423  break;
424  }
425  if (freectx) {
426  av_freep(ctx);
427  }
428 }
429 
431 {
432  uint64_t size = avio_r8(pb);
433  if (size & 0x80) { /* long form */
434  int bytes_num = size & 0x7f;
435  /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
436  if (bytes_num > 8)
437  return AVERROR_INVALIDDATA;
438  size = 0;
439  while (bytes_num--)
440  size = size << 8 | avio_r8(pb);
441  }
442  if (size > INT64_MAX)
443  return AVERROR_INVALIDDATA;
444  return size;
445 }
446 
447 static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
448 {
449  int i, b;
450  for (i = 0; i < size && !avio_feof(pb); i++) {
451  b = avio_r8(pb);
452  if (b == key[0])
453  i = 0;
454  else if (b != key[i])
455  i = -1;
456  }
457  return i == size;
458 }
459 
460 static int klv_read_packet(MXFContext *mxf, KLVPacket *klv, AVIOContext *pb)
461 {
462  int64_t length, pos;
463  if (!mxf_read_sync(pb, mxf_klv_key, 4))
464  return AVERROR_INVALIDDATA;
465  klv->offset = avio_tell(pb) - 4;
466  if (klv->offset < mxf->run_in)
467  return AVERROR_INVALIDDATA;
468 
469  memcpy(klv->key, mxf_klv_key, 4);
470  avio_read(pb, klv->key + 4, 12);
471  length = klv_decode_ber_length(pb);
472  if (length < 0)
473  return length;
474  klv->length = length;
475  pos = avio_tell(pb);
476  if (pos > INT64_MAX - length)
477  return AVERROR_INVALIDDATA;
478  klv->next_klv = pos + length;
479  return 0;
480 }
481 
482 static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv, int body_sid)
483 {
484  int i;
485 
486  for (i = 0; i < s->nb_streams; i++) {
487  MXFTrack *track = s->streams[i]->priv_data;
488  /* SMPTE 379M 7.3 */
489  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)))
490  return i;
491  }
492  /* return 0 if only one stream, for OP Atom files with 0 as track number */
493  return s->nb_streams == 1 && s->streams[0]->priv_data ? 0 : -1;
494 }
495 
497 {
498  // we look for partition where the offset is placed
499  int a, b, m;
500  int64_t pack_ofs;
501 
502  a = -1;
503  b = mxf->partitions_count;
504 
505  while (b - a > 1) {
506  m = (a + b) >> 1;
507  pack_ofs = mxf->partitions[m].pack_ofs;
508  if (pack_ofs <= offset)
509  a = m;
510  else
511  b = m;
512  }
513 
514  if (a == -1)
515  return 0;
516  return mxf->partitions[a].body_sid;
517 }
518 
519 static int mxf_get_eia608_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt, int64_t length)
520 {
521  int count = avio_rb16(s->pb);
522  int cdp_identifier, cdp_length, cdp_footer_id, ccdata_id, cc_count;
523  int line_num, sample_coding, sample_count;
524  int did, sdid, data_length;
525  int i, ret;
526 
527  if (count > 1)
528  av_log(s, AV_LOG_WARNING, "unsupported multiple ANC packets (%d) per KLV packet\n", count);
529 
530  for (i = 0; i < count; i++) {
531  if (length < 6) {
532  av_log(s, AV_LOG_ERROR, "error reading s436m packet %"PRId64"\n", length);
533  return AVERROR_INVALIDDATA;
534  }
535  line_num = avio_rb16(s->pb);
536  avio_r8(s->pb); // wrapping type
537  sample_coding = avio_r8(s->pb);
538  sample_count = avio_rb16(s->pb);
539  length -= 6 + 8 + sample_count;
540  if (line_num != 9 && line_num != 11)
541  continue;
542  if (sample_coding == 7 || sample_coding == 8 || sample_coding == 9) {
543  av_log(s, AV_LOG_WARNING, "unsupported s436m 10 bit sample coding\n");
544  continue;
545  }
546  if (length < 0)
547  return AVERROR_INVALIDDATA;
548 
549  avio_rb32(s->pb); // array count
550  avio_rb32(s->pb); // array elem size
551  did = avio_r8(s->pb);
552  sdid = avio_r8(s->pb);
553  data_length = avio_r8(s->pb);
554  if (did != 0x61 || sdid != 1) {
555  av_log(s, AV_LOG_WARNING, "unsupported did or sdid: %x %x\n", did, sdid);
556  continue;
557  }
558  cdp_identifier = avio_rb16(s->pb); // cdp id
559  if (cdp_identifier != 0x9669) {
560  av_log(s, AV_LOG_ERROR, "wrong cdp identifier %x\n", cdp_identifier);
561  return AVERROR_INVALIDDATA;
562  }
563  cdp_length = avio_r8(s->pb);
564  avio_r8(s->pb); // cdp_frame_rate
565  avio_r8(s->pb); // cdp_flags
566  avio_rb16(s->pb); // cdp_hdr_sequence_cntr
567  ccdata_id = avio_r8(s->pb); // ccdata_id
568  if (ccdata_id != 0x72) {
569  av_log(s, AV_LOG_ERROR, "wrong cdp data section %x\n", ccdata_id);
570  return AVERROR_INVALIDDATA;
571  }
572  cc_count = avio_r8(s->pb) & 0x1f;
573  ret = av_get_packet(s->pb, pkt, cc_count * 3);
574  if (ret < 0)
575  return ret;
576  if (cdp_length - 9 - 4 < cc_count * 3) {
577  av_log(s, AV_LOG_ERROR, "wrong cdp size %d cc count %d\n", cdp_length, cc_count);
578  return AVERROR_INVALIDDATA;
579  }
580  avio_skip(s->pb, data_length - 9 - 4 - cc_count * 3);
581  cdp_footer_id = avio_r8(s->pb);
582  if (cdp_footer_id != 0x74) {
583  av_log(s, AV_LOG_ERROR, "wrong cdp footer section %x\n", cdp_footer_id);
584  return AVERROR_INVALIDDATA;
585  }
586  avio_rb16(s->pb); // cdp_ftr_sequence_cntr
587  avio_r8(s->pb); // packet_checksum
588  break;
589  }
590 
591  return 0;
592 }
593 
594 /* XXX: use AVBitStreamFilter */
595 static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
596 {
597  const uint8_t *buf_ptr, *end_ptr;
598  uint8_t *data_ptr;
599  int i;
600 
601  if (length > 61444) /* worst case PAL 1920 samples 8 channels */
602  return AVERROR_INVALIDDATA;
603  length = av_get_packet(pb, pkt, length);
604  if (length < 0)
605  return length;
606  data_ptr = pkt->data;
607  end_ptr = pkt->data + length;
608  buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
609 
610  if (st->codecpar->ch_layout.nb_channels > 8)
611  return AVERROR_INVALIDDATA;
612 
613  for (; end_ptr - buf_ptr >= st->codecpar->ch_layout.nb_channels * 4; ) {
614  for (i = 0; i < st->codecpar->ch_layout.nb_channels; i++) {
615  uint32_t sample = bytestream_get_le32(&buf_ptr);
616  if (st->codecpar->bits_per_coded_sample == 24)
617  bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
618  else
619  bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
620  }
621  // always 8 channels stored SMPTE 331M
622  buf_ptr += 32 - st->codecpar->ch_layout.nb_channels * 4;
623  }
624  av_shrink_packet(pkt, data_ptr - pkt->data);
625  return 0;
626 }
627 
629 {
630  static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
631  MXFContext *mxf = s->priv_data;
632  AVIOContext *pb = s->pb;
633  int64_t end = avio_tell(pb) + klv->length;
634  int64_t size;
635  uint64_t orig_size;
636  uint64_t plaintext_size;
637  uint8_t ivec[16];
638  uint8_t tmpbuf[16];
639  int index;
640  int body_sid;
641 
642  if (!mxf->aesc && s->key && s->keylen == 16) {
643  mxf->aesc = av_aes_alloc();
644  if (!mxf->aesc)
645  return AVERROR(ENOMEM);
646  av_aes_init(mxf->aesc, s->key, 128, 1);
647  }
648  // crypto context
650  if (size < 0)
651  return size;
652  avio_skip(pb, size);
653  // plaintext offset
655  plaintext_size = avio_rb64(pb);
656  // source klv key
658  avio_read(pb, klv->key, 16);
660  return AVERROR_INVALIDDATA;
661 
662  body_sid = find_body_sid_by_absolute_offset(mxf, klv->offset);
663  index = mxf_get_stream_index(s, klv, body_sid);
664  if (index < 0)
665  return AVERROR_INVALIDDATA;
666  // source size
668  orig_size = avio_rb64(pb);
669  if (orig_size < plaintext_size)
670  return AVERROR_INVALIDDATA;
671  // enc. code
673  if (size < 32 || size - 32 < orig_size || (int)orig_size != orig_size)
674  return AVERROR_INVALIDDATA;
675  avio_read(pb, ivec, 16);
676  avio_read(pb, tmpbuf, 16);
677  if (mxf->aesc)
678  av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
679  if (memcmp(tmpbuf, checkv, 16))
680  av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
681  size -= 32;
682  size = av_get_packet(pb, pkt, size);
683  if (size < 0)
684  return size;
685  else if (size < plaintext_size)
686  return AVERROR_INVALIDDATA;
687  size -= plaintext_size;
688  if (mxf->aesc)
689  av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
690  &pkt->data[plaintext_size], size >> 4, ivec, 1);
691  av_shrink_packet(pkt, orig_size);
693  avio_skip(pb, end - avio_tell(pb));
694  return 0;
695 }
696 
697 static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
698 {
699  MXFContext *mxf = arg;
700  int item_num = avio_rb32(pb);
701  int item_len = avio_rb32(pb);
702 
703  if (item_len != 18) {
704  avpriv_request_sample(pb, "Primer pack item length %d", item_len);
705  return AVERROR_PATCHWELCOME;
706  }
707  if (item_num > 65536 || item_num < 0) {
708  av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num);
709  return AVERROR_INVALIDDATA;
710  }
711  if (mxf->local_tags)
712  av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n");
713  av_free(mxf->local_tags);
714  mxf->local_tags_count = 0;
715  mxf->local_tags = av_calloc(item_num, item_len);
716  if (!mxf->local_tags)
717  return AVERROR(ENOMEM);
718  mxf->local_tags_count = item_num;
719  avio_read(pb, mxf->local_tags, item_num*item_len);
720  return 0;
721 }
722 
723 static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
724 {
725  MXFContext *mxf = arg;
726  AVFormatContext *s = mxf->fc;
727  MXFPartition *partition, *tmp_part;
728  UID op;
729  uint64_t footer_partition;
730  uint32_t nb_essence_containers;
731  uint64_t this_partition;
732 
733  if (mxf->partitions_count >= INT_MAX / 2)
734  return AVERROR_INVALIDDATA;
735 
736  av_assert0(klv_offset >= mxf->run_in);
737 
738  tmp_part = av_realloc_array(mxf->partitions, mxf->partitions_count + 1, sizeof(*mxf->partitions));
739  if (!tmp_part)
740  return AVERROR(ENOMEM);
741  mxf->partitions = tmp_part;
742 
743  if (mxf->parsing_backward) {
744  /* insert the new partition pack in the middle
745  * this makes the entries in mxf->partitions sorted by offset */
746  memmove(&mxf->partitions[mxf->last_forward_partition+1],
748  (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
749  partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
750  } else {
751  mxf->last_forward_partition++;
752  partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
753  }
754 
755  memset(partition, 0, sizeof(*partition));
756  mxf->partitions_count++;
757  partition->pack_length = avio_tell(pb) - klv_offset + size;
758  partition->pack_ofs = klv_offset;
759 
760  switch(uid[13]) {
761  case 2:
762  partition->type = Header;
763  break;
764  case 3:
765  partition->type = BodyPartition;
766  break;
767  case 4:
768  partition->type = Footer;
769  break;
770  default:
771  av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
772  return AVERROR_INVALIDDATA;
773  }
774 
775  /* consider both footers to be closed (there is only Footer and CompleteFooter) */
776  partition->closed = partition->type == Footer || !(uid[14] & 1);
777  partition->complete = uid[14] > 2;
778  avio_skip(pb, 4);
779  partition->kag_size = avio_rb32(pb);
780  this_partition = avio_rb64(pb);
781  if (this_partition != klv_offset - mxf->run_in) {
782  av_log(mxf->fc, AV_LOG_ERROR,
783  "this_partition %"PRId64" mismatches %"PRId64"\n",
784  this_partition, klv_offset - mxf->run_in);
785  return AVERROR_INVALIDDATA;
786  }
787  partition->previous_partition = avio_rb64(pb);
788  footer_partition = avio_rb64(pb);
789  partition->header_byte_count = avio_rb64(pb);
790  partition->index_byte_count = avio_rb64(pb);
791  partition->index_sid = avio_rb32(pb);
792  partition->body_offset = avio_rb64(pb);
793  partition->body_sid = avio_rb32(pb);
794  if (avio_read(pb, op, sizeof(UID)) != sizeof(UID)) {
795  av_log(mxf->fc, AV_LOG_ERROR, "Failed reading UID\n");
796  return AVERROR_INVALIDDATA;
797  }
798  nb_essence_containers = avio_rb32(pb);
799 
800  if (partition->type == Header) {
801  char str[36];
802  snprintf(str, sizeof(str), "%08x.%08x.%08x.%08x", AV_RB32(&op[0]), AV_RB32(&op[4]), AV_RB32(&op[8]), AV_RB32(&op[12]));
803  av_dict_set(&s->metadata, "operational_pattern_ul", str, 0);
804  }
805 
806  if (this_partition &&
807  partition->previous_partition == this_partition) {
808  av_log(mxf->fc, AV_LOG_ERROR,
809  "PreviousPartition equal to ThisPartition %"PRIx64"\n",
810  partition->previous_partition);
811  /* override with the actual previous partition offset */
812  if (!mxf->parsing_backward && mxf->last_forward_partition > 1) {
813  MXFPartition *prev =
814  mxf->partitions + mxf->last_forward_partition - 2;
815  partition->previous_partition = prev->pack_ofs - mxf->run_in;
816  }
817  /* if no previous body partition are found point to the header
818  * partition */
819  if (partition->previous_partition == this_partition)
820  partition->previous_partition = 0;
821  av_log(mxf->fc, AV_LOG_ERROR,
822  "Overriding PreviousPartition with %"PRIx64"\n",
823  partition->previous_partition);
824  }
825 
826  /* some files don't have FooterPartition set in every partition */
827  if (footer_partition) {
828  if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
829  av_log(mxf->fc, AV_LOG_ERROR,
830  "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",
831  mxf->footer_partition, footer_partition);
832  } else {
833  mxf->footer_partition = footer_partition;
834  }
835  }
836 
837  av_log(mxf->fc, AV_LOG_TRACE,
838  "PartitionPack: ThisPartition = 0x%"PRIX64
839  ", PreviousPartition = 0x%"PRIX64", "
840  "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",
841  this_partition,
842  partition->previous_partition, footer_partition,
843  partition->index_sid, partition->body_sid);
844 
845  /* sanity check PreviousPartition if set */
846  //NOTE: this isn't actually enough, see mxf_seek_to_previous_partition()
847  if (partition->previous_partition &&
848  mxf->run_in + partition->previous_partition >= klv_offset) {
849  av_log(mxf->fc, AV_LOG_ERROR,
850  "PreviousPartition points to this partition or forward\n");
851  return AVERROR_INVALIDDATA;
852  }
853 
854  if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
855  else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
856  else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
857  else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
858  else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
859  else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
860  else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
861  else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
862  else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
863  else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
864  else if (op[12] == 0x10) {
865  /* SMPTE 390m: "There shall be exactly one essence container"
866  * The following block deals with files that violate this, namely:
867  * 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a
868  * abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */
869  if (nb_essence_containers != 1) {
870  MXFOP op = nb_essence_containers ? OP1a : OPAtom;
871 
872  /* only nag once */
873  if (!mxf->op)
874  av_log(mxf->fc, AV_LOG_WARNING,
875  "\"OPAtom\" with %"PRIu32" ECs - assuming %s\n",
876  nb_essence_containers,
877  op == OP1a ? "OP1a" : "OPAtom");
878 
879  mxf->op = op;
880  } else
881  mxf->op = OPAtom;
882  } else {
883  av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
884  mxf->op = OP1a;
885  }
886 
887  if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
888  av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %"PRId32" - guessing ",
889  partition->kag_size);
890 
891  if (mxf->op == OPSONYOpt)
892  partition->kag_size = 512;
893  else
894  partition->kag_size = 1;
895 
896  av_log(mxf->fc, AV_LOG_WARNING, "%"PRId32"\n", partition->kag_size);
897  }
898 
899  return 0;
900 }
901 
902 static uint64_t partition_score(MXFPartition *p)
903 {
904  uint64_t score;
905  if (!p)
906  return 0;
907  if (p->type == Footer)
908  score = 5;
909  else if (p->complete)
910  score = 4;
911  else if (p->closed)
912  score = 3;
913  else
914  score = 1;
915  return (score << 60) | ((uint64_t)p->pack_ofs >> 4);
916 }
917 
918 static int mxf_add_metadata_set(MXFContext *mxf, MXFMetadataSet **metadata_set)
919 {
921  enum MXFMetadataSetType type = (*metadata_set)->type;
922 
923  // Index Table is special because it might be added manually without
924  // partition and we iterate thorugh all instances of them. Also some files
925  // use the same Instance UID for different index tables...
926  if (type != IndexTableSegment) {
927  for (int i = 0; i < mxf->metadata_sets_count; i++) {
928  if (!memcmp((*metadata_set)->uid, mxf->metadata_sets[i]->uid, 16) && type == mxf->metadata_sets[i]->type) {
929  uint64_t old_s = mxf->metadata_sets[i]->partition_score;
930  uint64_t new_s = (*metadata_set)->partition_score;
931  if (old_s > new_s) {
932  mxf_free_metadataset(metadata_set, 1);
933  return 0;
934  }
935  }
936  }
937  }
938  tmp = av_realloc_array(mxf->metadata_sets, mxf->metadata_sets_count + 1, sizeof(*mxf->metadata_sets));
939  if (!tmp) {
940  mxf_free_metadataset(metadata_set, 1);
941  return AVERROR(ENOMEM);
942  }
943  mxf->metadata_sets = tmp;
944  mxf->metadata_sets[mxf->metadata_sets_count] = *metadata_set;
945  mxf->metadata_sets_count++;
946  return 0;
947 }
948 
949 static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
950 {
951  MXFCryptoContext *cryptocontext = arg;
952  if (size != 16)
953  return AVERROR_INVALIDDATA;
955  avio_read(pb, cryptocontext->source_container_ul, 16);
956  return 0;
957 }
958 
959 static int mxf_read_strong_ref_array(AVIOContext *pb, UID **refs, int *count)
960 {
961  int64_t ret;
962  unsigned c = avio_rb32(pb);
963 
964  //avio_read() used int
965  if (c > INT_MAX / sizeof(UID))
966  return AVERROR_PATCHWELCOME;
967  *count = c;
968 
969  av_free(*refs);
970  *refs = av_malloc_array(*count, sizeof(UID));
971  if (!*refs) {
972  *count = 0;
973  return AVERROR(ENOMEM);
974  }
975  avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
976  ret = avio_read(pb, (uint8_t *)*refs, *count * sizeof(UID));
977  if (ret != *count * sizeof(UID)) {
978  *count = ret < 0 ? 0 : ret / sizeof(UID);
979  return ret < 0 ? ret : AVERROR_INVALIDDATA;
980  }
981 
982  return 0;
983 }
984 
985 static inline int mxf_read_us_ascii_string(AVIOContext *pb, int size, char** str)
986 {
987  int ret;
988  size_t buf_size;
989 
990  if (size < 0 || size > INT_MAX - 1)
991  return AVERROR(EINVAL);
992 
993  buf_size = size + 1;
994  av_free(*str);
995  *str = av_malloc(buf_size);
996  if (!*str)
997  return AVERROR(ENOMEM);
998 
999  ret = avio_get_str(pb, size, *str, buf_size);
1000 
1001  if (ret < 0) {
1002  av_freep(str);
1003  return ret;
1004  }
1005 
1006  return ret;
1007 }
1008 
1009 static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, int be)
1010 {
1011  int ret;
1012  size_t buf_size;
1013 
1014  if (size < 0 || size > INT_MAX/2)
1015  return AVERROR(EINVAL);
1016 
1017  buf_size = size + size / 2 + 1;
1018  av_free(*str);
1019  *str = av_malloc(buf_size);
1020  if (!*str)
1021  return AVERROR(ENOMEM);
1022 
1023  if (be)
1024  ret = avio_get_str16be(pb, size, *str, buf_size);
1025  else
1026  ret = avio_get_str16le(pb, size, *str, buf_size);
1027 
1028  if (ret < 0) {
1029  av_freep(str);
1030  return ret;
1031  }
1032 
1033  return ret;
1034 }
1035 
1036 #define READ_STR16(type, big_endian) \
1037 static int mxf_read_utf16 ## type ##_string(AVIOContext *pb, int size, char** str) \
1038 { \
1039 return mxf_read_utf16_string(pb, size, str, big_endian); \
1040 }
1041 READ_STR16(be, 1)
1042 READ_STR16(le, 0)
1043 #undef READ_STR16
1044 
1045 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1046 {
1047  MXFContext *mxf = arg;
1048  switch (tag) {
1049  case 0x1901:
1050  if (mxf->packages_refs)
1051  av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple packages_refs\n");
1052  return mxf_read_strong_ref_array(pb, &mxf->packages_refs, &mxf->packages_count);
1053  case 0x1902:
1055  }
1056  return 0;
1057 }
1058 
1059 static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1060 {
1061  MXFStructuralComponent *source_clip = arg;
1062  switch(tag) {
1063  case 0x0202:
1064  source_clip->duration = avio_rb64(pb);
1065  break;
1066  case 0x1201:
1067  source_clip->start_position = avio_rb64(pb);
1068  break;
1069  case 0x1101:
1070  /* UMID, only get last 16 bytes */
1071  avio_read(pb, source_clip->source_package_ul, 16);
1072  avio_read(pb, source_clip->source_package_uid, 16);
1073  break;
1074  case 0x1102:
1075  source_clip->source_track_id = avio_rb32(pb);
1076  break;
1077  }
1078  return 0;
1079 }
1080 
1081 static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1082 {
1083  MXFTimecodeComponent *mxf_timecode = arg;
1084  switch(tag) {
1085  case 0x1501:
1086  mxf_timecode->start_frame = avio_rb64(pb);
1087  break;
1088  case 0x1502:
1089  mxf_timecode->rate = (AVRational){avio_rb16(pb), 1};
1090  break;
1091  case 0x1503:
1092  mxf_timecode->drop_frame = avio_r8(pb);
1093  break;
1094  }
1095  return 0;
1096 }
1097 
1098 static int mxf_read_pulldown_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1099 {
1100  MXFPulldownComponent *mxf_pulldown = arg;
1101  switch(tag) {
1102  case 0x0d01:
1103  avio_read(pb, mxf_pulldown->input_segment_ref, 16);
1104  break;
1105  }
1106  return 0;
1107 }
1108 
1109 static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1110 {
1111  MXFTrack *track = arg;
1112  switch(tag) {
1113  case 0x4801:
1114  track->track_id = avio_rb32(pb);
1115  break;
1116  case 0x4804:
1117  avio_read(pb, track->track_number, 4);
1118  break;
1119  case 0x4802:
1120  mxf_read_utf16be_string(pb, size, &track->name);
1121  break;
1122  case 0x4b01:
1123  track->edit_rate.num = avio_rb32(pb);
1124  track->edit_rate.den = avio_rb32(pb);
1125  break;
1126  case 0x4803:
1127  avio_read(pb, track->sequence_ref, 16);
1128  break;
1129  }
1130  return 0;
1131 }
1132 
1133 static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1134 {
1135  MXFSequence *sequence = arg;
1136  switch(tag) {
1137  case 0x0202:
1138  sequence->duration = avio_rb64(pb);
1139  break;
1140  case 0x0201:
1141  avio_read(pb, sequence->data_definition_ul, 16);
1142  break;
1143  case 0x4b02:
1144  sequence->origin = avio_r8(pb);
1145  break;
1146  case 0x1001:
1148  &sequence->structural_components_count);
1149  }
1150  return 0;
1151 }
1152 
1153 static int mxf_read_essence_group(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1154 {
1155  MXFEssenceGroup *essence_group = arg;
1156  switch (tag) {
1157  case 0x0202:
1158  essence_group->duration = avio_rb64(pb);
1159  break;
1160  case 0x0501:
1161  return mxf_read_strong_ref_array(pb, &essence_group->structural_components_refs,
1162  &essence_group->structural_components_count);
1163  }
1164  return 0;
1165 }
1166 
1167 static int mxf_read_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1168 {
1169  MXFPackage *package = arg;
1170  switch(tag) {
1171  case 0x4403:
1172  return mxf_read_strong_ref_array(pb, &package->tracks_refs,
1173  &package->tracks_count);
1174  case 0x4401:
1175  /* UMID */
1176  avio_read(pb, package->package_ul, 16);
1177  avio_read(pb, package->package_uid, 16);
1178  break;
1179  case 0x4701:
1180  avio_read(pb, package->descriptor_ref, 16);
1181  break;
1182  case 0x4402:
1183  return mxf_read_utf16be_string(pb, size, &package->name);
1184  case 0x4406:
1185  return mxf_read_strong_ref_array(pb, &package->comment_refs,
1186  &package->comment_count);
1187  }
1188  return 0;
1189 }
1190 
1191 static int mxf_read_essence_container_data(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1192 {
1193  MXFEssenceContainerData *essence_data = arg;
1194  switch(tag) {
1195  case 0x2701:
1196  /* linked package umid UMID */
1197  avio_read(pb, essence_data->package_ul, 16);
1198  avio_read(pb, essence_data->package_uid, 16);
1199  break;
1200  case 0x3f06:
1201  essence_data->index_sid = avio_rb32(pb);
1202  break;
1203  case 0x3f07:
1204  essence_data->body_sid = avio_rb32(pb);
1205  break;
1206  }
1207  return 0;
1208 }
1209 
1211 {
1212  int i, length;
1213  uint32_t nb_index_entries;
1214 
1215  if (segment->temporal_offset_entries)
1216  return AVERROR_INVALIDDATA;
1217 
1218  nb_index_entries = avio_rb32(pb);
1219  if (nb_index_entries > INT_MAX)
1220  return AVERROR_INVALIDDATA;
1221  segment->nb_index_entries = nb_index_entries;
1222 
1223  length = avio_rb32(pb);
1224  if(segment->nb_index_entries && length < 11)
1225  return AVERROR_INVALIDDATA;
1226 
1227  if (!FF_ALLOC_TYPED_ARRAY(segment->temporal_offset_entries, segment->nb_index_entries) ||
1228  !FF_ALLOC_TYPED_ARRAY(segment->flag_entries , segment->nb_index_entries) ||
1229  !FF_ALLOC_TYPED_ARRAY(segment->stream_offset_entries , segment->nb_index_entries)) {
1230  av_freep(&segment->temporal_offset_entries);
1231  av_freep(&segment->flag_entries);
1232  return AVERROR(ENOMEM);
1233  }
1234 
1235  for (i = 0; i < segment->nb_index_entries; i++) {
1236  if(avio_feof(pb))
1237  return AVERROR_INVALIDDATA;
1238  segment->temporal_offset_entries[i] = avio_r8(pb);
1239  avio_r8(pb); /* KeyFrameOffset */
1240  segment->flag_entries[i] = avio_r8(pb);
1241  segment->stream_offset_entries[i] = avio_rb64(pb);
1242  avio_skip(pb, length - 11);
1243  }
1244  return 0;
1245 }
1246 
1247 static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1248 {
1250  switch(tag) {
1251  case 0x3F05:
1252  segment->edit_unit_byte_count = avio_rb32(pb);
1253  av_log(NULL, AV_LOG_TRACE, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
1254  break;
1255  case 0x3F06:
1256  segment->index_sid = avio_rb32(pb);
1257  av_log(NULL, AV_LOG_TRACE, "IndexSID %d\n", segment->index_sid);
1258  break;
1259  case 0x3F07:
1260  segment->body_sid = avio_rb32(pb);
1261  av_log(NULL, AV_LOG_TRACE, "BodySID %d\n", segment->body_sid);
1262  break;
1263  case 0x3F0A:
1264  av_log(NULL, AV_LOG_TRACE, "IndexEntryArray found\n");
1265  return mxf_read_index_entry_array(pb, segment);
1266  case 0x3F0B:
1267  segment->index_edit_rate.num = avio_rb32(pb);
1268  segment->index_edit_rate.den = avio_rb32(pb);
1269  av_log(NULL, AV_LOG_TRACE, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
1270  segment->index_edit_rate.den);
1271  break;
1272  case 0x3F0C:
1273  segment->index_start_position = avio_rb64(pb);
1274  av_log(NULL, AV_LOG_TRACE, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
1275  break;
1276  case 0x3F0D:
1277  segment->index_duration = avio_rb64(pb);
1278  av_log(NULL, AV_LOG_TRACE, "IndexDuration %"PRId64"\n", segment->index_duration);
1279  break;
1280  }
1281  return 0;
1282 }
1283 
1284 static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
1285 {
1286  int code, value, ofs = 0;
1287  char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */
1288 
1289  do {
1290  code = avio_r8(pb);
1291  value = avio_r8(pb);
1292  av_log(NULL, AV_LOG_TRACE, "pixel layout: code %#x\n", code);
1293 
1294  if (ofs <= 14) {
1295  layout[ofs++] = code;
1296  layout[ofs++] = value;
1297  } else
1298  break; /* don't read byte by byte on sneaky files filled with lots of non-zeroes */
1299  } while (code != 0); /* SMPTE 377M E.2.46 */
1300 
1301  ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
1302 }
1303 
1304 static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1305 {
1306  MXFDescriptor *descriptor = arg;
1307  int entry_count, entry_size;
1308 
1309  switch(tag) {
1310  case 0x3F01:
1311  return mxf_read_strong_ref_array(pb, &descriptor->file_descriptors_refs,
1312  &descriptor->file_descriptors_count);
1313  case 0x3002: /* ContainerDuration */
1314  descriptor->duration = avio_rb64(pb);
1315  break;
1316  case 0x3004:
1317  avio_read(pb, descriptor->essence_container_ul, 16);
1318  break;
1319  case 0x3005:
1320  avio_read(pb, descriptor->codec_ul, 16);
1321  break;
1322  case 0x3006:
1323  descriptor->linked_track_id = avio_rb32(pb);
1324  break;
1325  case 0x3201: /* PictureEssenceCoding */
1326  avio_read(pb, descriptor->essence_codec_ul, 16);
1327  break;
1328  case 0x3203:
1329  descriptor->width = avio_rb32(pb);
1330  break;
1331  case 0x3202:
1332  descriptor->height = avio_rb32(pb);
1333  break;
1334  case 0x320C:
1335  descriptor->frame_layout = avio_r8(pb);
1336  break;
1337  case 0x320D:
1338  entry_count = avio_rb32(pb);
1339  entry_size = avio_rb32(pb);
1340  if (entry_size == 4) {
1341  if (entry_count > 0)
1342  descriptor->video_line_map[0] = avio_rb32(pb);
1343  else
1344  descriptor->video_line_map[0] = 0;
1345  if (entry_count > 1)
1346  descriptor->video_line_map[1] = avio_rb32(pb);
1347  else
1348  descriptor->video_line_map[1] = 0;
1349  } else
1350  av_log(NULL, AV_LOG_WARNING, "VideoLineMap element size %d currently not supported\n", entry_size);
1351  break;
1352  case 0x320E:
1353  descriptor->aspect_ratio.num = avio_rb32(pb);
1354  descriptor->aspect_ratio.den = avio_rb32(pb);
1355  break;
1356  case 0x3210:
1357  avio_read(pb, descriptor->color_trc_ul, 16);
1358  break;
1359  case 0x3212:
1360  descriptor->field_dominance = avio_r8(pb);
1361  break;
1362  case 0x3219:
1363  avio_read(pb, descriptor->color_primaries_ul, 16);
1364  break;
1365  case 0x321A:
1366  avio_read(pb, descriptor->color_space_ul, 16);
1367  break;
1368  case 0x3301:
1369  descriptor->component_depth = avio_rb32(pb);
1370  break;
1371  case 0x3302:
1372  descriptor->horiz_subsampling = avio_rb32(pb);
1373  break;
1374  case 0x3304:
1375  descriptor->black_ref_level = avio_rb32(pb);
1376  break;
1377  case 0x3305:
1378  descriptor->white_ref_level = avio_rb32(pb);
1379  break;
1380  case 0x3306:
1381  descriptor->color_range = avio_rb32(pb);
1382  break;
1383  case 0x3308:
1384  descriptor->vert_subsampling = avio_rb32(pb);
1385  break;
1386  case 0x3D03:
1387  descriptor->sample_rate.num = avio_rb32(pb);
1388  descriptor->sample_rate.den = avio_rb32(pb);
1389  break;
1390  case 0x3D06: /* SoundEssenceCompression */
1391  avio_read(pb, descriptor->essence_codec_ul, 16);
1392  break;
1393  case 0x3D07:
1394  descriptor->channels = avio_rb32(pb);
1395  break;
1396  case 0x3D01:
1397  descriptor->bits_per_sample = avio_rb32(pb);
1398  break;
1399  case 0x3401:
1400  mxf_read_pixel_layout(pb, descriptor);
1401  break;
1402  default:
1403  /* Private uid used by SONY C0023S01.mxf */
1405  if (descriptor->extradata)
1406  av_log(NULL, AV_LOG_WARNING, "Duplicate sony_mpeg4_extradata\n");
1407  av_free(descriptor->extradata);
1408  descriptor->extradata_size = 0;
1409  descriptor->extradata = av_malloc(size);
1410  if (!descriptor->extradata)
1411  return AVERROR(ENOMEM);
1412  descriptor->extradata_size = size;
1413  avio_read(pb, descriptor->extradata, size);
1414  }
1415  if (IS_KLV_KEY(uid, mxf_jp2k_rsiz)) {
1416  uint32_t rsiz = avio_rb16(pb);
1417  if (rsiz == AV_PROFILE_JPEG2000_DCINEMA_2K ||
1419  descriptor->pix_fmt = AV_PIX_FMT_XYZ12;
1420  }
1422  if (!descriptor->mastering) {
1424  if (!descriptor->mastering)
1425  return AVERROR(ENOMEM);
1426  }
1428  for (int i = 0; i < 3; i++) {
1429  /* Order: large x, large y, other (i.e. RGB) */
1432  }
1433  /* Check we have seen mxf_mastering_display_white_point_chromaticity */
1434  if (descriptor->mastering->white_point[0].den != 0)
1435  descriptor->mastering->has_primaries = 1;
1436  }
1440  /* Check we have seen mxf_mastering_display_primaries */
1441  if (descriptor->mastering->display_primaries[0][0].den != 0)
1442  descriptor->mastering->has_primaries = 1;
1443  }
1446  /* Check we have seen mxf_mastering_display_minimum_luminance */
1447  if (descriptor->mastering->min_luminance.den != 0)
1448  descriptor->mastering->has_luminance = 1;
1449  }
1452  /* Check we have seen mxf_mastering_display_maximum_luminance */
1453  if (descriptor->mastering->max_luminance.den != 0)
1454  descriptor->mastering->has_luminance = 1;
1455  }
1456  }
1458  if (!descriptor->coll) {
1459  descriptor->coll = av_content_light_metadata_alloc(&descriptor->coll_size);
1460  if (!descriptor->coll)
1461  return AVERROR(ENOMEM);
1462  }
1464  descriptor->coll->MaxCLL = avio_rb16(pb);
1465  }
1467  descriptor->coll->MaxFALL = avio_rb16(pb);
1468  }
1469  }
1470 
1472  return mxf_read_strong_ref_array(pb, &descriptor->sub_descriptors_refs, &descriptor->sub_descriptors_count);
1473 
1474  break;
1475  }
1476  return 0;
1477 }
1478 
1479 static int mxf_read_mca_sub_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1480 {
1481  MXFMCASubDescriptor *mca_sub_descriptor = arg;
1482 
1484  avio_read(pb, mca_sub_descriptor->mca_label_dictionary_id, 16);
1485 
1487  avio_read(pb, mca_sub_descriptor->mca_link_id, 16);
1488 
1490  avio_read(pb, mca_sub_descriptor->soundfield_group_link_id, 16);
1491 
1494 
1496  mca_sub_descriptor->mca_channel_id = avio_rb32(pb);
1497 
1499  return mxf_read_us_ascii_string(pb, size, &mca_sub_descriptor->language);
1500 
1501  return 0;
1502 }
1503 
1504 static int mxf_read_ffv1_sub_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1505 {
1506  MXFFFV1SubDescriptor *ffv1_sub_descriptor = arg;
1507 
1509  if (ffv1_sub_descriptor->extradata)
1510  av_log(NULL, AV_LOG_WARNING, "Duplicate ffv1_extradata\n");
1511  av_free(ffv1_sub_descriptor->extradata);
1512  ffv1_sub_descriptor->extradata_size = 0;
1513  ffv1_sub_descriptor->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
1514  if (!ffv1_sub_descriptor->extradata)
1515  return AVERROR(ENOMEM);
1516  ffv1_sub_descriptor->extradata_size = size;
1517  avio_read(pb, ffv1_sub_descriptor->extradata, size);
1518  }
1519 
1520  return 0;
1521 }
1522 
1523 static int mxf_read_indirect_value(void *arg, AVIOContext *pb, int size)
1524 {
1525  MXFTaggedValue *tagged_value = arg;
1526  uint8_t key[17];
1527 
1528  if (size <= 17)
1529  return 0;
1530 
1531  avio_read(pb, key, 17);
1532  /* TODO: handle other types of of indirect values */
1533  if (memcmp(key, mxf_indirect_value_utf16le, 17) == 0) {
1534  return mxf_read_utf16le_string(pb, size - 17, &tagged_value->value);
1535  } else if (memcmp(key, mxf_indirect_value_utf16be, 17) == 0) {
1536  return mxf_read_utf16be_string(pb, size - 17, &tagged_value->value);
1537  }
1538  return 0;
1539 }
1540 
1541 static int mxf_read_tagged_value(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
1542 {
1543  MXFTaggedValue *tagged_value = arg;
1544  switch (tag){
1545  case 0x5001:
1546  return mxf_read_utf16be_string(pb, size, &tagged_value->name);
1547  case 0x5003:
1548  return mxf_read_indirect_value(tagged_value, pb, size);
1549  }
1550  return 0;
1551 }
1552 
1553 /*
1554  * Match an uid independently of the version byte and up to len common bytes
1555  * Returns: boolean
1556  */
1557 static int mxf_match_uid(const UID key, const uint8_t uid_prefix[], int len)
1558 {
1559  int i;
1560  for (i = 0; i < len; i++) {
1561  if (i != 7 && key[i] != uid_prefix[i])
1562  return 0;
1563  }
1564  return 1;
1565 }
1566 
1567 static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
1568 {
1569  while (uls->uid[0]) {
1570  if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
1571  break;
1572  uls++;
1573  }
1574  return uls;
1575 }
1576 
1577 static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
1578 {
1579  int i;
1580 
1581  if (!strong_ref)
1582  return NULL;
1583  for (i = mxf->metadata_sets_count - 1; i >= 0; i--) {
1584  if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
1585  (type == AnyType || mxf->metadata_sets[i]->type == type)) {
1586  return mxf->metadata_sets[i];
1587  }
1588  }
1589  return NULL;
1590 }
1591 
1593  // video essence container uls
1594  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000, NULL, 14, J2KWrap },
1595  { { 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 */
1596  { { 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 */
1597  { { 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 */
1598  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x14,0x01,0x00 }, 14, AV_CODEC_ID_TIFF, NULL, 14 }, /* TIFF */
1599  { { 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 */
1600  { { 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 */
1601  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x1c,0x01,0x00 }, 14, AV_CODEC_ID_PRORES, NULL, 14 }, /* ProRes */
1602  { { 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 */
1603  { { 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 */
1604  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x0d,0x01,0x03,0x01,0x02,0x23,0x01,0x00 }, 14, AV_CODEC_ID_FFV1, NULL, 14 },
1605  { { 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 */
1606  { { 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 */
1607  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x01,0x01 }, 15, AV_CODEC_ID_HQ_HQA },
1608  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x02,0x01 }, 15, AV_CODEC_ID_HQX },
1609  { { 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 */
1610  { { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4f }, 14, AV_CODEC_ID_RAWVIDEO }, /* Legacy ?? Uncompressed Picture */
1611  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1612 };
1613 
1614 /* EC ULs for intra-only formats */
1616  { { 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 */
1617  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1618 };
1619 
1620 /* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */
1622  { { 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 */
1623  { { 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 */
1624  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1625 };
1626 
1627 /* actual coded width for AVC-Intra to allow selecting correct SPS/PPS */
1629  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 16, 1440 },
1630  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 16, 1440 },
1631  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 16, 1440 },
1632  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 16, 1440 },
1633  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, 0 },
1634 };
1635 
1637  // sound essence container uls
1638  { { 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 */
1639  { { 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 */
1640  { { 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 */
1641  { { 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 */
1642  { { 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) */
1643  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x0d,0x01,0x03,0x01,0x02,0x16,0x00,0x00 }, 14, AV_CODEC_ID_AAC, NULL, 14 }, /* AAC ADIF (SMPTE 381-4) */
1644  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x0d,0x01,0x03,0x01,0x02,0x17,0x00,0x00 }, 14, AV_CODEC_ID_AAC, NULL, 14 }, /* AAC ADTS (SMPTE 381-4) */
1645  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x0d,0x01,0x03,0x01,0x02,0x18,0x00,0x00 }, 14, AV_CODEC_ID_AAC, NULL, 14 }, /* AAC LATM/LOAS (SMPTE 381-4) */
1646  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1647 };
1648 
1650  { { 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 },
1651  { { 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 },
1652  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x13,0x01,0x01 }, 16, AV_CODEC_ID_TTML },
1653  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
1654 };
1655 
1656 typedef struct MXFChannelOrderingUL {
1658  uint64_t layout_mask;
1661 
1663  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x01,0x00,0x00,0x00,0x00 }, AV_CH_FRONT_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left
1664  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x02,0x00,0x00,0x00,0x00 }, AV_CH_FRONT_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right
1665  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x03,0x00,0x00,0x00,0x00 }, AV_CH_FRONT_CENTER, AV_AUDIO_SERVICE_TYPE_MAIN }, // Center
1666  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x04,0x00,0x00,0x00,0x00 }, AV_CH_LOW_FREQUENCY, AV_AUDIO_SERVICE_TYPE_MAIN }, // Low Frequency Effects
1667  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x05,0x00,0x00,0x00,0x00 }, AV_CH_SIDE_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Surround
1668  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x06,0x00,0x00,0x00,0x00 }, AV_CH_SIDE_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Surround
1669  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x07,0x00,0x00,0x00,0x00 }, AV_CH_SIDE_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Side Surround
1670  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x08,0x00,0x00,0x00,0x00 }, AV_CH_SIDE_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Side Surround
1671  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x09,0x00,0x00,0x00,0x00 }, AV_CH_BACK_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Rear Surround
1672  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x0a,0x00,0x00,0x00,0x00 }, AV_CH_BACK_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Rear Surround
1673  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x0b,0x00,0x00,0x00,0x00 }, AV_CH_FRONT_LEFT_OF_CENTER, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Center
1674  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x0c,0x00,0x00,0x00,0x00 }, AV_CH_FRONT_RIGHT_OF_CENTER, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Center
1675  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x0d,0x00,0x00,0x00,0x00 }, AV_CH_BACK_CENTER, AV_AUDIO_SERVICE_TYPE_MAIN }, // Center Surround
1676  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x0e,0x00,0x00,0x00,0x00 }, AV_CH_FRONT_CENTER, AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED }, // Hearing impaired audio channel
1677  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x0f,0x00,0x00,0x00,0x00 }, AV_CH_FRONT_CENTER, AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED }, // Visually impaired narrative audio channel
1678  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x20,0x03,0x00,0x00,0x00 }, AV_CH_STEREO_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Total
1679  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x20,0x04,0x00,0x00,0x00 }, AV_CH_STEREO_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Total
1680  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x01,0x00,0x00 }, AV_CH_TOP_FRONT_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Height
1681  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x02,0x00,0x00 }, AV_CH_TOP_FRONT_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Height
1682  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x03,0x00,0x00 }, AV_CH_TOP_FRONT_CENTER, AV_AUDIO_SERVICE_TYPE_MAIN }, // Center Height
1683  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x04,0x00,0x00 }, AV_CH_TOP_SIDE_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Surround Height
1684  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x05,0x00,0x00 }, AV_CH_TOP_SIDE_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Surround Height
1685  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x06,0x00,0x00 }, AV_CH_TOP_SIDE_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Side Surround Height
1686  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x07,0x00,0x00 }, AV_CH_TOP_SIDE_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Side Surround Height
1687  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x08,0x00,0x00 }, AV_CH_TOP_BACK_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Rear Surround Height
1688  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x09,0x00,0x00 }, AV_CH_TOP_BACK_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Rear Surround Height
1689  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x0a,0x00,0x00 }, AV_CH_TOP_SIDE_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Top Surround
1690  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x0b,0x00,0x00 }, AV_CH_TOP_SIDE_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Top Surround
1691  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x0c,0x00,0x00 }, AV_CH_TOP_CENTER, AV_AUDIO_SERVICE_TYPE_MAIN }, // Top Surround
1692  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x0d,0x00,0x00 }, AV_CH_LOW_FREQUENCY, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Front Subwoofer
1693  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x0e,0x00,0x00 }, AV_CH_LOW_FREQUENCY_2, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Front Subwoofer
1694  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x0f,0x00,0x00 }, AV_CH_TOP_BACK_CENTER, AV_AUDIO_SERVICE_TYPE_MAIN }, // Center Rear Height
1695  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x10,0x00,0x00 }, AV_CH_BACK_CENTER, AV_AUDIO_SERVICE_TYPE_MAIN }, // Center Rear
1696  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x11,0x00,0x00 }, AV_CH_BOTTOM_FRONT_LEFT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Left Below
1697  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x12,0x00,0x00 }, AV_CH_BOTTOM_FRONT_RIGHT, AV_AUDIO_SERVICE_TYPE_MAIN }, // Right Below
1698  { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0d,0x03,0x02,0x01,0x30,0x01,0x13,0x00,0x00 }, AV_CH_BOTTOM_FRONT_CENTER, AV_AUDIO_SERVICE_TYPE_MAIN }, // Center Below
1699  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_AUDIO_SERVICE_TYPE_NB },
1700 };
1701 
1702 static MXFWrappingScheme mxf_get_wrapping_kind(UID *essence_container_ul)
1703 {
1704  int val;
1705  const MXFCodecUL *codec_ul;
1706 
1708  if (!codec_ul->uid[0])
1710  if (!codec_ul->uid[0])
1711  codec_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul);
1712  if (!codec_ul->uid[0] || !codec_ul->wrapping_indicator_pos)
1713  return UnknownWrapped;
1714 
1715  val = (*essence_container_ul)[codec_ul->wrapping_indicator_pos];
1716  switch (codec_ul->wrapping_indicator_type) {
1717  case RawVWrap:
1718  val = val % 4;
1719  break;
1720  case RawAWrap:
1721  if (val == 0x03 || val == 0x04)
1722  val -= 0x02;
1723  break;
1724  case D10D11Wrap:
1725  if (val == 0x02)
1726  val = 0x01;
1727  break;
1728  case J2KWrap:
1729  if (val != 0x02)
1730  val = 0x01;
1731  break;
1732  }
1733  if (val == 0x01)
1734  return FrameWrapped;
1735  if (val == 0x02)
1736  return ClipWrapped;
1737  return UnknownWrapped;
1738 }
1739 
1740 static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
1741 {
1742  int i, j, nb_segments = 0;
1743  MXFIndexTableSegment **unsorted_segments;
1744  int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
1745 
1746  /* count number of segments, allocate arrays and copy unsorted segments */
1747  for (i = 0; i < mxf->metadata_sets_count; i++)
1748  if (mxf->metadata_sets[i]->type == IndexTableSegment)
1749  nb_segments++;
1750 
1751  if (!nb_segments)
1752  return AVERROR_INVALIDDATA;
1753 
1754  if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
1755  !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
1756  av_freep(sorted_segments);
1757  av_free(unsorted_segments);
1758  return AVERROR(ENOMEM);
1759  }
1760 
1761  for (i = nb_segments = 0; i < mxf->metadata_sets_count; i++) {
1762  if (mxf->metadata_sets[i]->type == IndexTableSegment) {
1764  if (s->edit_unit_byte_count || s->nb_index_entries)
1765  unsorted_segments[nb_segments++] = s;
1766  else
1767  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
1768  s->index_sid, s->index_start_position);
1769  }
1770  }
1771 
1772  if (!nb_segments) {
1773  av_freep(sorted_segments);
1774  av_free(unsorted_segments);
1775  return AVERROR_INVALIDDATA;
1776  }
1777 
1778  *nb_sorted_segments = 0;
1779 
1780  /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
1781  for (i = 0; i < nb_segments; i++) {
1782  int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
1783  uint64_t best_index_duration = 0;
1784 
1785  for (j = 0; j < nb_segments; j++) {
1786  MXFIndexTableSegment *s = unsorted_segments[j];
1787 
1788  /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
1789  * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
1790  * If we come across an entry with the same IndexStartPosition but larger IndexDuration, then we'll prefer it over the one we currently have.
1791  */
1792  if ((i == 0 ||
1793  s->body_sid > last_body_sid ||
1794  s->body_sid == last_body_sid && s->index_sid > last_index_sid ||
1795  s->body_sid == last_body_sid && s->index_sid == last_index_sid && s->index_start_position > last_index_start) &&
1796  (best == -1 ||
1797  s->body_sid < best_body_sid ||
1798  s->body_sid == best_body_sid && s->index_sid < best_index_sid ||
1799  s->body_sid == best_body_sid && s->index_sid == best_index_sid && s->index_start_position < best_index_start ||
1800  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)) {
1801  best = j;
1802  best_body_sid = s->body_sid;
1803  best_index_sid = s->index_sid;
1804  best_index_start = s->index_start_position;
1805  best_index_duration = s->index_duration;
1806  }
1807  }
1808 
1809  /* no suitable entry found -> we're done */
1810  if (best == -1)
1811  break;
1812 
1813  (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
1814  last_body_sid = best_body_sid;
1815  last_index_sid = best_index_sid;
1816  last_index_start = best_index_start;
1817  }
1818 
1819  av_free(unsorted_segments);
1820 
1821  return 0;
1822 }
1823 
1824 /**
1825  * Computes the absolute file offset of the given essence container offset
1826  */
1827 static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out, MXFPartition **partition_out)
1828 {
1829  MXFPartition *last_p = NULL;
1830  int a, b, m, m0;
1831 
1832  if (offset < 0)
1833  return AVERROR(EINVAL);
1834 
1835  a = -1;
1836  b = mxf->partitions_count;
1837 
1838  while (b - a > 1) {
1839  m0 = m = (a + b) >> 1;
1840 
1841  while (m < b && mxf->partitions[m].body_sid != body_sid)
1842  m++;
1843 
1844  if (m < b && mxf->partitions[m].body_offset <= offset)
1845  a = m;
1846  else
1847  b = m0;
1848  }
1849 
1850  if (a >= 0)
1851  last_p = &mxf->partitions[a];
1852 
1853  if (last_p && (!last_p->essence_length || last_p->essence_length > (offset - last_p->body_offset))) {
1854  *offset_out = last_p->essence_offset + (offset - last_p->body_offset);
1855  if (partition_out)
1856  *partition_out = last_p;
1857  return 0;
1858  }
1859 
1860  av_log(mxf->fc, AV_LOG_ERROR,
1861  "failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n",
1862  offset, body_sid);
1863 
1864  return AVERROR_INVALIDDATA;
1865 }
1866 
1867 /**
1868  * Returns the end position of the essence container with given BodySID, or zero if unknown
1869  */
1870 static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
1871 {
1872  for (int x = mxf->partitions_count - 1; x >= 0; x--) {
1873  MXFPartition *p = &mxf->partitions[x];
1874 
1875  if (p->body_sid != body_sid)
1876  continue;
1877 
1878  if (!p->essence_length)
1879  return 0;
1880 
1881  return p->essence_offset + p->essence_length;
1882  }
1883 
1884  return 0;
1885 }
1886 
1887 /* EditUnit -> absolute offset */
1888 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)
1889 {
1890  int i;
1891  int64_t offset_temp = 0;
1892 
1893  edit_unit = av_rescale_q(edit_unit, index_table->segments[0]->index_edit_rate, edit_rate);
1894 
1895  for (i = 0; i < index_table->nb_segments; i++) {
1896  MXFIndexTableSegment *s = index_table->segments[i];
1897 
1898  edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */
1899 
1900  if (edit_unit < s->index_start_position + s->index_duration) {
1901  int64_t index = edit_unit - s->index_start_position;
1902 
1903  if (s->edit_unit_byte_count)
1904  offset_temp += s->edit_unit_byte_count * index;
1905  else {
1906  if (s->nb_index_entries == 2 * s->index_duration + 1)
1907  index *= 2; /* Avid index */
1908 
1909  if (index < 0 || index >= s->nb_index_entries) {
1910  av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
1911  index_table->index_sid, s->index_start_position);
1912  return AVERROR_INVALIDDATA;
1913  }
1914 
1915  offset_temp = s->stream_offset_entries[index];
1916  }
1917 
1918  if (edit_unit_out)
1919  *edit_unit_out = av_rescale_q(edit_unit, edit_rate, s->index_edit_rate);
1920 
1921  return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out, partition_out);
1922  } else {
1923  /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
1924  offset_temp += s->edit_unit_byte_count * s->index_duration;
1925  }
1926  }
1927 
1928  if (nag)
1929  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);
1930 
1931  return AVERROR_INVALIDDATA;
1932 }
1933 
1935 {
1936  int i, j, x;
1937  int8_t max_temporal_offset = -128;
1938  uint8_t *flags;
1939 
1940  /* first compute how many entries we have */
1941  for (i = 0; i < index_table->nb_segments; i++) {
1942  MXFIndexTableSegment *s = index_table->segments[i];
1943 
1944  if (!s->nb_index_entries) {
1945  index_table->nb_ptses = 0;
1946  return 0; /* no TemporalOffsets */
1947  }
1948 
1949  if (s->index_duration > INT_MAX - index_table->nb_ptses) {
1950  index_table->nb_ptses = 0;
1951  av_log(mxf->fc, AV_LOG_ERROR, "ignoring IndexSID %d, duration is too large\n", s->index_sid);
1952  return 0;
1953  }
1954 
1955  if (s->nb_index_entries != s->index_duration &&
1956  s->nb_index_entries != s->index_duration + 1 && /* Avid index */
1957  s->nb_index_entries != s->index_duration * 2 + 1) {
1958  index_table->nb_ptses = 0;
1959  av_log(mxf->fc, AV_LOG_ERROR, "ignoring IndexSID %d, duration does not match nb_index_entries\n", s->index_sid);
1960  return 0;
1961  }
1962 
1963  index_table->nb_ptses += s->index_duration;
1964  }
1965 
1966  /* paranoid check */
1967  if (index_table->nb_ptses <= 0)
1968  return 0;
1969 
1970  if (!(index_table->ptses = av_malloc_array(index_table->nb_ptses, sizeof(int64_t))) ||
1971  !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry))) ||
1972  !(index_table->offsets = av_malloc_array(index_table->nb_ptses, sizeof(int8_t))) ||
1973  !(flags = av_malloc_array(index_table->nb_ptses, sizeof(uint8_t)))) {
1974  av_freep(&index_table->ptses);
1975  av_freep(&index_table->fake_index);
1976  av_freep(&index_table->offsets);
1977  return AVERROR(ENOMEM);
1978  }
1979 
1980  /* we may have a few bad TemporalOffsets
1981  * make sure the corresponding PTSes don't have the bogus value 0 */
1982  for (x = 0; x < index_table->nb_ptses; x++)
1983  index_table->ptses[x] = AV_NOPTS_VALUE;
1984 
1985  /**
1986  * We have this:
1987  *
1988  * x TemporalOffset
1989  * 0: 0
1990  * 1: 1
1991  * 2: 1
1992  * 3: -2
1993  * 4: 1
1994  * 5: 1
1995  * 6: -2
1996  *
1997  * We want to transform it into this:
1998  *
1999  * x DTS PTS
2000  * 0: -1 0
2001  * 1: 0 3
2002  * 2: 1 1
2003  * 3: 2 2
2004  * 4: 3 6
2005  * 5: 4 4
2006  * 6: 5 5
2007  *
2008  * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
2009  * then settings ffstream(mxf)->first_dts = -max(TemporalOffset[x]).
2010  * The latter makes DTS <= PTS.
2011  */
2012  for (i = x = 0; i < index_table->nb_segments; i++) {
2013  MXFIndexTableSegment *s = index_table->segments[i];
2014  int index_delta = 1;
2015  int n = s->nb_index_entries;
2016 
2017  if (s->nb_index_entries == 2 * s->index_duration + 1)
2018  index_delta = 2; /* Avid index */
2019  if (s->nb_index_entries == index_delta * s->index_duration + 1)
2020  /* ignore the last entry - it's the size of the essence container in Avid */
2021  n--;
2022 
2023  for (j = 0; j < n; j += index_delta, x++) {
2024  int offset = s->temporal_offset_entries[j] / index_delta;
2025  int index = x + offset;
2026 
2027  if (x >= index_table->nb_ptses) {
2028  av_log(mxf->fc, AV_LOG_ERROR,
2029  "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
2030  s->nb_index_entries, s->index_duration);
2031  break;
2032  }
2033 
2034  flags[x] = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
2035 
2036  if (index < 0 || index >= index_table->nb_ptses) {
2037  av_log(mxf->fc, AV_LOG_ERROR,
2038  "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
2039  x, offset, index);
2040  continue;
2041  }
2042 
2043  index_table->offsets[x] = offset;
2044  index_table->ptses[index] = x;
2045  max_temporal_offset = FFMAX(max_temporal_offset, offset);
2046  }
2047  }
2048 
2049  /* calculate the fake index table in display order */
2050  for (x = 0; x < index_table->nb_ptses; x++) {
2051  index_table->fake_index[x].timestamp = x;
2052  if (index_table->ptses[x] != AV_NOPTS_VALUE)
2053  index_table->fake_index[index_table->ptses[x]].flags = flags[x];
2054  }
2055  av_freep(&flags);
2056 
2057  index_table->first_dts = -max_temporal_offset;
2058 
2059  return 0;
2060 }
2061 
2062 /**
2063  * Sorts and collects index table segments into index tables.
2064  * Also computes PTSes if possible.
2065  */
2067 {
2068  int i, j, k, ret, nb_sorted_segments;
2069  MXFIndexTableSegment **sorted_segments = NULL;
2070 
2071  if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
2072  nb_sorted_segments <= 0) {
2073  av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
2074  return 0;
2075  }
2076 
2077  /* sanity check and count unique BodySIDs/IndexSIDs */
2078  for (i = 0; i < nb_sorted_segments; i++) {
2079  if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
2080  mxf->nb_index_tables++;
2081  else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
2082  av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
2084  goto finish_decoding_index;
2085  }
2086  }
2087 
2089  sizeof(*mxf->index_tables));
2090  if (!mxf->index_tables) {
2091  av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
2092  ret = AVERROR(ENOMEM);
2093  goto finish_decoding_index;
2094  }
2095 
2096  /* distribute sorted segments to index tables */
2097  for (i = j = 0; i < nb_sorted_segments; i++) {
2098  if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
2099  /* next IndexSID */
2100  j++;
2101  }
2102 
2103  mxf->index_tables[j].nb_segments++;
2104  }
2105 
2106  for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
2107  MXFIndexTable *t = &mxf->index_tables[j];
2108  MXFTrack *mxf_track = NULL;
2109 
2110  t->segments = av_calloc(t->nb_segments, sizeof(*t->segments));
2111  if (!t->segments) {
2112  av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment"
2113  " pointer array\n");
2114  ret = AVERROR(ENOMEM);
2115  goto finish_decoding_index;
2116  }
2117 
2118  if (sorted_segments[i]->index_start_position)
2119  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
2120  sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
2121 
2122  memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
2123  t->index_sid = sorted_segments[i]->index_sid;
2124  t->body_sid = sorted_segments[i]->body_sid;
2125 
2126  if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
2127  goto finish_decoding_index;
2128 
2129  for (k = 0; k < mxf->fc->nb_streams; k++) {
2130  MXFTrack *track = mxf->fc->streams[k]->priv_data;
2131  if (track && track->index_sid == t->index_sid) {
2132  mxf_track = track;
2133  break;
2134  }
2135  }
2136 
2137  /* fix zero IndexDurations */
2138  for (k = 0; k < t->nb_segments; k++) {
2139  if (!t->segments[k]->index_edit_rate.num || !t->segments[k]->index_edit_rate.den) {
2140  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has invalid IndexEditRate\n",
2141  t->index_sid, k);
2142  if (mxf_track)
2143  t->segments[k]->index_edit_rate = mxf_track->edit_rate;
2144  }
2145 
2146  if (t->segments[k]->index_duration)
2147  continue;
2148 
2149  if (t->nb_segments > 1)
2150  av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
2151  t->index_sid, k);
2152 
2153  if (!mxf_track) {
2154  av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
2155  break;
2156  }
2157 
2158  /* assume the first stream's duration is reasonable
2159  * leave index_duration = 0 on further segments in case we have any (unlikely)
2160  */
2161  t->segments[k]->index_duration = mxf_track->original_duration;
2162  break;
2163  }
2164  }
2165 
2166  ret = 0;
2167 finish_decoding_index:
2168  av_free(sorted_segments);
2169  return ret;
2170 }
2171 
2172 static int mxf_is_st_422(const UID *essence_container_ul) {
2173  static const uint8_t st_422_essence_container_ul[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c };
2174 
2175  return essence_container_ul && mxf_match_uid(*essence_container_ul, st_422_essence_container_ul,
2176  sizeof(st_422_essence_container_ul));
2177 }
2178 
2179 static int mxf_is_intra_only(MXFDescriptor *descriptor)
2180 {
2182  &descriptor->essence_container_ul)->id != AV_CODEC_ID_NONE ||
2184  &descriptor->essence_codec_ul)->id != AV_CODEC_ID_NONE;
2185 }
2186 
2187 static void mxf_umid_to_str(const UID ul, const UID uid,
2188  char str[2 + sizeof(UID) * 4 + 1])
2189 {
2190  snprintf(str, 2 + sizeof(UID) * 4 + 1, "0x");
2191  ff_data_to_hex(str + 2, ul, sizeof(UID), 0);
2192  ff_data_to_hex(str + 2 + 2 * sizeof(UID), uid, sizeof(UID), 0);
2193 }
2194 
2195 static int mxf_version_to_str(uint16_t major, uint16_t minor, uint16_t tertiary,
2196  uint16_t patch, uint16_t release, char **str)
2197 {
2198  *str = av_asprintf("%d.%d.%d.%d.%d", major, minor, tertiary, patch, release);
2199  if (!*str)
2200  return AVERROR(ENOMEM);
2201  return 0;
2202 }
2203 
2204 static int mxf_add_umid_metadata(AVDictionary **pm, const char *key, MXFPackage* package)
2205 {
2206  char str[2 + 4 * sizeof(UID) + 1];
2207  if (!package)
2208  return 0;
2209  mxf_umid_to_str(package->package_ul, package->package_uid, str);
2210  av_dict_set(pm, key, str, 0);
2211  return 0;
2212 }
2213 
2214 static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
2215 {
2216  char buf[AV_TIMECODE_STR_SIZE];
2217  av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0);
2218 
2219  return 0;
2220 }
2221 
2223 {
2224  MXFStructuralComponent *component = NULL;
2225  MXFPulldownComponent *pulldown = NULL;
2226 
2227  component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
2228  if (!component)
2229  return NULL;
2230 
2231  switch (component->meta.type) {
2232  case TimecodeComponent:
2233  return (MXFTimecodeComponent*)component;
2234  case PulldownComponent: /* timcode component may be located on a pulldown component */
2235  pulldown = (MXFPulldownComponent*)component;
2237  default:
2238  break;
2239  }
2240  return NULL;
2241 }
2242 
2243 static MXFPackage* mxf_resolve_source_package(MXFContext *mxf, UID package_ul, UID package_uid)
2244 {
2245  MXFPackage *package = NULL;
2246  int i;
2247 
2248  for (i = 0; i < mxf->packages_count; i++) {
2249  package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], SourcePackage);
2250  if (!package)
2251  continue;
2252 
2253  if (!memcmp(package->package_ul, package_ul, 16) && !memcmp(package->package_uid, package_uid, 16))
2254  return package;
2255  }
2256  return NULL;
2257 }
2258 
2259 static MXFDescriptor* mxf_resolve_descriptor(MXFContext *mxf, UID *strong_ref, int track_id)
2260 {
2261  MXFDescriptor *descriptor = mxf_resolve_strong_ref(mxf, strong_ref, Descriptor);
2262  if (descriptor)
2263  return descriptor;
2264 
2265  descriptor = mxf_resolve_strong_ref(mxf, strong_ref, MultipleDescriptor);
2266  if (descriptor) {
2267  for (int i = 0; i < descriptor->file_descriptors_count; i++) {
2268  MXFDescriptor *file_descriptor = mxf_resolve_strong_ref(mxf, &descriptor->file_descriptors_refs[i], Descriptor);
2269 
2270  if (!file_descriptor) {
2271  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve file descriptor strong ref\n");
2272  continue;
2273  }
2274  if (file_descriptor->linked_track_id == track_id) {
2275  return file_descriptor;
2276  }
2277  }
2278  }
2279 
2280  return NULL;
2281 }
2282 
2284 {
2285  MXFStructuralComponent *component = NULL;
2286  MXFPackage *package = NULL;
2287  MXFDescriptor *descriptor = NULL;
2288  int i;
2289 
2290  if (!essence_group || !essence_group->structural_components_count)
2291  return NULL;
2292 
2293  /* essence groups contains multiple representations of the same media,
2294  this return the first components with a valid Descriptor typically index 0 */
2295  for (i =0; i < essence_group->structural_components_count; i++){
2296  component = mxf_resolve_strong_ref(mxf, &essence_group->structural_components_refs[i], SourceClip);
2297  if (!component)
2298  continue;
2299 
2300  if (!(package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid)))
2301  continue;
2302 
2303  descriptor = mxf_resolve_strong_ref(mxf, &package->descriptor_ref, Descriptor);
2304  if (descriptor)
2305  return component;
2306  }
2307  return NULL;
2308 }
2309 
2311 {
2312  MXFStructuralComponent *component = NULL;
2313 
2314  component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
2315  if (!component)
2316  return NULL;
2317  switch (component->meta.type) {
2318  case SourceClip:
2319  return component;
2320  case EssenceGroup:
2321  return mxf_resolve_essence_group_choice(mxf, (MXFEssenceGroup*) component);
2322  default:
2323  break;
2324  }
2325  return NULL;
2326 }
2327 
2329 {
2331  int i;
2332  char *key = NULL;
2333 
2334  for (i = 0; i < package->comment_count; i++) {
2335  tag = mxf_resolve_strong_ref(mxf, &package->comment_refs[i], TaggedValue);
2336  if (!tag || !tag->name || !tag->value)
2337  continue;
2338 
2339  key = av_asprintf("comment_%s", tag->name);
2340  if (!key)
2341  return AVERROR(ENOMEM);
2342 
2344  }
2345  return 0;
2346 }
2347 
2349 {
2350  MXFPackage *physical_package = NULL;
2351  MXFTrack *physical_track = NULL;
2352  MXFStructuralComponent *sourceclip = NULL;
2353  MXFTimecodeComponent *mxf_tc = NULL;
2354  int i, j, k;
2355  AVTimecode tc;
2356  int flags;
2357  int64_t start_position;
2358 
2359  for (i = 0; i < source_track->sequence->structural_components_count; i++) {
2360  sourceclip = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip);
2361  if (!sourceclip)
2362  continue;
2363 
2364  if (!(physical_package = mxf_resolve_source_package(mxf, sourceclip->source_package_ul, sourceclip->source_package_uid)))
2365  break;
2366 
2367  mxf_add_umid_metadata(&st->metadata, "reel_umid", physical_package);
2368 
2369  /* the name of physical source package is name of the reel or tape */
2370  if (physical_package->name && physical_package->name[0])
2371  av_dict_set(&st->metadata, "reel_name", physical_package->name, 0);
2372 
2373  /* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track
2374  * to the start_frame of the timecode component located on one of the tracks of the physical source package.
2375  */
2376  for (j = 0; j < physical_package->tracks_count; j++) {
2377  if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) {
2378  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
2379  continue;
2380  }
2381 
2382  if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) {
2383  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
2384  continue;
2385  }
2386 
2387  if (physical_track->edit_rate.num <= 0 ||
2388  physical_track->edit_rate.den <= 0) {
2389  av_log(mxf->fc, AV_LOG_WARNING,
2390  "Invalid edit rate (%d/%d) found on structural"
2391  " component #%d, defaulting to 25/1\n",
2392  physical_track->edit_rate.num,
2393  physical_track->edit_rate.den, i);
2394  physical_track->edit_rate = (AVRational){25, 1};
2395  }
2396 
2397  for (k = 0; k < physical_track->sequence->structural_components_count; k++) {
2398  if (!(mxf_tc = mxf_resolve_timecode_component(mxf, &physical_track->sequence->structural_components_refs[k])))
2399  continue;
2400 
2401  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
2402  /* scale sourceclip start_position to match physical track edit rate */
2403  start_position = av_rescale_q(sourceclip->start_position,
2404  physical_track->edit_rate,
2405  source_track->edit_rate);
2406 
2407  if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) {
2408  mxf_add_timecode_metadata(&st->metadata, "timecode", &tc);
2409  return 0;
2410  }
2411  }
2412  }
2413  }
2414 
2415  return 0;
2416 }
2417 
2419 {
2420  MXFStructuralComponent *component = NULL;
2421  const MXFCodecUL *codec_ul = NULL;
2422  MXFPackage tmp_package;
2423  AVStream *st;
2424  int j;
2425 
2426  for (j = 0; j < track->sequence->structural_components_count; j++) {
2427  component = mxf_resolve_sourceclip(mxf, &track->sequence->structural_components_refs[j]);
2428  if (!component)
2429  continue;
2430  break;
2431  }
2432  if (!component)
2433  return 0;
2434 
2435  st = avformat_new_stream(mxf->fc, NULL);
2436  if (!st) {
2437  av_log(mxf->fc, AV_LOG_ERROR, "could not allocate metadata stream\n");
2438  return AVERROR(ENOMEM);
2439  }
2440 
2443  st->id = track->track_id;
2444 
2445  memcpy(&tmp_package.package_ul, component->source_package_ul, 16);
2446  memcpy(&tmp_package.package_uid, component->source_package_uid, 16);
2447  mxf_add_umid_metadata(&st->metadata, "file_package_umid", &tmp_package);
2448  if (track->name && track->name[0])
2449  av_dict_set(&st->metadata, "track_name", track->name, 0);
2450 
2452  av_dict_set(&st->metadata, "data_type", av_get_media_type_string(codec_ul->id), 0);
2453  return 0;
2454 }
2455 
2457 {
2458  if (descriptor->black_ref_level || descriptor->white_ref_level || descriptor->color_range) {
2459  /* CDCI range metadata */
2460  if (!descriptor->component_depth)
2461  return AVCOL_RANGE_UNSPECIFIED;
2462  if (descriptor->black_ref_level == 0 && descriptor->component_depth < 31 &&
2463  descriptor->white_ref_level == ((1<<descriptor->component_depth) - 1) &&
2464  (descriptor->color_range == (1<<descriptor->component_depth) ||
2465  descriptor->color_range == ((1<<descriptor->component_depth) - 1)))
2466  return AVCOL_RANGE_JPEG;
2467  if (descriptor->component_depth >= 8 && descriptor->component_depth < 31 &&
2468  descriptor->black_ref_level == (1 <<(descriptor->component_depth - 4)) &&
2469  descriptor->white_ref_level == (235<<(descriptor->component_depth - 8)) &&
2470  descriptor->color_range == ((14<<(descriptor->component_depth - 4)) + 1))
2471  return AVCOL_RANGE_MPEG;
2472  avpriv_request_sample(mxf->fc, "Unrecognized CDCI color range (color diff range %d, b %d, w %d, depth %d)",
2473  descriptor->color_range, descriptor->black_ref_level,
2474  descriptor->white_ref_level, descriptor->component_depth);
2475  }
2476 
2477  return AVCOL_RANGE_UNSPECIFIED;
2478 }
2479 
2480 static int is_pcm(enum AVCodecID codec_id)
2481 {
2482  /* we only care about "normal" PCM codecs until we get samples */
2484 }
2485 
2486 static int set_language(AVFormatContext *s, const char *rfc5646, AVDictionary **met)
2487 {
2488  // language abbr should contain at least 2 chars
2489  if (rfc5646 && strlen(rfc5646) > 1) {
2490  char primary_tag[4] =
2491  {rfc5646[0], rfc5646[1], rfc5646[2] != '-' ? rfc5646[2] : '\0', '\0'};
2492 
2493  const char *iso6392 = ff_convert_lang_to(primary_tag,
2495  if (iso6392)
2496  return(av_dict_set(met, "language", iso6392, 0));
2497  }
2498  return 0;
2499 }
2500 
2502 {
2503  for (int k = 0; k < mxf->metadata_sets_count; k++) {
2505  if (group->meta.type == type && !memcmp(&group->mca_link_id, mca_link_id, 16))
2506  return group;
2507  }
2508  return NULL;
2509 }
2510 
2511 static void parse_ffv1_sub_descriptor(MXFContext *mxf, MXFTrack *source_track, MXFDescriptor *descriptor, AVStream *st)
2512 {
2513  for (int i = 0; i < descriptor->sub_descriptors_count; i++) {
2514  MXFFFV1SubDescriptor *ffv1_sub_descriptor = mxf_resolve_strong_ref(mxf, &descriptor->sub_descriptors_refs[i], FFV1SubDescriptor);
2515  if (ffv1_sub_descriptor == NULL)
2516  continue;
2517 
2518  descriptor->extradata = ffv1_sub_descriptor->extradata;
2519  descriptor->extradata_size = ffv1_sub_descriptor->extradata_size;
2520  ffv1_sub_descriptor->extradata = NULL;
2521  ffv1_sub_descriptor->extradata_size = 0;
2522  break;
2523  }
2524 }
2525 
2526 static int parse_mca_labels(MXFContext *mxf, MXFTrack *source_track, MXFDescriptor *descriptor, AVStream *st)
2527 {
2528  uint64_t routing[FF_SANE_NB_CHANNELS] = {0};
2529  char *language = NULL;
2530  int ambigous_language = 0;
2531  enum AVAudioServiceType service_type = AV_AUDIO_SERVICE_TYPE_NB;
2532  int ambigous_service_type = 0;
2533  int has_channel_label = 0;
2534 
2535  for (int i = 0; i < descriptor->sub_descriptors_count; i++) {
2536  char *channel_language;
2537 
2539  if (label == NULL)
2540  continue;
2541 
2542  has_channel_label = 1;
2543  for (const MXFChannelOrderingUL* channel_ordering = mxf_channel_ordering; channel_ordering->uid[0]; channel_ordering++) {
2544  if (IS_KLV_KEY(channel_ordering->uid, label->mca_label_dictionary_id)) {
2545  int target_channel = label->mca_channel_id;
2546  if (target_channel == 0 && descriptor->channels == 1)
2547  target_channel = 1;
2548  if (target_channel <= 0 || target_channel > descriptor->channels) {
2549  av_log(mxf->fc, AV_LOG_ERROR, "AudioChannelLabelSubDescriptor has invalid MCA channel ID %d\n", target_channel);
2550  return AVERROR_INVALIDDATA;
2551  }
2552  routing[target_channel - 1] = channel_ordering->layout_mask;
2553  if (service_type == AV_AUDIO_SERVICE_TYPE_NB)
2554  service_type = channel_ordering->service_type;
2555  else if (service_type != channel_ordering->service_type)
2556  ambigous_service_type = 1;
2557  break;
2558  }
2559  }
2560 
2561  channel_language = label->language;
2562  if (!channel_language) {
2564  if (group) {
2565  channel_language = group->language;
2566  if (!channel_language && group->group_of_soundfield_groups_link_id_count) {
2569  if (supergroup)
2570  channel_language = supergroup->language;
2571  }
2572  }
2573  }
2574  if (channel_language) {
2575  if (language && strcmp(language, channel_language))
2576  ambigous_language = 1;
2577  else
2578  language = channel_language;
2579  }
2580  }
2581 
2582  if (language && !ambigous_language) {
2583  int ret = set_language(mxf->fc, language, &st->metadata);
2584  if (ret < 0)
2585  return ret;
2586  }
2587 
2588  if (service_type != AV_AUDIO_SERVICE_TYPE_NB && service_type != AV_AUDIO_SERVICE_TYPE_MAIN && !ambigous_service_type) {
2589  enum AVAudioServiceType *ast;
2593  sizeof(*ast), 0);
2594  if (!side_data)
2595  return AVERROR(ENOMEM);
2596  ast = (enum AVAudioServiceType*)side_data->data;
2597  *ast = service_type;
2598  }
2599 
2600  if (has_channel_label) {
2601  uint64_t channel_layout = 0;
2602  int ret;
2603 
2604  for (int i = 0; i < descriptor->channels; i++) {
2605  if (!routing[i]) {
2606  av_log(mxf->fc, AV_LOG_WARNING, "Designation of audio channel %d in stream #%d is unknown or unsupported, "
2607  "falling back to unknown channel layout\n", st->index, i);
2608  return 0;
2609  }
2610  if (channel_layout & routing[i]) {
2611  char buf[32];
2612  av_channel_name(buf, sizeof(buf), routing[i]);
2613  av_log(mxf->fc, AV_LOG_WARNING, "%s audio channel is used multiple times in stream #%d, "
2614  "falling back to unknown channel layout\n",
2615  buf, st->index);
2616  return 0;
2617  }
2618  if (routing[i] < channel_layout) {
2619  av_log(mxf->fc, AV_LOG_WARNING, "stream #%d is not in in native channel order, "
2620  "falling back to unknown channel layout\n", st->index);
2621  return 0;
2622  }
2623  channel_layout |= routing[i];
2624  }
2625 
2626  av_assert0(descriptor->channels == av_popcount64(channel_layout));
2627 
2628  ret = av_channel_layout_from_mask(&st->codecpar->ch_layout, channel_layout);
2629  if (ret < 0)
2630  return ret;
2631  }
2632 
2633  return 0;
2634 }
2635 
2637 {
2638  MXFPackage *material_package = NULL;
2639  int i, j, k, ret;
2640 
2641  av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count);
2642  /* TODO: handle multiple material packages (OP3x) */
2643  for (i = 0; i < mxf->packages_count; i++) {
2644  material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
2645  if (material_package) break;
2646  }
2647  if (!material_package) {
2648  av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
2649  return AVERROR_INVALIDDATA;
2650  }
2651 
2652  mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package);
2653  if (material_package->name && material_package->name[0])
2654  av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0);
2655  mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package);
2656 
2657  for (i = 0; i < material_package->tracks_count; i++) {
2658  MXFPackage *source_package = NULL;
2659  MXFTrack *material_track = NULL;
2660  MXFTrack *source_track = NULL;
2661  MXFTrack *temp_track = NULL;
2662  MXFDescriptor *descriptor = NULL;
2663  MXFStructuralComponent *component = NULL;
2664  MXFTimecodeComponent *mxf_tc = NULL;
2665  UID *essence_container_ul = NULL;
2666  const MXFCodecUL *codec_ul = NULL;
2667  const MXFCodecUL *container_ul = NULL;
2668  const MXFCodecUL *pix_fmt_ul = NULL;
2669  AVStream *st;
2670  FFStream *sti;
2671  AVTimecode tc;
2672  int flags;
2673 
2674  if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
2675  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
2676  continue;
2677  }
2678 
2679  if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
2680  mxf_tc = (MXFTimecodeComponent*)component;
2681  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
2682  if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
2683  mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
2684  }
2685  }
2686 
2687  if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
2688  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
2689  continue;
2690  }
2691 
2692  for (j = 0; j < material_track->sequence->structural_components_count; j++) {
2693  component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
2694  if (!component)
2695  continue;
2696 
2697  mxf_tc = (MXFTimecodeComponent*)component;
2698  flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
2699  if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
2700  mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
2701  break;
2702  }
2703  }
2704 
2705  /* TODO: handle multiple source clips, only finds first valid source clip */
2706  if(material_track->sequence->structural_components_count > 1)
2707  av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n",
2708  material_track->track_id, material_track->sequence->structural_components_count);
2709 
2710  for (j = 0; j < material_track->sequence->structural_components_count; j++) {
2711  component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]);
2712  if (!component)
2713  continue;
2714 
2715  source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid);
2716  if (!source_package) {
2717  av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id);
2718  continue;
2719  }
2720  for (k = 0; k < source_package->tracks_count; k++) {
2721  if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
2722  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
2724  goto fail_and_free;
2725  }
2726  if (temp_track->track_id == component->source_track_id) {
2727  source_track = temp_track;
2728  break;
2729  }
2730  }
2731  if (!source_track) {
2732  av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
2733  break;
2734  }
2735 
2736  for (k = 0; k < mxf->essence_container_data_count; k++) {
2737  MXFEssenceContainerData *essence_data;
2738 
2739  if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) {
2740  av_log(mxf->fc, AV_LOG_TRACE, "could not resolve essence container data strong ref\n");
2741  continue;
2742  }
2743  if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) {
2744  source_track->body_sid = essence_data->body_sid;
2745  source_track->index_sid = essence_data->index_sid;
2746  break;
2747  }
2748  }
2749 
2750  if(source_track && component)
2751  break;
2752  }
2753  if (!source_track || !component || !source_package) {
2754  if((ret = mxf_add_metadata_stream(mxf, material_track)))
2755  goto fail_and_free;
2756  continue;
2757  }
2758 
2759  if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
2760  av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
2762  goto fail_and_free;
2763  }
2764 
2765  /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
2766  * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
2767  if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
2768  av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
2769  continue;
2770  }
2771 
2772  st = avformat_new_stream(mxf->fc, NULL);
2773  if (!st) {
2774  av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
2775  ret = AVERROR(ENOMEM);
2776  goto fail_and_free;
2777  }
2778  sti = ffstream(st);
2779  st->id = material_track->track_id;
2780  st->priv_data = source_track;
2781 
2782  descriptor = mxf_resolve_descriptor(mxf, &source_package->descriptor_ref, source_track->track_id);
2783 
2784  /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many
2785  * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */
2786  if (descriptor && descriptor->duration != AV_NOPTS_VALUE)
2787  source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration);
2788  else
2789  source_track->original_duration = st->duration = component->duration;
2790 
2791  if (st->duration == -1)
2792  st->duration = AV_NOPTS_VALUE;
2793  st->start_time = component->start_position;
2794  if (material_track->edit_rate.num <= 0 ||
2795  material_track->edit_rate.den <= 0) {
2796  av_log(mxf->fc, AV_LOG_WARNING,
2797  "Invalid edit rate (%d/%d) found on stream #%d, "
2798  "defaulting to 25/1\n",
2799  material_track->edit_rate.num,
2800  material_track->edit_rate.den, st->index);
2801  material_track->edit_rate = (AVRational){25, 1};
2802  }
2803  avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
2804 
2805  /* ensure SourceTrack EditRate == MaterialTrack EditRate since only
2806  * the former is accessible via st->priv_data */
2807  source_track->edit_rate = material_track->edit_rate;
2808 
2809  PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
2811  st->codecpar->codec_type = codec_ul->id;
2812 
2813  if (!descriptor) {
2814  av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
2815  continue;
2816  }
2817  PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
2818  PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
2819  essence_container_ul = &descriptor->essence_container_ul;
2820  source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul);
2821  if (source_track->wrapping == UnknownWrapped)
2822  av_log(mxf->fc, AV_LOG_INFO, "wrapping of stream %d is unknown\n", st->index);
2823  /* HACK: replacing the original key with mxf_encrypted_essence_container
2824  * is not allowed according to s429-6, try to find correct information anyway */
2825  if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
2826  av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
2827  for (k = 0; k < mxf->metadata_sets_count; k++) {
2828  MXFMetadataSet *metadata = mxf->metadata_sets[k];
2829  if (metadata->type == CryptoContext) {
2830  essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
2831  break;
2832  }
2833  }
2834  }
2835 
2836  /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
2838  st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
2839  if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
2841  st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
2842  }
2843 
2844  av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ",
2846  for (k = 0; k < 16; k++) {
2847  av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x",
2848  descriptor->essence_codec_ul[k]);
2849  if (!(k+1 & 19) || k == 5)
2850  av_log(mxf->fc, AV_LOG_VERBOSE, ".");
2851  }
2852  av_log(mxf->fc, AV_LOG_VERBOSE, "\n");
2853 
2854  mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package);
2855  if (source_package->name && source_package->name[0])
2856  av_dict_set(&st->metadata, "file_package_name", source_package->name, 0);
2857  if (material_track->name && material_track->name[0])
2858  av_dict_set(&st->metadata, "track_name", material_track->name, 0);
2859 
2860  mxf_parse_physical_source_package(mxf, source_track, st);
2861 
2862  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2863  source_track->intra_only = mxf_is_intra_only(descriptor);
2865  if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
2866  st->codecpar->codec_id = container_ul->id;
2867  st->codecpar->width = descriptor->width;
2868  st->codecpar->height = descriptor->height; /* Field height, not frame height */
2869  switch (descriptor->frame_layout) {
2870  case FullFrame:
2872  break;
2873  case OneField:
2874  /* Every other line is stored and needs to be duplicated. */
2875  av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n");
2876  break; /* The correct thing to do here is fall through, but by breaking we might be
2877  able to decode some streams at half the vertical resolution, rather than not al all.
2878  It's also for compatibility with the old behavior. */
2879  case MixedFields:
2880  break;
2881  case SegmentedFrame:
2883  case SeparateFields:
2884  av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n",
2885  descriptor->video_line_map[0], descriptor->video_line_map[1],
2886  descriptor->field_dominance);
2887  if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) {
2888  /* Detect coded field order from VideoLineMap:
2889  * (even, even) => bottom field coded first
2890  * (even, odd) => top field coded first
2891  * (odd, even) => top field coded first
2892  * (odd, odd) => bottom field coded first
2893  */
2894  if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) {
2895  switch (descriptor->field_dominance) {
2899  break;
2902  break;
2903  default:
2905  "Field dominance %d support",
2906  descriptor->field_dominance);
2907  }
2908  } else {
2909  switch (descriptor->field_dominance) {
2913  break;
2916  break;
2917  default:
2919  "Field dominance %d support",
2920  descriptor->field_dominance);
2921  }
2922  }
2923  }
2924  /* Turn field height into frame height. */
2925  st->codecpar->height *= 2;
2926  break;
2927  default:
2928  av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout);
2929  }
2930 
2931  if (mxf_is_st_422(essence_container_ul)) {
2932  switch ((*essence_container_ul)[14]) {
2933  case 2: /* Cn: Clip- wrapped Picture Element */
2934  case 3: /* I1: Interlaced Frame, 1 field/KLV */
2935  case 4: /* I2: Interlaced Frame, 2 fields/KLV */
2936  case 6: /* P1: Frame- wrapped Picture Element */
2937  st->avg_frame_rate = source_track->edit_rate;
2938  st->r_frame_rate = st->avg_frame_rate;
2939  break;
2940  case 5: /* F1: Field-wrapped Picture Element */
2941  st->avg_frame_rate = av_mul_q(av_make_q(2, 1), source_track->edit_rate);
2942  st->r_frame_rate = st->avg_frame_rate;
2943  break;
2944  default:
2945  break;
2946  }
2947  }
2948 
2949  if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
2950  switch (descriptor->essence_codec_ul[14]) {
2951  case 1: st->codecpar->codec_tag = MKTAG('a','p','c','o'); break;
2952  case 2: st->codecpar->codec_tag = MKTAG('a','p','c','s'); break;
2953  case 3: st->codecpar->codec_tag = MKTAG('a','p','c','n'); break;
2954  case 4: st->codecpar->codec_tag = MKTAG('a','p','c','h'); break;
2955  case 5: st->codecpar->codec_tag = MKTAG('a','p','4','h'); break;
2956  case 6: st->codecpar->codec_tag = MKTAG('a','p','4','x'); break;
2957  }
2958  }
2959 
2960  if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
2961  st->codecpar->format = descriptor->pix_fmt;
2962  if (st->codecpar->format == AV_PIX_FMT_NONE) {
2964  &descriptor->essence_codec_ul);
2965  st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id;
2966  if (st->codecpar->format== AV_PIX_FMT_NONE) {
2968  &descriptor->essence_codec_ul)->id;
2969  if (!st->codecpar->codec_tag) {
2970  /* support files created before RP224v10 by defaulting to UYVY422
2971  if subsampling is 4:2:2 and component depth is 8-bit */
2972  if (descriptor->horiz_subsampling == 2 &&
2973  descriptor->vert_subsampling == 1 &&
2974  descriptor->component_depth == 8) {
2976  }
2977  }
2978  }
2979  }
2980  }
2982  if (material_track->sequence->origin) {
2983  av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0);
2984  }
2985  if (source_track->sequence->origin) {
2986  av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0);
2987  }
2988  if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den)
2989  sti->display_aspect_ratio = descriptor->aspect_ratio;
2990  st->codecpar->color_range = mxf_get_color_range(mxf, descriptor);
2994  if (descriptor->mastering) {
2997  (uint8_t *)descriptor->mastering, sizeof(*descriptor->mastering), 0)) {
2998  ret = AVERROR(ENOMEM);
2999  goto fail_and_free;
3000  }
3001  descriptor->mastering = NULL;
3002  }
3003  if (descriptor->coll) {
3006  (uint8_t *)descriptor->coll, descriptor->coll_size, 0)) {
3007  ret = AVERROR(ENOMEM);
3008  goto fail_and_free;
3009  }
3010  descriptor->coll = NULL;
3011  }
3012  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3014  /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */
3016  st->codecpar->codec_id = (enum AVCodecID)container_ul->id;
3017  st->codecpar->ch_layout.nb_channels = descriptor->channels;
3018 
3019  if (descriptor->sample_rate.den > 0) {
3020  st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
3021  avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
3022  } else {
3023  av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) "
3024  "found for stream #%d, time base forced to 1/48000\n",
3025  descriptor->sample_rate.num, descriptor->sample_rate.den,
3026  st->index);
3027  avpriv_set_pts_info(st, 64, 1, 48000);
3028  }
3029 
3030  /* if duration is set, rescale it from EditRate to SampleRate */
3031  if (st->duration != AV_NOPTS_VALUE)
3032  st->duration = av_rescale_q(st->duration,
3033  av_inv_q(material_track->edit_rate),
3034  st->time_base);
3035 
3036  /* TODO: implement AV_CODEC_ID_RAWAUDIO */
3037  if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) {
3038  if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
3040  else if (descriptor->bits_per_sample == 32)
3042  } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) {
3043  if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
3045  else if (descriptor->bits_per_sample == 32)
3047  } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
3049  } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
3051  }
3053 
3054  if (descriptor->channels <= 0 || descriptor->channels >= FF_SANE_NB_CHANNELS) {
3055  av_log(mxf->fc, AV_LOG_ERROR, "Invalid number of channels %d, must be less than %d\n", descriptor->channels, FF_SANE_NB_CHANNELS);
3056  return AVERROR_INVALIDDATA;
3057  }
3058 
3059  ret = parse_mca_labels(mxf, source_track, descriptor, st);
3060  if (ret < 0)
3061  return ret;
3062  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
3063  enum AVMediaType type;
3065  if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
3066  st->codecpar->codec_id = container_ul->id;
3068  if (type == AVMEDIA_TYPE_SUBTITLE)
3069  st->codecpar->codec_type = type;
3070  if (container_ul->desc)
3071  av_dict_set(&st->metadata, "data_type", container_ul->desc, 0);
3072  if (mxf->eia608_extract &&
3073  !strcmp(container_ul->desc, "vbi_vanc_smpte_436M")) {
3076  }
3077  }
3078  if (!descriptor->extradata)
3079  parse_ffv1_sub_descriptor(mxf, source_track, descriptor, st);
3080  if (descriptor->extradata) {
3081  if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) {
3082  memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size);
3083  }
3084  } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
3086  &descriptor->essence_codec_ul)->id;
3087  if (coded_width)
3088  st->codecpar->width = coded_width;
3090  if (ret < 0)
3091  return ret;
3092  }
3093  if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) {
3094  /* TODO: decode timestamps */
3096  }
3097  }
3098 
3099  for (int i = 0; i < mxf->fc->nb_streams; i++) {
3100  MXFTrack *track1 = mxf->fc->streams[i]->priv_data;
3101  if (track1 && track1->body_sid) {
3102  for (int j = i + 1; j < mxf->fc->nb_streams; j++) {
3103  MXFTrack *track2 = mxf->fc->streams[j]->priv_data;
3104  if (track2 && track1->body_sid == track2->body_sid && track1->wrapping != track2->wrapping) {
3105  if (track1->wrapping == UnknownWrapped)
3106  track1->wrapping = track2->wrapping;
3107  else if (track2->wrapping == UnknownWrapped)
3108  track2->wrapping = track1->wrapping;
3109  else
3110  av_log(mxf->fc, AV_LOG_ERROR, "stream %d and stream %d have the same BodySID (%d) "
3111  "with different wrapping\n", i, j, track1->body_sid);
3112  }
3113  }
3114  }
3115  }
3116 
3117  ret = 0;
3118 fail_and_free:
3119  return ret;
3120 }
3121 
3122 static int64_t mxf_timestamp_to_int64(uint64_t timestamp)
3123 {
3124  struct tm time = { 0 };
3125  int msecs;
3126  time.tm_year = (timestamp >> 48) - 1900;
3127  time.tm_mon = (timestamp >> 40 & 0xFF) - 1;
3128  time.tm_mday = (timestamp >> 32 & 0xFF);
3129  time.tm_hour = (timestamp >> 24 & 0xFF);
3130  time.tm_min = (timestamp >> 16 & 0xFF);
3131  time.tm_sec = (timestamp >> 8 & 0xFF);
3132  msecs = (timestamp & 0xFF) * 4;
3133 
3134  /* Clip values for legacy reasons. Maybe we should return error instead? */
3135  time.tm_mon = av_clip(time.tm_mon, 0, 11);
3136  time.tm_mday = av_clip(time.tm_mday, 1, 31);
3137  time.tm_hour = av_clip(time.tm_hour, 0, 23);
3138  time.tm_min = av_clip(time.tm_min, 0, 59);
3139  time.tm_sec = av_clip(time.tm_sec, 0, 59);
3140  msecs = av_clip(msecs, 0, 999);
3141 
3142  return (int64_t)av_timegm(&time) * 1000000 + msecs * 1000;
3143 }
3144 
3145 #define SET_STR_METADATA(pb, name, str) do { \
3146  if ((ret = mxf_read_utf16be_string(pb, size, &str)) < 0) \
3147  return ret; \
3148  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
3149 } while (0)
3150 
3151 #define SET_VERSION_METADATA(pb, name, major, minor, tertiary, patch, release, str) do { \
3152  major = avio_rb16(pb); \
3153  minor = avio_rb16(pb); \
3154  tertiary = avio_rb16(pb); \
3155  patch = avio_rb16(pb); \
3156  release = avio_rb16(pb); \
3157  if ((ret = mxf_version_to_str(major, minor, tertiary, patch, release, &str)) < 0) \
3158  return ret; \
3159  av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
3160 } while (0)
3161 
3162 #define SET_UID_METADATA(pb, name, var, str) do { \
3163  char uuid_str[2 * AV_UUID_LEN + 4 + 1]; \
3164  avio_read(pb, var, 16); \
3165  av_uuid_unparse(uid, uuid_str); \
3166  av_dict_set(&s->metadata, name, uuid_str, 0); \
3167 } while (0)
3168 
3169 #define SET_TS_METADATA(pb, name, var, str) do { \
3170  var = avio_rb64(pb); \
3171  if (var && (ret = avpriv_dict_set_timestamp(&s->metadata, name, mxf_timestamp_to_int64(var))) < 0) \
3172  return ret; \
3173 } while (0)
3174 
3175 static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset)
3176 {
3177  MXFContext *mxf = arg;
3178  AVFormatContext *s = mxf->fc;
3179  int ret;
3180  UID uid = { 0 };
3181  char *str = NULL;
3182  uint64_t ts;
3183  uint16_t major, minor, tertiary, patch, release;
3184  switch (tag) {
3185  case 0x3C01:
3186  SET_STR_METADATA(pb, "company_name", str);
3187  break;
3188  case 0x3C02:
3189  SET_STR_METADATA(pb, "product_name", str);
3190  break;
3191  case 0x3C03:
3192  SET_VERSION_METADATA(pb, "product_version_num", major, minor, tertiary, patch, release, str);
3193  break;
3194  case 0x3C04:
3195  SET_STR_METADATA(pb, "product_version", str);
3196  break;
3197  case 0x3C05:
3198  SET_UID_METADATA(pb, "product_uid", uid, str);
3199  break;
3200  case 0x3C06:
3201  SET_TS_METADATA(pb, "modification_date", ts, str);
3202  break;
3203  case 0x3C07:
3204  SET_VERSION_METADATA(pb, "toolkit_version_num", major, minor, tertiary, patch, release, str);
3205  break;
3206  case 0x3C08:
3207  SET_STR_METADATA(pb, "application_platform", str);
3208  break;
3209  case 0x3C09:
3210  SET_UID_METADATA(pb, "generation_uid", uid, str);
3211  break;
3212  case 0x3C0A:
3213  SET_UID_METADATA(pb, "uid", uid, str);
3214  break;
3215  }
3216  return 0;
3217 }
3218 
3219 static int mxf_read_preface_metadata(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
3220 {
3221  MXFContext *mxf = arg;
3222  AVFormatContext *s = mxf->fc;
3223  int ret;
3224  char *str = NULL;
3225 
3226  if (tag >= 0x8000 && (IS_KLV_KEY(uid, mxf_avid_project_name))) {
3227  SET_STR_METADATA(pb, "project_name", str);
3228  }
3229  return 0;
3230 }
3231 
3233  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
3234  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
3235  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
3236  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
3237  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
3238  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
3239  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
3240  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
3241  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
3242  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
3243  { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
3244  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2f,0x00 }, mxf_read_preface_metadata },
3245  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x30,0x00 }, mxf_read_identification_metadata },
3246  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
3247  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_package, sizeof(MXFPackage), SourcePackage },
3248  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_package, sizeof(MXFPackage), MaterialPackage },
3249  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0f,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
3250  { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x05,0x00 }, mxf_read_essence_group, sizeof(MXFEssenceGroup), EssenceGroup},
3251  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
3252  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3f,0x00 }, mxf_read_tagged_value, sizeof(MXFTaggedValue), TaggedValue },
3253  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
3254  { { 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 */
3255  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
3256  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
3257  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
3258  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
3259  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2VideoDescriptor */
3260  { { 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 */
3261  { { 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 */
3262  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5e,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2AudioDescriptor */
3263  { { 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 */
3264  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x6b,0x00 }, mxf_read_mca_sub_descriptor, sizeof(MXFMCASubDescriptor), AudioChannelLabelSubDescriptor },
3265  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x6c,0x00 }, mxf_read_mca_sub_descriptor, sizeof(MXFMCASubDescriptor), SoundfieldGroupLabelSubDescriptor },
3266  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x6d,0x00 }, mxf_read_mca_sub_descriptor, sizeof(MXFMCASubDescriptor), GroupOfSoundfieldGroupsLabelSubDescriptor },
3267  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x81,0x03 }, mxf_read_ffv1_sub_descriptor, sizeof(MXFFFV1SubDescriptor), FFV1SubDescriptor },
3268  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
3269  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
3270  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent },
3271  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0c,0x00 }, mxf_read_pulldown_component, sizeof(MXFPulldownComponent), PulldownComponent },
3272  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
3273  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
3274  { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x23,0x00 }, mxf_read_essence_container_data, sizeof(MXFEssenceContainerData), EssenceContainerData },
3275  { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
3276 };
3277 
3279 {
3280  ctx->type = type;
3281  ctx->partition_score = partition_score(partition);
3282  switch (type){
3283  case MultipleDescriptor:
3284  case Descriptor:
3285  ((MXFDescriptor*)ctx)->pix_fmt = AV_PIX_FMT_NONE;
3286  ((MXFDescriptor*)ctx)->duration = AV_NOPTS_VALUE;
3287  break;
3288  default:
3289  break;
3290  }
3291  return 0;
3292 }
3293 
3294 static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
3295 {
3296  AVIOContext *pb = mxf->fc->pb;
3297  uint64_t klv_end = avio_tell(pb) + klv->length;
3298  MXFMetadataSet *meta;
3299  void *ctx;
3300 
3301  if (ctx_size) {
3302  meta = av_mallocz(ctx_size);
3303  if (!meta)
3304  return AVERROR(ENOMEM);
3305  ctx = meta;
3307  } else {
3308  meta = NULL;
3309  ctx = mxf;
3310  }
3311  while (avio_tell(pb) + 4ULL < klv_end && !avio_feof(pb)) {
3312  int ret;
3313  int tag = avio_rb16(pb);
3314  int size = avio_rb16(pb); /* KLV specified by 0x53 */
3315  int64_t next = avio_tell(pb);
3316  UID uid = {0};
3317  if (next < 0 || next > INT64_MAX - size) {
3318  if (meta) {
3319  mxf_free_metadataset(&meta, 1);
3320  }
3321  return next < 0 ? next : AVERROR_INVALIDDATA;
3322  }
3323  next += size;
3324 
3325  av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x size %d\n", tag, size);
3326  if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
3327  av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
3328  continue;
3329  }
3330  if (tag > 0x7FFF) { /* dynamic tag */
3331  int i;
3332  for (i = 0; i < mxf->local_tags_count; i++) {
3333  int local_tag = AV_RB16(mxf->local_tags+i*18);
3334  if (local_tag == tag) {
3335  memcpy(uid, mxf->local_tags+i*18+2, 16);
3336  av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x\n", local_tag);
3337  PRINT_KEY(mxf->fc, "uid", uid);
3338  }
3339  }
3340  }
3341  if (meta && tag == 0x3C0A) {
3342  avio_read(pb, meta->uid, 16);
3343  } else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0) {
3344  if (meta) {
3345  mxf_free_metadataset(&meta, 1);
3346  }
3347  return ret;
3348  }
3349 
3350  /* Accept the 64k local set limit being exceeded (Avid). Don't accept
3351  * it extending past the end of the KLV though (zzuf5.mxf). */
3352  if (avio_tell(pb) > klv_end) {
3353  if (meta) {
3354  mxf_free_metadataset(&meta, 1);
3355  }
3356 
3357  av_log(mxf->fc, AV_LOG_ERROR,
3358  "local tag %#04x extends past end of local set @ %#"PRIx64"\n",
3359  tag, klv->offset);
3360  return AVERROR_INVALIDDATA;
3361  } else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */
3362  avio_seek(pb, next, SEEK_SET);
3363  }
3364  return meta ? mxf_add_metadata_set(mxf, &meta) : 0;
3365 }
3366 
3367 /**
3368  * Matches any partition pack key, in other words:
3369  * - HeaderPartition
3370  * - BodyPartition
3371  * - FooterPartition
3372  * @return non-zero if the key is a partition pack key, zero otherwise
3373  */
3375 {
3376  //NOTE: this is a little lax since it doesn't constraint key[14]
3377  return !memcmp(key, mxf_header_partition_pack_key, 13) &&
3378  key[13] >= 2 && key[13] <= 4;
3379 }
3380 
3381 /**
3382  * Parses a metadata KLV
3383  * @return <0 on error, 0 otherwise
3384  */
3386  int ctx_size, enum MXFMetadataSetType type)
3387 {
3388  AVFormatContext *s = mxf->fc;
3389  int res;
3390  if (klv.key[5] == 0x53) {
3391  res = mxf_read_local_tags(mxf, &klv, read, ctx_size, type);
3392  } else {
3393  uint64_t next = avio_tell(s->pb) + klv.length;
3394  res = read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
3395 
3396  /* only seek forward, else this can loop for a long time */
3397  if (avio_tell(s->pb) > next) {
3398  av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
3399  klv.offset);
3400  return AVERROR_INVALIDDATA;
3401  }
3402 
3403  avio_seek(s->pb, next, SEEK_SET);
3404  }
3405  if (res < 0) {
3406  av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
3407  return res;
3408  }
3409  return 0;
3410 }
3411 
3412 /**
3413  * Seeks to the previous partition and parses it, if possible
3414  * @return <= 0 if we should stop parsing, > 0 if we should keep going
3415  */
3417 {
3418  AVIOContext *pb = mxf->fc->pb;
3419  KLVPacket klv;
3420  int64_t current_partition_ofs;
3421  int ret;
3422 
3423  if (!mxf->current_partition ||
3425  return 0; /* we've parsed all partitions */
3426 
3427  /* seek to previous partition */
3428  current_partition_ofs = mxf->current_partition->pack_ofs; //includes run-in
3429  avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
3430  mxf->current_partition = NULL;
3431 
3432  av_log(mxf->fc, AV_LOG_TRACE, "seeking to previous partition\n");
3433 
3434  /* Make sure this is actually a PartitionPack, and if so parse it.
3435  * See deadlock2.mxf
3436  */
3437  if ((ret = klv_read_packet(mxf, &klv, pb)) < 0) {
3438  av_log(mxf->fc, AV_LOG_ERROR, "failed to read PartitionPack KLV\n");
3439  return ret;
3440  }
3441 
3442  if (!mxf_is_partition_pack_key(klv.key)) {
3443  av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition @ %" PRIx64 " isn't a PartitionPack\n", klv.offset);
3444  return AVERROR_INVALIDDATA;
3445  }
3446 
3447  /* We can't just check ofs >= current_partition_ofs because PreviousPartition
3448  * can point to just before the current partition, causing klv_read_packet()
3449  * to sync back up to it. See deadlock3.mxf
3450  */
3451  if (klv.offset >= current_partition_ofs) {
3452  av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition for PartitionPack @ %"
3453  PRIx64 " indirectly points to itself\n", current_partition_ofs);
3454  return AVERROR_INVALIDDATA;
3455  }
3456 
3457  if ((ret = mxf_parse_klv(mxf, klv, mxf_read_partition_pack, 0, 0)) < 0)
3458  return ret;
3459 
3460  return 1;
3461 }
3462 
3463 /**
3464  * Called when essence is encountered
3465  * @return <= 0 if we should stop parsing, > 0 if we should keep going
3466  */
3468 {
3469  AVIOContext *pb = mxf->fc->pb;
3470  int64_t ret;
3471 
3472  if (mxf->parsing_backward) {
3473  return mxf_seek_to_previous_partition(mxf);
3474  } else {
3475  if (!mxf->footer_partition) {
3476  av_log(mxf->fc, AV_LOG_TRACE, "no FooterPartition\n");
3477  return 0;
3478  }
3479 
3480  av_log(mxf->fc, AV_LOG_TRACE, "seeking to FooterPartition\n");
3481 
3482  /* remember where we were so we don't end up seeking further back than this */
3483  mxf->last_forward_tell = avio_tell(pb);
3484 
3485  if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) {
3486  av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing FooterPartition\n");
3487  return -1;
3488  }
3489 
3490  /* seek to FooterPartition and parse backward */
3491  if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
3492  av_log(mxf->fc, AV_LOG_ERROR,
3493  "failed to seek to FooterPartition @ 0x%" PRIx64
3494  " (%"PRId64") - partial file?\n",
3495  mxf->run_in + mxf->footer_partition, ret);
3496  return ret;
3497  }
3498 
3499  mxf->current_partition = NULL;
3500  mxf->parsing_backward = 1;
3501  }
3502 
3503  return 1;
3504 }
3505 
3506 /**
3507  * Called when the next partition or EOF is encountered
3508  * @return <= 0 if we should stop parsing, > 0 if we should keep going
3509  */
3511 {
3512  return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
3513 }
3514 
3516 {
3517  for (int i = 0; i < s->nb_streams; i++) {
3518  MXFTrack *track = s->streams[i]->priv_data;
3519  if (track && track->body_sid == body_sid && track->wrapping != UnknownWrapped)
3520  return track->wrapping;
3521  }
3522  return UnknownWrapped;
3523 }
3524 
3525 /**
3526  * Figures out the proper offset and length of the essence container in each partition
3527  */
3529 {
3530  MXFContext *mxf = s->priv_data;
3531  int x;
3532 
3533  for (x = 0; x < mxf->partitions_count; x++) {
3534  MXFPartition *p = &mxf->partitions[x];
3535  MXFWrappingScheme wrapping;
3536 
3537  if (!p->body_sid)
3538  continue; /* BodySID == 0 -> no essence */
3539 
3540  /* for clip wrapped essences we point essence_offset after the KL (usually klv.offset + 20 or 25)
3541  * otherwise we point essence_offset at the key of the first essence KLV.
3542  */
3543 
3544  wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_by_body_sid(s, p->body_sid);
3545 
3546  if (wrapping == ClipWrapped) {
3549  } else {
3551 
3552  /* essence container spans to the next partition */
3553  if (x < mxf->partitions_count - 1)
3554  p->essence_length = mxf->partitions[x+1].pack_ofs - mxf->run_in - p->essence_offset;
3555 
3556  if (p->essence_length < 0) {
3557  /* next ThisPartition < essence_offset */
3558  p->essence_length = 0;
3559  av_log(mxf->fc, AV_LOG_ERROR,
3560  "partition %i: bad ThisPartition = %"PRIX64"\n",
3561  x+1, mxf->partitions[x+1].pack_ofs - mxf->run_in);
3562  }
3563  }
3564  }
3565 }
3566 
3567 static MXFIndexTable *mxf_find_index_table(MXFContext *mxf, int index_sid)
3568 {
3569  int i;
3570  for (i = 0; i < mxf->nb_index_tables; i++)
3571  if (mxf->index_tables[i].index_sid == index_sid)
3572  return &mxf->index_tables[i];
3573  return NULL;
3574 }
3575 
3576 /**
3577  * Deal with the case where for some audio atoms EditUnitByteCount is
3578  * very small (2, 4..). In those cases we should read more than one
3579  * sample per call to mxf_read_packet().
3580  */
3582 {
3583  MXFTrack *track = st->priv_data;
3584  MXFIndexTable *t;
3585 
3586  if (!track)
3587  return;
3588  track->edit_units_per_packet = 1;
3589  if (track->wrapping != ClipWrapped)
3590  return;
3591 
3592  t = mxf_find_index_table(mxf, track->index_sid);
3593 
3594  /* expect PCM with exactly one index table segment and a small (< 32) EUBC */
3595  if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
3596  !is_pcm(st->codecpar->codec_id) ||
3597  !t ||
3598  t->nb_segments != 1 ||
3599  t->segments[0]->edit_unit_byte_count >= 32)
3600  return;
3601 
3602  /* arbitrarily default to 48 kHz PAL audio frame size */
3603  /* TODO: We could compute this from the ratio between the audio
3604  * and video edit rates for 48 kHz NTSC we could use the
3605  * 1802-1802-1802-1802-1801 pattern. */
3606  track->edit_units_per_packet = FFMAX(1, track->edit_rate.num / track->edit_rate.den / 25);
3607 }
3608 
3609 /**
3610  * Deal with the case where ClipWrapped essences does not have any IndexTableSegments.
3611  */
3613 {
3614  MXFTrack *track = st->priv_data;
3616  MXFPartition *p = NULL;
3617  int essence_partition_count = 0;
3618  int edit_unit_byte_count = 0;
3619  int i, ret;
3620 
3621  if (!track || track->wrapping != ClipWrapped)
3622  return 0;
3623 
3624  /* check if track already has an IndexTableSegment */
3625  for (i = 0; i < mxf->metadata_sets_count; i++) {
3626  if (mxf->metadata_sets[i]->type == IndexTableSegment) {
3628  if (s->body_sid == track->body_sid)
3629  return 0;
3630  }
3631  }
3632 
3633  /* find the essence partition */
3634  for (i = 0; i < mxf->partitions_count; i++) {
3635  /* BodySID == 0 -> no essence */
3636  if (mxf->partitions[i].body_sid != track->body_sid)
3637  continue;
3638 
3639  p = &mxf->partitions[i];
3640  essence_partition_count++;
3641  }
3642 
3643  /* only handle files with a single essence partition */
3644  if (essence_partition_count != 1)
3645  return 0;
3646 
3648  edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) *
3649  st->codecpar->ch_layout.nb_channels) >> 3;
3650  } else if (st->duration > 0 && p->first_essence_klv.length > 0 && p->first_essence_klv.length % st->duration == 0) {
3651  edit_unit_byte_count = p->first_essence_klv.length / st->duration;
3652  }
3653 
3654  if (edit_unit_byte_count <= 0)
3655  return 0;
3656 
3657  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);
3658 
3659  if (!(segment = av_mallocz(sizeof(*segment))))
3660  return AVERROR(ENOMEM);
3661 
3662  if ((ret = mxf_add_metadata_set(mxf, (MXFMetadataSet**)&segment)))
3663  return ret;
3664 
3665  /* Make sure we have nonzero unique index_sid, body_sid will be ok, because
3666  * using the same SID for index is forbidden in MXF. */
3667  if (!track->index_sid)
3668  track->index_sid = track->body_sid;
3669 
3670  segment->meta.type = IndexTableSegment;
3671  /* stream will be treated as small EditUnitByteCount */
3672  segment->edit_unit_byte_count = edit_unit_byte_count;
3673  segment->index_start_position = 0;
3674  segment->index_duration = st->duration;
3675  segment->index_edit_rate = av_inv_q(st->time_base);
3676  segment->index_sid = track->index_sid;
3677  segment->body_sid = p->body_sid;
3678  return 0;
3679 }
3680 
3682 {
3683  MXFContext *mxf = s->priv_data;
3684  uint32_t length;
3685  int64_t file_size, max_rip_length, min_rip_length;
3686  KLVPacket klv;
3687 
3688  if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL))
3689  return;
3690 
3691  file_size = avio_size(s->pb);
3692 
3693  /* S377m says to check the RIP length for "silly" values, without defining "silly".
3694  * The limit below assumes a file with nothing but partition packs and a RIP.
3695  * Before changing this, consider that a muxer may place each sample in its own partition.
3696  *
3697  * 105 is the size of the smallest possible PartitionPack
3698  * 12 is the size of each RIP entry
3699  * 28 is the size of the RIP header and footer, assuming an 8-byte BER
3700  */
3701  max_rip_length = ((file_size - mxf->run_in) / 105) * 12 + 28;
3702  max_rip_length = FFMIN(max_rip_length, INT_MAX); //2 GiB and up is also silly
3703 
3704  /* We're only interested in RIPs with at least two entries.. */
3705  min_rip_length = 16+1+24+4;
3706 
3707  /* See S377m section 11 */
3708  avio_seek(s->pb, file_size - 4, SEEK_SET);
3709  length = avio_rb32(s->pb);
3710 
3711  if (length < min_rip_length || length > max_rip_length)
3712  goto end;
3713  avio_seek(s->pb, file_size - length, SEEK_SET);
3714  if (klv_read_packet(mxf, &klv, s->pb) < 0 ||
3716  goto end;
3717  if (klv.next_klv != file_size || klv.length <= 4 || (klv.length - 4) % 12) {
3718  av_log(s, AV_LOG_WARNING, "Invalid RIP KLV length\n");
3719  goto end;
3720  }
3721 
3722  avio_skip(s->pb, klv.length - 12);
3723  mxf->footer_partition = avio_rb64(s->pb);
3724 
3725  /* sanity check */
3726  if (mxf->run_in + mxf->footer_partition >= file_size) {
3727  av_log(s, AV_LOG_WARNING, "bad FooterPartition in RIP - ignoring\n");
3728  mxf->footer_partition = 0;
3729  }
3730 
3731 end:
3732  avio_seek(s->pb, mxf->run_in, SEEK_SET);
3733 }
3734 
3736 {
3737  MXFContext *mxf = s->priv_data;
3738  KLVPacket klv;
3739  int64_t essence_offset = 0;
3740  int ret;
3741  int64_t run_in;
3742 
3743  mxf->last_forward_tell = INT64_MAX;
3744 
3746  av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
3747  return AVERROR_INVALIDDATA;
3748  }
3749  avio_seek(s->pb, -14, SEEK_CUR);
3750  mxf->fc = s;
3751  run_in = avio_tell(s->pb);
3752  if (run_in < 0 || run_in > RUN_IN_MAX)
3753  return AVERROR_INVALIDDATA;
3754  mxf->run_in = run_in;
3755 
3757 
3758  while (!avio_feof(s->pb)) {
3759  const MXFMetadataReadTableEntry *metadata;
3760 
3761  ret = klv_read_packet(mxf, &klv, s->pb);
3762  if (ret < 0 || IS_KLV_KEY(klv.key, ff_mxf_random_index_pack_key)) {
3763  if (ret >= 0 && avio_size(s->pb) > klv.next_klv)
3764  av_log(s, AV_LOG_WARNING, "data after the RandomIndexPack, assuming end of file\n");
3765  /* EOF - seek to previous partition or stop */
3766  if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
3767  break;
3768  else
3769  continue;
3770  }
3771 
3772  PRINT_KEY(s, "read header", klv.key);
3773  av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
3780 
3781  if (!mxf->current_partition) {
3782  av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
3783  return AVERROR_INVALIDDATA;
3784  }
3785 
3788 
3789  if (!essence_offset)
3790  essence_offset = klv.offset;
3791 
3792  /* seek to footer, previous partition or stop */
3793  if (mxf_parse_handle_essence(mxf) <= 0)
3794  break;
3795  continue;
3796  } else if (mxf_is_partition_pack_key(klv.key) && mxf->current_partition) {
3797  /* next partition pack - keep going, seek to previous partition or stop */
3798  if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
3799  break;
3800  else if (mxf->parsing_backward)
3801  continue;
3802  /* we're still parsing forward. proceed to parsing this partition pack */
3803  }
3804 
3805  for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
3806  if (IS_KLV_KEY(klv.key, metadata->key)) {
3807  if ((ret = mxf_parse_klv(mxf, klv, metadata->read, metadata->ctx_size, metadata->type)) < 0)
3808  return ret;
3809  break;
3810  }
3811  }
3812  if (!metadata->read) {
3813  av_log(s, AV_LOG_VERBOSE, "Dark key " PRIxUID "\n",
3814  UID_ARG(klv.key));
3815  avio_skip(s->pb, klv.length);
3816  }
3817  }
3818  /* FIXME avoid seek */
3819  if (!essence_offset) {
3820  av_log(s, AV_LOG_ERROR, "no essence\n");
3821  return AVERROR_INVALIDDATA;
3822  }
3823  avio_seek(s->pb, essence_offset, SEEK_SET);
3824 
3825  /* we need to do this before computing the index tables
3826  * to be able to fill in zero IndexDurations with st->duration */
3827  if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
3828  return ret;
3829 
3830  for (int i = 0; i < s->nb_streams; i++)
3831  mxf_handle_missing_index_segment(mxf, s->streams[i]);
3832 
3833  if ((ret = mxf_compute_index_tables(mxf)) < 0)
3834  return ret;
3835 
3836  if (mxf->nb_index_tables > 1) {
3837  /* TODO: look up which IndexSID to use via EssenceContainerData */
3838  av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
3839  mxf->nb_index_tables, mxf->index_tables[0].index_sid);
3840  } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom && (s->error_recognition & AV_EF_EXPLODE)) {
3841  av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
3842  return AVERROR_INVALIDDATA;
3843  }
3844 
3846 
3847  for (int i = 0; i < s->nb_streams; i++)
3848  mxf_compute_edit_units_per_packet(mxf, s->streams[i]);
3849 
3850  return 0;
3851 }
3852 
3853 /* Get the edit unit of the next packet from current_offset in a track. The returned edit unit can be original_duration as well! */
3854 static int mxf_get_next_track_edit_unit(MXFContext *mxf, MXFTrack *track, int64_t current_offset, int64_t *edit_unit_out)
3855 {
3856  int64_t a, b, m, offset;
3857  MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
3858 
3859  if (!t || track->original_duration <= 0)
3860  return -1;
3861 
3862  a = -1;
3863  b = track->original_duration;
3864 
3865  while (b - a > 1) {
3866  m = (a + b) >> 1;
3867  if (mxf_edit_unit_absolute_offset(mxf, t, m, track->edit_rate, NULL, &offset, NULL, 0) < 0)
3868  return -1;
3869  if (offset < current_offset)
3870  a = m;
3871  else
3872  b = m;
3873  }
3874 
3875  *edit_unit_out = b;
3876 
3877  return 0;
3878 }
3879 
3881  int64_t edit_unit)
3882 {
3883  MXFTrack *track = st->priv_data;
3884  AVRational time_base = av_inv_q(track->edit_rate);
3886 
3887  // For non-audio sample_count equals current edit unit
3889  return edit_unit;
3890 
3891  if ((sample_rate.num / sample_rate.den) == 48000) {
3892  return av_rescale_q(edit_unit, sample_rate, track->edit_rate);
3893  } else {
3894  int64_t remainder = (sample_rate.num * (int64_t) time_base.num) %
3895  ( time_base.den * (int64_t)sample_rate.den);
3896  if (remainder)
3897  av_log(mxf->fc, AV_LOG_WARNING,
3898  "seeking detected on stream #%d with time base (%d/%d) and "
3899  "sample rate (%d/%d), audio pts won't be accurate.\n",
3900  st->index, time_base.num, time_base.den,
3901  sample_rate.num, sample_rate.den);
3902  return av_rescale_q(edit_unit, sample_rate, track->edit_rate);
3903  }
3904 }
3905 
3906 /**
3907  * Make sure track->sample_count is correct based on what offset we're currently at.
3908  * Also determine the next edit unit (or packet) offset.
3909  * @return next_ofs if OK, <0 on error
3910  */
3911 static int64_t mxf_set_current_edit_unit(MXFContext *mxf, AVStream *st, int64_t current_offset, int resync)
3912 {
3913  int64_t next_ofs = -1;
3914  MXFTrack *track = st->priv_data;
3915  int64_t edit_unit = av_rescale_q(track->sample_count, st->time_base, av_inv_q(track->edit_rate));
3916  int64_t new_edit_unit;
3917  MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
3918 
3919  if (!t || track->wrapping == UnknownWrapped)
3920  return -1;
3921 
3922  if (mxf_edit_unit_absolute_offset(mxf, t, edit_unit + track->edit_units_per_packet, track->edit_rate, NULL, &next_ofs, NULL, 0) < 0 &&
3923  (next_ofs = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
3924  av_log(mxf->fc, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
3925  return -1;
3926  }
3927 
3928  /* check if the next edit unit offset (next_ofs) starts ahead of current_offset */
3929  if (next_ofs > current_offset)
3930  return next_ofs;
3931 
3932  if (!resync) {
3933  av_log(mxf->fc, AV_LOG_ERROR, "cannot find current edit unit for stream %d, invalid index?\n", st->index);
3934  return -1;
3935  }
3936 
3937  if (mxf_get_next_track_edit_unit(mxf, track, current_offset + 1, &new_edit_unit) < 0 || new_edit_unit <= 0) {
3938  av_log(mxf->fc, AV_LOG_ERROR, "failed to find next track edit unit in stream %d\n", st->index);
3939  return -1;
3940  }
3941 
3942  new_edit_unit--;
3943  track->sample_count = mxf_compute_sample_count(mxf, st, new_edit_unit);
3944  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);
3945 
3946  return mxf_set_current_edit_unit(mxf, st, current_offset, 0);
3947 }
3948 
3950  AVPacket *pkt)
3951 {
3952  AVStream *st = mxf->fc->streams[pkt->stream_index];
3953  MXFTrack *track = st->priv_data;
3954  int64_t bits_per_sample = par->bits_per_coded_sample;
3955 
3956  if (!bits_per_sample)
3957  bits_per_sample = av_get_bits_per_sample(par->codec_id);
3958 
3959  pkt->pts = track->sample_count;
3960 
3961  if (par->ch_layout.nb_channels <= 0 ||
3962  bits_per_sample <= 0 ||
3963  par->ch_layout.nb_channels * (int64_t)bits_per_sample < 8)
3964  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);
3965  else
3966  track->sample_count += pkt->size / (par->ch_layout.nb_channels * (int64_t)bits_per_sample / 8);
3967 
3968  return 0;
3969 }
3970 
3971 static int mxf_set_pts(MXFContext *mxf, AVStream *st, AVPacket *pkt)
3972 {
3973  AVCodecParameters *par = st->codecpar;
3974  MXFTrack *track = st->priv_data;
3975 
3976  if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
3977  /* see if we have an index table to derive timestamps from */
3978  MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
3979 
3980  if (t && track->sample_count < t->nb_ptses) {
3981  pkt->dts = track->sample_count + t->first_dts;
3982  pkt->pts = t->ptses[track->sample_count];
3983  } else if (track->intra_only) {
3984  /* intra-only -> PTS = EditUnit.
3985  * let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */
3986  pkt->pts = track->sample_count;
3987  }
3988  track->sample_count++;
3989  } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
3990  int ret = mxf_set_audio_pts(mxf, par, pkt);
3991  if (ret < 0)
3992  return ret;
3993  } else if (track) {
3994  pkt->dts = pkt->pts = track->sample_count;
3995  pkt->duration = 1;
3996  track->sample_count++;
3997  }
3998  return 0;
3999 }
4000 
4002 {
4003  KLVPacket klv;
4004  MXFContext *mxf = s->priv_data;
4005  int ret;
4006 
4007  while (1) {
4008  int64_t max_data_size;
4009  int64_t pos = avio_tell(s->pb);
4010 
4011  if (pos < mxf->current_klv_data.next_klv - mxf->current_klv_data.length || pos >= mxf->current_klv_data.next_klv) {
4012  mxf->current_klv_data = (KLVPacket){{0}};
4013  ret = klv_read_packet(mxf, &klv, s->pb);
4014  if (ret < 0)
4015  break;
4016  max_data_size = klv.length;
4017  pos = klv.next_klv - klv.length;
4018  PRINT_KEY(s, "read packet", klv.key);
4019  av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
4021  ret = mxf_decrypt_triplet(s, pkt, &klv);
4022  if (ret < 0) {
4023  av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
4024  return ret;
4025  }
4026  return 0;
4027  }
4028  } else {
4029  klv = mxf->current_klv_data;
4030  max_data_size = klv.next_klv - pos;
4031  }
4035  int body_sid = find_body_sid_by_absolute_offset(mxf, klv.offset);
4036  int index = mxf_get_stream_index(s, &klv, body_sid);
4037  int64_t next_ofs;
4038  AVStream *st;
4039  MXFTrack *track;
4040 
4041  if (index < 0) {
4043  "error getting stream index %"PRIu32"\n",
4044  AV_RB32(klv.key + 12));
4045  goto skip;
4046  }
4047 
4048  st = s->streams[index];
4049  track = st->priv_data;
4050 
4051  if (s->streams[index]->discard == AVDISCARD_ALL)
4052  goto skip;
4053 
4054  next_ofs = mxf_set_current_edit_unit(mxf, st, pos, 1);
4055 
4056  if (track->wrapping != FrameWrapped) {
4057  int64_t size;
4058 
4059  if (next_ofs <= 0) {
4060  // If we have no way to packetize the data, then return it in chunks...
4061  if (klv.next_klv - klv.length == pos && max_data_size > MXF_MAX_CHUNK_SIZE) {
4063  avpriv_request_sample(s, "Huge KLV without proper index in non-frame wrapped essence");
4064  }
4065  size = FFMIN(max_data_size, MXF_MAX_CHUNK_SIZE);
4066  } else {
4067  if ((size = next_ofs - pos) <= 0) {
4068  av_log(s, AV_LOG_ERROR, "bad size: %"PRId64"\n", size);
4069  mxf->current_klv_data = (KLVPacket){{0}};
4070  return AVERROR_INVALIDDATA;
4071  }
4072  // We must not overread, because the next edit unit might be in another KLV
4073  if (size > max_data_size)
4074  size = max_data_size;
4075  }
4076 
4077  mxf->current_klv_data = klv;
4078  klv.offset = pos;
4079  klv.length = size;
4080  klv.next_klv = klv.offset + klv.length;
4081  }
4082 
4083  /* check for 8 channels AES3 element */
4084  if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
4085  ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index],
4086  pkt, klv.length);
4087  if (ret < 0) {
4088  av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
4089  mxf->current_klv_data = (KLVPacket){{0}};
4090  return ret;
4091  }
4092  } else if (mxf->eia608_extract &&
4093  s->streams[index]->codecpar->codec_id == AV_CODEC_ID_EIA_608) {
4094  ret = mxf_get_eia608_packet(s, s->streams[index], pkt, klv.length);
4095  if (ret < 0) {
4096  mxf->current_klv_data = (KLVPacket){{0}};
4097  return ret;
4098  }
4099  } else {
4100  ret = av_get_packet(s->pb, pkt, klv.length);
4101  if (ret < 0) {
4102  mxf->current_klv_data = (KLVPacket){{0}};
4103  return ret;
4104  }
4105  }
4106  pkt->stream_index = index;
4107  pkt->pos = klv.offset;
4108 
4109  ret = mxf_set_pts(mxf, st, pkt);
4110  if (ret < 0) {
4111  mxf->current_klv_data = (KLVPacket){{0}};
4112  return ret;
4113  }
4114 
4115  /* seek for truncated packets */
4116  avio_seek(s->pb, klv.next_klv, SEEK_SET);
4117 
4118  return 0;
4119  } else {
4120  skip:
4121  avio_skip(s->pb, max_data_size);
4122  mxf->current_klv_data = (KLVPacket){{0}};
4123  }
4124  }
4125  return avio_feof(s->pb) ? AVERROR_EOF : ret;
4126 }
4127 
4129 {
4130  MXFContext *mxf = s->priv_data;
4131  int i;
4132 
4133  av_freep(&mxf->packages_refs);
4135 
4136  for (i = 0; i < s->nb_streams; i++)
4137  s->streams[i]->priv_data = NULL;
4138 
4139  for (i = 0; i < mxf->metadata_sets_count; i++) {
4141  }
4142  mxf->metadata_sets_count = 0;
4143  av_freep(&mxf->partitions);
4144  av_freep(&mxf->metadata_sets);
4145  av_freep(&mxf->aesc);
4146  av_freep(&mxf->local_tags);
4147 
4148  if (mxf->index_tables) {
4149  for (i = 0; i < mxf->nb_index_tables; i++) {
4150  av_freep(&mxf->index_tables[i].segments);
4151  av_freep(&mxf->index_tables[i].ptses);
4153  av_freep(&mxf->index_tables[i].offsets);
4154  }
4155  }
4156  av_freep(&mxf->index_tables);
4157 
4158  return 0;
4159 }
4160 
4161 static int mxf_probe(const AVProbeData *p) {
4162  const uint8_t *bufp = p->buf;
4163  const uint8_t *end = p->buf + FFMIN(p->buf_size, RUN_IN_MAX + 1 + sizeof(mxf_header_partition_pack_key));
4164 
4165  if (p->buf_size < sizeof(mxf_header_partition_pack_key))
4166  return 0;
4167 
4168  /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
4169  end -= sizeof(mxf_header_partition_pack_key);
4170 
4171  for (; bufp < end;) {
4172  if (!((bufp[13] - 1) & 0xF2)){
4173  if (AV_RN32(bufp ) == AV_RN32(mxf_header_partition_pack_key ) &&
4174  AV_RN32(bufp+ 4) == AV_RN32(mxf_header_partition_pack_key+ 4) &&
4175  AV_RN32(bufp+ 8) == AV_RN32(mxf_header_partition_pack_key+ 8) &&
4177  return bufp == p->buf ? AVPROBE_SCORE_MAX : AVPROBE_SCORE_MAX - 1;
4178  bufp ++;
4179  } else
4180  bufp += 10;
4181  }
4182 
4183  return 0;
4184 }
4185 
4186 /* rudimentary byte seek */
4187 /* XXX: use MXF Index */
4188 static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
4189 {
4190  AVStream *st = s->streams[stream_index];
4191  int64_t seconds;
4192  MXFContext* mxf = s->priv_data;
4193  int64_t seekpos;
4194  int i, ret;
4195  MXFIndexTable *t;
4196  MXFTrack *source_track = st->priv_data;
4197 
4198  if (!source_track)
4199  return 0;
4200 
4201  /* if audio then truncate sample_time to EditRate */
4203  sample_time = av_rescale_q(sample_time, st->time_base,
4204  av_inv_q(source_track->edit_rate));
4205 
4206  if (mxf->nb_index_tables <= 0) {
4207  if (!s->bit_rate)
4208  return AVERROR_INVALIDDATA;
4209  if (sample_time < 0)
4210  sample_time = 0;
4211  seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
4212 
4213  seekpos = avio_seek(s->pb, (