You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2609 lines
97KB

  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 Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /*
  22. * References
  23. * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
  24. * SMPTE 377M MXF File Format Specifications
  25. * SMPTE 378M Operational Pattern 1a
  26. * SMPTE 379M MXF Generic Container
  27. * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
  28. * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
  29. * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
  30. *
  31. * Principle
  32. * Search for Track numbers which will identify essence element KLV packets.
  33. * Search for SourcePackage which define tracks which contains Track numbers.
  34. * Material Package contains tracks with reference to SourcePackage tracks.
  35. * Search for Descriptors (Picture, Sound) which contains codec info and parameters.
  36. * Assign Descriptors to correct Tracks.
  37. *
  38. * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
  39. * Metadata parsing resolves Strong References to objects.
  40. *
  41. * Simple demuxer, only OP1A supported and some files might not work at all.
  42. * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
  43. */
  44. #include <inttypes.h>
  45. #include "libavutil/aes.h"
  46. #include "libavutil/mathematics.h"
  47. #include "libavcodec/bytestream.h"
  48. #include "avformat.h"
  49. #include "internal.h"
  50. #include "mxf.h"
  51. typedef enum {
  52. Header,
  53. BodyPartition,
  54. Footer
  55. } MXFPartitionType;
  56. typedef enum {
  57. OP1a = 1,
  58. OP1b,
  59. OP1c,
  60. OP2a,
  61. OP2b,
  62. OP2c,
  63. OP3a,
  64. OP3b,
  65. OP3c,
  66. OPAtom,
  67. OPSonyOpt, /* FATE sample, violates the spec in places */
  68. } MXFOP;
  69. typedef struct {
  70. int closed;
  71. int complete;
  72. MXFPartitionType type;
  73. uint64_t previous_partition;
  74. int index_sid;
  75. int body_sid;
  76. int64_t this_partition;
  77. int64_t essence_offset; ///< absolute offset of essence
  78. int64_t essence_length;
  79. int32_t kag_size;
  80. int64_t header_byte_count;
  81. int64_t index_byte_count;
  82. int pack_length;
  83. } MXFPartition;
  84. typedef struct {
  85. UID uid;
  86. enum MXFMetadataSetType type;
  87. UID source_container_ul;
  88. } MXFCryptoContext;
  89. typedef struct {
  90. UID uid;
  91. enum MXFMetadataSetType type;
  92. UID source_package_uid;
  93. UID data_definition_ul;
  94. int64_t duration;
  95. int64_t start_position;
  96. int source_track_id;
  97. } MXFStructuralComponent;
  98. typedef struct {
  99. UID uid;
  100. enum MXFMetadataSetType type;
  101. UID data_definition_ul;
  102. UID *structural_components_refs;
  103. int structural_components_count;
  104. int64_t duration;
  105. } MXFSequence;
  106. typedef struct {
  107. UID uid;
  108. enum MXFMetadataSetType type;
  109. MXFSequence *sequence; /* mandatory, and only one */
  110. UID sequence_ref;
  111. int track_id;
  112. uint8_t track_number[4];
  113. AVRational edit_rate;
  114. int intra_only;
  115. uint64_t sample_count;
  116. int64_t original_duration; /* st->duration in SampleRate/EditRate units */
  117. } MXFTrack;
  118. typedef struct {
  119. UID uid;
  120. enum MXFMetadataSetType type;
  121. UID essence_container_ul;
  122. UID essence_codec_ul;
  123. AVRational sample_rate;
  124. AVRational aspect_ratio;
  125. int width;
  126. int height; /* Field height, not frame height */
  127. int frame_layout; /* See MXFFrameLayout enum */
  128. #define MXF_TFF 1
  129. #define MXF_BFF 2
  130. int field_dominance;
  131. int channels;
  132. int bits_per_sample;
  133. unsigned int component_depth;
  134. unsigned int horiz_subsampling;
  135. unsigned int vert_subsampling;
  136. UID *sub_descriptors_refs;
  137. int sub_descriptors_count;
  138. int linked_track_id;
  139. uint8_t *extradata;
  140. int extradata_size;
  141. enum AVPixelFormat pix_fmt;
  142. } MXFDescriptor;
  143. typedef struct {
  144. UID uid;
  145. enum MXFMetadataSetType type;
  146. int edit_unit_byte_count;
  147. int index_sid;
  148. int body_sid;
  149. AVRational index_edit_rate;
  150. uint64_t index_start_position;
  151. uint64_t index_duration;
  152. int8_t *temporal_offset_entries;
  153. int *flag_entries;
  154. uint64_t *stream_offset_entries;
  155. int nb_index_entries;
  156. } MXFIndexTableSegment;
  157. typedef struct {
  158. UID uid;
  159. enum MXFMetadataSetType type;
  160. UID package_uid;
  161. UID *tracks_refs;
  162. int tracks_count;
  163. MXFDescriptor *descriptor; /* only one */
  164. UID descriptor_ref;
  165. } MXFPackage;
  166. typedef struct {
  167. UID uid;
  168. enum MXFMetadataSetType type;
  169. } MXFMetadataSet;
  170. /* decoded index table */
  171. typedef struct {
  172. int index_sid;
  173. int body_sid;
  174. int nb_ptses; /* number of PTSes or total duration of index */
  175. int64_t first_dts; /* DTS = EditUnit + first_dts */
  176. int64_t *ptses; /* maps EditUnit -> PTS */
  177. int nb_segments;
  178. MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */
  179. AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */
  180. } MXFIndexTable;
  181. typedef struct {
  182. MXFPartition *partitions;
  183. unsigned partitions_count;
  184. MXFOP op;
  185. UID *packages_refs;
  186. int packages_count;
  187. MXFMetadataSet **metadata_sets;
  188. int metadata_sets_count;
  189. AVFormatContext *fc;
  190. struct AVAES *aesc;
  191. uint8_t *local_tags;
  192. int local_tags_count;
  193. uint64_t last_partition;
  194. uint64_t footer_partition;
  195. KLVPacket current_klv_data;
  196. int current_klv_index;
  197. int run_in;
  198. MXFPartition *current_partition;
  199. int parsing_backward;
  200. int64_t last_forward_tell;
  201. int last_forward_partition;
  202. int current_edit_unit;
  203. int nb_index_tables;
  204. MXFIndexTable *index_tables;
  205. int edit_units_per_packet; ///< how many edit units to read at a time (PCM, OPAtom)
  206. } MXFContext;
  207. enum MXFWrappingScheme {
  208. Frame,
  209. Clip,
  210. };
  211. /* NOTE: klv_offset is not set (-1) for local keys */
  212. typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
  213. typedef struct {
  214. const UID key;
  215. MXFMetadataReadFunc *read;
  216. int ctx_size;
  217. enum MXFMetadataSetType type;
  218. } MXFMetadataReadTableEntry;
  219. /* partial keys to match */
  220. static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
  221. static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
  222. static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
  223. static const uint8_t mxf_system_item_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x03,0x01,0x04 };
  224. static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
  225. /* complete keys to match */
  226. 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 };
  227. static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
  228. static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
  229. static const uint8_t mxf_random_index_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
  230. static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
  231. #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
  232. static int64_t klv_decode_ber_length(AVIOContext *pb)
  233. {
  234. uint64_t size = avio_r8(pb);
  235. if (size & 0x80) { /* long form */
  236. int bytes_num = size & 0x7f;
  237. /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
  238. if (bytes_num > 8)
  239. return AVERROR_INVALIDDATA;
  240. size = 0;
  241. while (bytes_num--)
  242. size = size << 8 | avio_r8(pb);
  243. }
  244. return size;
  245. }
  246. static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
  247. {
  248. int i, b;
  249. for (i = 0; i < size && !pb->eof_reached; i++) {
  250. b = avio_r8(pb);
  251. if (b == key[0])
  252. i = 0;
  253. else if (b != key[i])
  254. i = -1;
  255. }
  256. return i == size;
  257. }
  258. static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
  259. {
  260. if (!mxf_read_sync(pb, mxf_klv_key, 4))
  261. return AVERROR_INVALIDDATA;
  262. klv->offset = avio_tell(pb) - 4;
  263. memcpy(klv->key, mxf_klv_key, 4);
  264. avio_read(pb, klv->key + 4, 12);
  265. klv->length = klv_decode_ber_length(pb);
  266. return klv->length == -1 ? -1 : 0;
  267. }
  268. static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)
  269. {
  270. int i;
  271. for (i = 0; i < s->nb_streams; i++) {
  272. MXFTrack *track = s->streams[i]->priv_data;
  273. /* SMPTE 379M 7.3 */
  274. if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
  275. return i;
  276. }
  277. /* return 0 if only one stream, for OP Atom files with 0 as track number */
  278. return s->nb_streams == 1 ? 0 : -1;
  279. }
  280. /* XXX: use AVBitStreamFilter */
  281. static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
  282. {
  283. const uint8_t *buf_ptr, *end_ptr;
  284. uint8_t *data_ptr;
  285. int i;
  286. if (length > 61444) /* worst case PAL 1920 samples 8 channels */
  287. return AVERROR_INVALIDDATA;
  288. length = av_get_packet(pb, pkt, length);
  289. if (length < 0)
  290. return length;
  291. data_ptr = pkt->data;
  292. end_ptr = pkt->data + length;
  293. buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
  294. for (; end_ptr - buf_ptr >= st->codec->channels * 4; ) {
  295. for (i = 0; i < st->codec->channels; i++) {
  296. uint32_t sample = bytestream_get_le32(&buf_ptr);
  297. if (st->codec->bits_per_coded_sample == 24)
  298. bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
  299. else
  300. bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
  301. }
  302. buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M
  303. }
  304. av_shrink_packet(pkt, data_ptr - pkt->data);
  305. return 0;
  306. }
  307. static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
  308. {
  309. static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
  310. MXFContext *mxf = s->priv_data;
  311. AVIOContext *pb = s->pb;
  312. int64_t end = avio_tell(pb) + klv->length;
  313. int64_t size;
  314. uint64_t orig_size;
  315. uint64_t plaintext_size;
  316. uint8_t ivec[16];
  317. uint8_t tmpbuf[16];
  318. int index;
  319. if (!mxf->aesc && s->key && s->keylen == 16) {
  320. mxf->aesc = av_aes_alloc();
  321. if (!mxf->aesc)
  322. return AVERROR(ENOMEM);
  323. av_aes_init(mxf->aesc, s->key, 128, 1);
  324. }
  325. // crypto context
  326. avio_skip(pb, klv_decode_ber_length(pb));
  327. // plaintext offset
  328. klv_decode_ber_length(pb);
  329. plaintext_size = avio_rb64(pb);
  330. // source klv key
  331. klv_decode_ber_length(pb);
  332. avio_read(pb, klv->key, 16);
  333. if (!IS_KLV_KEY(klv, mxf_essence_element_key))
  334. return AVERROR_INVALIDDATA;
  335. index = mxf_get_stream_index(s, klv);
  336. if (index < 0)
  337. return AVERROR_INVALIDDATA;
  338. // source size
  339. klv_decode_ber_length(pb);
  340. orig_size = avio_rb64(pb);
  341. if (orig_size < plaintext_size)
  342. return AVERROR_INVALIDDATA;
  343. // enc. code
  344. size = klv_decode_ber_length(pb);
  345. if (size < 32 || size - 32 < orig_size)
  346. return AVERROR_INVALIDDATA;
  347. avio_read(pb, ivec, 16);
  348. avio_read(pb, tmpbuf, 16);
  349. if (mxf->aesc)
  350. av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
  351. if (memcmp(tmpbuf, checkv, 16))
  352. av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
  353. size -= 32;
  354. size = av_get_packet(pb, pkt, size);
  355. if (size < 0)
  356. return size;
  357. else if (size < plaintext_size)
  358. return AVERROR_INVALIDDATA;
  359. size -= plaintext_size;
  360. if (mxf->aesc)
  361. av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
  362. &pkt->data[plaintext_size], size >> 4, ivec, 1);
  363. av_shrink_packet(pkt, orig_size);
  364. pkt->stream_index = index;
  365. avio_skip(pb, end - avio_tell(pb));
  366. return 0;
  367. }
  368. static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  369. {
  370. MXFContext *mxf = arg;
  371. int item_num = avio_rb32(pb);
  372. int item_len = avio_rb32(pb);
  373. if (item_len != 18) {
  374. avpriv_request_sample(pb, "Primer pack item length %d", item_len);
  375. return AVERROR_PATCHWELCOME;
  376. }
  377. if (item_num > UINT_MAX / item_len)
  378. return AVERROR_INVALIDDATA;
  379. mxf->local_tags_count = item_num;
  380. mxf->local_tags = av_malloc(item_num*item_len);
  381. if (!mxf->local_tags)
  382. return AVERROR(ENOMEM);
  383. avio_read(pb, mxf->local_tags, item_num*item_len);
  384. return 0;
  385. }
  386. static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  387. {
  388. MXFContext *mxf = arg;
  389. MXFPartition *partition;
  390. UID op;
  391. uint64_t footer_partition;
  392. uint32_t nb_essence_containers;
  393. int err;
  394. if ((err = av_reallocp_array(&mxf->partitions, mxf->partitions_count + 1,
  395. sizeof(*mxf->partitions))) < 0) {
  396. mxf->partitions_count = 0;
  397. return err;
  398. }
  399. if (mxf->parsing_backward) {
  400. /* insert the new partition pack in the middle
  401. * this makes the entries in mxf->partitions sorted by offset */
  402. memmove(&mxf->partitions[mxf->last_forward_partition+1],
  403. &mxf->partitions[mxf->last_forward_partition],
  404. (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
  405. partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
  406. } else {
  407. mxf->last_forward_partition++;
  408. partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
  409. }
  410. memset(partition, 0, sizeof(*partition));
  411. mxf->partitions_count++;
  412. partition->pack_length = avio_tell(pb) - klv_offset + size;
  413. switch(uid[13]) {
  414. case 2:
  415. partition->type = Header;
  416. break;
  417. case 3:
  418. partition->type = BodyPartition;
  419. break;
  420. case 4:
  421. partition->type = Footer;
  422. break;
  423. default:
  424. av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
  425. return AVERROR_INVALIDDATA;
  426. }
  427. /* consider both footers to be closed (there is only Footer and CompleteFooter) */
  428. partition->closed = partition->type == Footer || !(uid[14] & 1);
  429. partition->complete = uid[14] > 2;
  430. avio_skip(pb, 4);
  431. partition->kag_size = avio_rb32(pb);
  432. partition->this_partition = avio_rb64(pb);
  433. partition->previous_partition = avio_rb64(pb);
  434. footer_partition = avio_rb64(pb);
  435. partition->header_byte_count = avio_rb64(pb);
  436. partition->index_byte_count = avio_rb64(pb);
  437. partition->index_sid = avio_rb32(pb);
  438. avio_skip(pb, 8);
  439. partition->body_sid = avio_rb32(pb);
  440. avio_read(pb, op, sizeof(UID));
  441. nb_essence_containers = avio_rb32(pb);
  442. if (partition->this_partition &&
  443. partition->previous_partition == partition->this_partition) {
  444. av_log(mxf->fc, AV_LOG_ERROR,
  445. "PreviousPartition equal to ThisPartition %"PRIx64"\n",
  446. partition->previous_partition);
  447. /* override with the actual previous partition offset */
  448. if (!mxf->parsing_backward && mxf->last_forward_partition > 1) {
  449. MXFPartition *prev =
  450. mxf->partitions + mxf->last_forward_partition - 2;
  451. partition->previous_partition = prev->this_partition;
  452. }
  453. /* if no previous body partition are found point to the header
  454. * partition */
  455. if (partition->previous_partition == partition->this_partition)
  456. partition->previous_partition = 0;
  457. av_log(mxf->fc, AV_LOG_ERROR,
  458. "Overriding PreviousPartition with %"PRIx64"\n",
  459. partition->previous_partition);
  460. }
  461. /* some files don'thave FooterPartition set in every partition */
  462. if (footer_partition) {
  463. if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
  464. av_log(mxf->fc, AV_LOG_ERROR,
  465. "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",
  466. mxf->footer_partition, footer_partition);
  467. } else {
  468. mxf->footer_partition = footer_partition;
  469. }
  470. }
  471. av_dlog(mxf->fc,
  472. "PartitionPack: ThisPartition = 0x%"PRIX64
  473. ", PreviousPartition = 0x%"PRIX64", "
  474. "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",
  475. partition->this_partition,
  476. partition->previous_partition, footer_partition,
  477. partition->index_sid, partition->body_sid);
  478. /* sanity check PreviousPartition if set */
  479. if (partition->previous_partition &&
  480. mxf->run_in + partition->previous_partition >= klv_offset) {
  481. av_log(mxf->fc, AV_LOG_ERROR,
  482. "PreviousPartition points to this partition or forward\n");
  483. return AVERROR_INVALIDDATA;
  484. }
  485. if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
  486. else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
  487. else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
  488. else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
  489. else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
  490. else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
  491. else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
  492. else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
  493. else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
  494. else if (op[12] == 64&& op[13] == 1) mxf->op = OPSonyOpt;
  495. else if (op[12] == 0x10) {
  496. /* SMPTE 390m: "There shall be exactly one essence container"
  497. * The following block deals with files that violate this, namely:
  498. * 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a
  499. * abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */
  500. if (nb_essence_containers != 1) {
  501. MXFOP op = nb_essence_containers ? OP1a : OPAtom;
  502. /* only nag once */
  503. if (!mxf->op)
  504. av_log(mxf->fc, AV_LOG_WARNING,
  505. "\"OPAtom\" with %"PRIu32" ECs - assuming %s\n",
  506. nb_essence_containers,
  507. op == OP1a ? "OP1a" : "OPAtom");
  508. mxf->op = op;
  509. } else
  510. mxf->op = OPAtom;
  511. } else {
  512. av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
  513. mxf->op = OP1a;
  514. }
  515. if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
  516. av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %"PRId32" - guessing ",
  517. partition->kag_size);
  518. if (mxf->op == OPSonyOpt)
  519. partition->kag_size = 512;
  520. else
  521. partition->kag_size = 1;
  522. av_log(mxf->fc, AV_LOG_WARNING, "%"PRId32"\n", partition->kag_size);
  523. }
  524. return 0;
  525. }
  526. static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
  527. {
  528. int err;
  529. if ((err = av_reallocp_array(&mxf->metadata_sets, mxf->metadata_sets_count + 1,
  530. sizeof(*mxf->metadata_sets))) < 0) {
  531. mxf->metadata_sets_count = 0;
  532. return err;
  533. }
  534. mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
  535. mxf->metadata_sets_count++;
  536. return 0;
  537. }
  538. static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  539. {
  540. MXFCryptoContext *cryptocontext = arg;
  541. if (size != 16)
  542. return AVERROR_INVALIDDATA;
  543. if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
  544. avio_read(pb, cryptocontext->source_container_ul, 16);
  545. return 0;
  546. }
  547. static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  548. {
  549. MXFContext *mxf = arg;
  550. switch (tag) {
  551. case 0x1901:
  552. mxf->packages_count = avio_rb32(pb);
  553. if (mxf->packages_count >= UINT_MAX / sizeof(UID))
  554. return AVERROR_INVALIDDATA;
  555. mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));
  556. if (!mxf->packages_refs)
  557. return AVERROR(ENOMEM);
  558. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  559. avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));
  560. break;
  561. }
  562. return 0;
  563. }
  564. static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  565. {
  566. MXFStructuralComponent *source_clip = arg;
  567. switch(tag) {
  568. case 0x0202:
  569. source_clip->duration = avio_rb64(pb);
  570. break;
  571. case 0x1201:
  572. source_clip->start_position = avio_rb64(pb);
  573. break;
  574. case 0x1101:
  575. /* UMID, only get last 16 bytes */
  576. avio_skip(pb, 16);
  577. avio_read(pb, source_clip->source_package_uid, 16);
  578. break;
  579. case 0x1102:
  580. source_clip->source_track_id = avio_rb32(pb);
  581. break;
  582. }
  583. return 0;
  584. }
  585. static int mxf_read_material_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  586. {
  587. MXFPackage *package = arg;
  588. switch(tag) {
  589. case 0x4403:
  590. package->tracks_count = avio_rb32(pb);
  591. if (package->tracks_count >= UINT_MAX / sizeof(UID))
  592. return AVERROR_INVALIDDATA;
  593. package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
  594. if (!package->tracks_refs)
  595. return AVERROR(ENOMEM);
  596. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  597. avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
  598. break;
  599. }
  600. return 0;
  601. }
  602. static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  603. {
  604. MXFTrack *track = arg;
  605. switch(tag) {
  606. case 0x4801:
  607. track->track_id = avio_rb32(pb);
  608. break;
  609. case 0x4804:
  610. avio_read(pb, track->track_number, 4);
  611. break;
  612. case 0x4b01:
  613. track->edit_rate.num = avio_rb32(pb);
  614. track->edit_rate.den = avio_rb32(pb);
  615. break;
  616. case 0x4803:
  617. avio_read(pb, track->sequence_ref, 16);
  618. break;
  619. }
  620. return 0;
  621. }
  622. static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  623. {
  624. MXFSequence *sequence = arg;
  625. switch(tag) {
  626. case 0x0202:
  627. sequence->duration = avio_rb64(pb);
  628. break;
  629. case 0x0201:
  630. avio_read(pb, sequence->data_definition_ul, 16);
  631. break;
  632. case 0x1001:
  633. sequence->structural_components_count = avio_rb32(pb);
  634. if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))
  635. return AVERROR_INVALIDDATA;
  636. sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));
  637. if (!sequence->structural_components_refs)
  638. return AVERROR(ENOMEM);
  639. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  640. avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));
  641. break;
  642. }
  643. return 0;
  644. }
  645. static int mxf_read_source_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  646. {
  647. MXFPackage *package = arg;
  648. switch(tag) {
  649. case 0x4403:
  650. package->tracks_count = avio_rb32(pb);
  651. if (package->tracks_count >= UINT_MAX / sizeof(UID))
  652. return AVERROR_INVALIDDATA;
  653. package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));
  654. if (!package->tracks_refs)
  655. return AVERROR(ENOMEM);
  656. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  657. avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));
  658. break;
  659. case 0x4401:
  660. /* UMID, only get last 16 bytes */
  661. avio_skip(pb, 16);
  662. avio_read(pb, package->package_uid, 16);
  663. break;
  664. case 0x4701:
  665. avio_read(pb, package->descriptor_ref, 16);
  666. break;
  667. }
  668. return 0;
  669. }
  670. static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
  671. {
  672. int i, length;
  673. segment->nb_index_entries = avio_rb32(pb);
  674. if (!segment->nb_index_entries)
  675. return 0;
  676. else if (segment->nb_index_entries < 0 ||
  677. segment->nb_index_entries >
  678. (INT_MAX / sizeof(*segment->stream_offset_entries)))
  679. return AVERROR(ENOMEM);
  680. length = avio_rb32(pb);
  681. segment->temporal_offset_entries = av_mallocz(segment->nb_index_entries *
  682. sizeof(*segment->temporal_offset_entries));
  683. segment->flag_entries = av_mallocz(segment->nb_index_entries *
  684. sizeof(*segment->flag_entries));
  685. segment->stream_offset_entries = av_mallocz(segment->nb_index_entries *
  686. sizeof(*segment->stream_offset_entries));
  687. if (!segment->flag_entries || !segment->stream_offset_entries ||
  688. !segment->temporal_offset_entries) {
  689. av_freep(&segment->flag_entries);
  690. av_freep(&segment->stream_offset_entries);
  691. av_freep(&segment->temporal_offset_entries);
  692. return AVERROR(ENOMEM);
  693. }
  694. for (i = 0; i < segment->nb_index_entries; i++) {
  695. segment->temporal_offset_entries[i] = avio_r8(pb);
  696. avio_r8(pb); /* KeyFrameOffset */
  697. segment->flag_entries[i] = avio_r8(pb);
  698. segment->stream_offset_entries[i] = avio_rb64(pb);
  699. avio_skip(pb, length - 11);
  700. }
  701. return 0;
  702. }
  703. static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  704. {
  705. MXFIndexTableSegment *segment = arg;
  706. switch(tag) {
  707. case 0x3F05:
  708. segment->edit_unit_byte_count = avio_rb32(pb);
  709. av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
  710. break;
  711. case 0x3F06:
  712. segment->index_sid = avio_rb32(pb);
  713. av_dlog(NULL, "IndexSID %d\n", segment->index_sid);
  714. break;
  715. case 0x3F07:
  716. segment->body_sid = avio_rb32(pb);
  717. av_dlog(NULL, "BodySID %d\n", segment->body_sid);
  718. break;
  719. case 0x3F0A:
  720. av_dlog(NULL, "IndexEntryArray found\n");
  721. return mxf_read_index_entry_array(pb, segment);
  722. case 0x3F0B:
  723. segment->index_edit_rate.num = avio_rb32(pb);
  724. segment->index_edit_rate.den = avio_rb32(pb);
  725. av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
  726. segment->index_edit_rate.den);
  727. break;
  728. case 0x3F0C:
  729. segment->index_start_position = avio_rb64(pb);
  730. av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
  731. break;
  732. case 0x3F0D:
  733. segment->index_duration = avio_rb64(pb);
  734. av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);
  735. break;
  736. }
  737. return 0;
  738. }
  739. static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
  740. {
  741. int code, value, ofs = 0;
  742. char layout[16] = {0};
  743. do {
  744. code = avio_r8(pb);
  745. value = avio_r8(pb);
  746. av_dlog(NULL, "pixel layout: code %#x\n", code);
  747. if (ofs < 16) {
  748. layout[ofs++] = code;
  749. layout[ofs++] = value;
  750. }
  751. } while (code != 0); /* SMPTE 377M E.2.46 */
  752. ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
  753. }
  754. static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
  755. {
  756. MXFDescriptor *descriptor = arg;
  757. descriptor->pix_fmt = AV_PIX_FMT_NONE;
  758. switch(tag) {
  759. case 0x3F01:
  760. descriptor->sub_descriptors_count = avio_rb32(pb);
  761. if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
  762. return AVERROR_INVALIDDATA;
  763. descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
  764. if (!descriptor->sub_descriptors_refs)
  765. return AVERROR(ENOMEM);
  766. avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
  767. avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
  768. break;
  769. case 0x3004:
  770. avio_read(pb, descriptor->essence_container_ul, 16);
  771. break;
  772. case 0x3006:
  773. descriptor->linked_track_id = avio_rb32(pb);
  774. break;
  775. case 0x3201: /* PictureEssenceCoding */
  776. avio_read(pb, descriptor->essence_codec_ul, 16);
  777. break;
  778. case 0x3203:
  779. descriptor->width = avio_rb32(pb);
  780. break;
  781. case 0x3202:
  782. descriptor->height = avio_rb32(pb);
  783. break;
  784. case 0x320C:
  785. descriptor->frame_layout = avio_r8(pb);
  786. break;
  787. case 0x320E:
  788. descriptor->aspect_ratio.num = avio_rb32(pb);
  789. descriptor->aspect_ratio.den = avio_rb32(pb);
  790. break;
  791. case 0x3212:
  792. descriptor->field_dominance = avio_r8(pb);
  793. break;
  794. case 0x3301:
  795. descriptor->component_depth = avio_rb32(pb);
  796. break;
  797. case 0x3302:
  798. descriptor->horiz_subsampling = avio_rb32(pb);
  799. break;
  800. case 0x3308:
  801. descriptor->vert_subsampling = avio_rb32(pb);
  802. break;
  803. case 0x3D03:
  804. descriptor->sample_rate.num = avio_rb32(pb);
  805. descriptor->sample_rate.den = avio_rb32(pb);
  806. break;
  807. case 0x3D06: /* SoundEssenceCompression */
  808. avio_read(pb, descriptor->essence_codec_ul, 16);
  809. break;
  810. case 0x3D07:
  811. descriptor->channels = avio_rb32(pb);
  812. break;
  813. case 0x3D01:
  814. descriptor->bits_per_sample = avio_rb32(pb);
  815. break;
  816. case 0x3401:
  817. mxf_read_pixel_layout(pb, descriptor);
  818. break;
  819. default:
  820. /* Private uid used by SONY C0023S01.mxf */
  821. if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
  822. av_free(descriptor->extradata);
  823. descriptor->extradata_size = 0;
  824. descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
  825. if (!descriptor->extradata)
  826. return AVERROR(ENOMEM);
  827. descriptor->extradata_size = size;
  828. avio_read(pb, descriptor->extradata, size);
  829. }
  830. break;
  831. }
  832. return 0;
  833. }
  834. /*
  835. * Match an uid independently of the version byte and up to len common bytes
  836. * Returns: boolean
  837. */
  838. static int mxf_match_uid(const UID key, const UID uid, int len)
  839. {
  840. int i;
  841. for (i = 0; i < len; i++) {
  842. if (i != 7 && key[i] != uid[i])
  843. return 0;
  844. }
  845. return 1;
  846. }
  847. static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
  848. {
  849. while (uls->uid[0]) {
  850. if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
  851. break;
  852. uls++;
  853. }
  854. return uls;
  855. }
  856. static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
  857. {
  858. int i;
  859. if (!strong_ref)
  860. return NULL;
  861. for (i = 0; i < mxf->metadata_sets_count; i++) {
  862. if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
  863. (type == AnyType || mxf->metadata_sets[i]->type == type)) {
  864. return mxf->metadata_sets[i];
  865. }
  866. }
  867. return NULL;
  868. }
  869. static const MXFCodecUL mxf_picture_essence_container_uls[] = {
  870. // video essence container uls
  871. { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MPEG-ES Frame wrapped */
  872. { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, AV_CODEC_ID_DVVIDEO }, /* DV 625 25mbps */
  873. { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14, AV_CODEC_ID_RAWVIDEO }, /* Uncompressed Picture */
  874. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
  875. };
  876. /* EC ULs for intra-only formats */
  877. static const MXFCodecUL mxf_intra_only_essence_container_uls[] = {
  878. { { 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 */
  879. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
  880. };
  881. /* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */
  882. static const MXFCodecUL mxf_intra_only_picture_essence_coding_uls[] = {
  883. { { 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 */
  884. { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, /* JPEG2000 Codestream */
  885. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
  886. };
  887. static const MXFCodecUL mxf_sound_essence_container_uls[] = {
  888. // sound essence container uls
  889. { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, AV_CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */
  890. { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, AV_CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */
  891. { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, AV_CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */
  892. { { 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 */
  893. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
  894. };
  895. static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
  896. {
  897. int i, j, nb_segments = 0;
  898. MXFIndexTableSegment **unsorted_segments;
  899. int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
  900. /* count number of segments, allocate arrays and copy unsorted segments */
  901. for (i = 0; i < mxf->metadata_sets_count; i++)
  902. if (mxf->metadata_sets[i]->type == IndexTableSegment)
  903. nb_segments++;
  904. if (!nb_segments)
  905. return AVERROR_INVALIDDATA;
  906. *sorted_segments = av_mallocz(nb_segments * sizeof(**sorted_segments));
  907. unsorted_segments = av_mallocz(nb_segments * sizeof(*unsorted_segments));
  908. if (!*sorted_segments || !unsorted_segments) {
  909. av_freep(sorted_segments);
  910. av_free(unsorted_segments);
  911. return AVERROR(ENOMEM);
  912. }
  913. for (i = j = 0; i < mxf->metadata_sets_count; i++)
  914. if (mxf->metadata_sets[i]->type == IndexTableSegment)
  915. unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
  916. *nb_sorted_segments = 0;
  917. /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
  918. for (i = 0; i < nb_segments; i++) {
  919. int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
  920. uint64_t best_index_duration = 0;
  921. for (j = 0; j < nb_segments; j++) {
  922. MXFIndexTableSegment *s = unsorted_segments[j];
  923. /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
  924. * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
  925. * If we come across an entry with the same IndexStartPosition but larger IndexDuration, then we'll prefer it over the one we currently have.
  926. */
  927. if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&
  928. (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start ||
  929. (s->index_start_position == best_index_start && s->index_duration > best_index_duration))) {
  930. best = j;
  931. best_body_sid = s->body_sid;
  932. best_index_sid = s->index_sid;
  933. best_index_start = s->index_start_position;
  934. best_index_duration = s->index_duration;
  935. }
  936. }
  937. /* no suitable entry found -> we're done */
  938. if (best == -1)
  939. break;
  940. (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
  941. last_body_sid = best_body_sid;
  942. last_index_sid = best_index_sid;
  943. last_index_start = best_index_start;
  944. }
  945. av_free(unsorted_segments);
  946. return 0;
  947. }
  948. /**
  949. * Computes the absolute file offset of the given essence container offset
  950. */
  951. static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out)
  952. {
  953. int x;
  954. int64_t offset_in = offset; /* for logging */
  955. for (x = 0; x < mxf->partitions_count; x++) {
  956. MXFPartition *p = &mxf->partitions[x];
  957. if (p->body_sid != body_sid)
  958. continue;
  959. if (offset < p->essence_length || !p->essence_length) {
  960. *offset_out = p->essence_offset + offset;
  961. return 0;
  962. }
  963. offset -= p->essence_length;
  964. }
  965. av_log(mxf->fc, AV_LOG_ERROR,
  966. "failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n",
  967. offset_in, body_sid);
  968. return AVERROR_INVALIDDATA;
  969. }
  970. /**
  971. * Returns the end position of the essence container with given BodySID, or zero if unknown
  972. */
  973. static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
  974. {
  975. int x;
  976. int64_t ret = 0;
  977. for (x = 0; x < mxf->partitions_count; x++) {
  978. MXFPartition *p = &mxf->partitions[x];
  979. if (p->body_sid != body_sid)
  980. continue;
  981. if (!p->essence_length)
  982. return 0;
  983. ret = p->essence_offset + p->essence_length;
  984. }
  985. return ret;
  986. }
  987. /* EditUnit -> absolute offset */
  988. static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, int64_t *edit_unit_out, int64_t *offset_out, int nag)
  989. {
  990. int i;
  991. int64_t offset_temp = 0;
  992. for (i = 0; i < index_table->nb_segments; i++) {
  993. MXFIndexTableSegment *s = index_table->segments[i];
  994. edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */
  995. if (edit_unit < s->index_start_position + s->index_duration) {
  996. int64_t index = edit_unit - s->index_start_position;
  997. if (s->edit_unit_byte_count)
  998. offset_temp += s->edit_unit_byte_count * index;
  999. else if (s->nb_index_entries) {
  1000. if (s->nb_index_entries == 2 * s->index_duration + 1)
  1001. index *= 2; /* Avid index */
  1002. if (index < 0 || index >= s->nb_index_entries) {
  1003. av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
  1004. index_table->index_sid, s->index_start_position);
  1005. return AVERROR_INVALIDDATA;
  1006. }
  1007. offset_temp = s->stream_offset_entries[index];
  1008. } else {
  1009. av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
  1010. index_table->index_sid, s->index_start_position);
  1011. return AVERROR_INVALIDDATA;
  1012. }
  1013. if (edit_unit_out)
  1014. *edit_unit_out = edit_unit;
  1015. return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out);
  1016. } else {
  1017. /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
  1018. offset_temp += s->edit_unit_byte_count * s->index_duration;
  1019. }
  1020. }
  1021. if (nag)
  1022. 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);
  1023. return AVERROR_INVALIDDATA;
  1024. }
  1025. static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
  1026. {
  1027. int i, j, x;
  1028. int8_t max_temporal_offset = -128;
  1029. /* first compute how many entries we have */
  1030. for (i = 0; i < index_table->nb_segments; i++) {
  1031. MXFIndexTableSegment *s = index_table->segments[i];
  1032. if (!s->nb_index_entries) {
  1033. index_table->nb_ptses = 0;
  1034. return 0; /* no TemporalOffsets */
  1035. }
  1036. index_table->nb_ptses += s->index_duration;
  1037. }
  1038. /* paranoid check */
  1039. if (index_table->nb_ptses <= 0)
  1040. return 0;
  1041. if (index_table->nb_ptses > INT_MAX / sizeof(AVIndexEntry))
  1042. return AVERROR(ENOMEM);
  1043. index_table->ptses = av_mallocz(index_table->nb_ptses *
  1044. sizeof(int64_t));
  1045. index_table->fake_index = av_mallocz(index_table->nb_ptses *
  1046. sizeof(AVIndexEntry));
  1047. if (!index_table->ptses || !index_table->fake_index) {
  1048. av_freep(&index_table->ptses);
  1049. return AVERROR(ENOMEM);
  1050. }
  1051. /* we may have a few bad TemporalOffsets
  1052. * make sure the corresponding PTSes don't have the bogus value 0 */
  1053. for (x = 0; x < index_table->nb_ptses; x++)
  1054. index_table->ptses[x] = AV_NOPTS_VALUE;
  1055. /**
  1056. * We have this:
  1057. *
  1058. * x TemporalOffset
  1059. * 0: 0
  1060. * 1: 1
  1061. * 2: 1
  1062. * 3: -2
  1063. * 4: 1
  1064. * 5: 1
  1065. * 6: -2
  1066. *
  1067. * We want to transform it into this:
  1068. *
  1069. * x DTS PTS
  1070. * 0: -1 0
  1071. * 1: 0 3
  1072. * 2: 1 1
  1073. * 3: 2 2
  1074. * 4: 3 6
  1075. * 5: 4 4
  1076. * 6: 5 5
  1077. *
  1078. * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
  1079. * then settings mxf->first_dts = -max(TemporalOffset[x]).
  1080. * The latter makes DTS <= PTS.
  1081. */
  1082. for (i = x = 0; i < index_table->nb_segments; i++) {
  1083. MXFIndexTableSegment *s = index_table->segments[i];
  1084. int index_delta = 1;
  1085. int n = s->nb_index_entries;
  1086. if (s->nb_index_entries == 2 * s->index_duration + 1) {
  1087. index_delta = 2; /* Avid index */
  1088. /* ignore the last entry - it's the size of the essence container */
  1089. n--;
  1090. }
  1091. for (j = 0; j < n; j += index_delta, x++) {
  1092. int offset = s->temporal_offset_entries[j] / index_delta;
  1093. int index = x + offset;
  1094. if (x >= index_table->nb_ptses) {
  1095. av_log(mxf->fc, AV_LOG_ERROR,
  1096. "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
  1097. s->nb_index_entries, s->index_duration);
  1098. break;
  1099. }
  1100. index_table->fake_index[x].timestamp = x;
  1101. index_table->fake_index[x].flags = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
  1102. if (index < 0 || index >= index_table->nb_ptses) {
  1103. av_log(mxf->fc, AV_LOG_ERROR,
  1104. "index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
  1105. x, offset, index);
  1106. continue;
  1107. }
  1108. index_table->ptses[index] = x;
  1109. max_temporal_offset = FFMAX(max_temporal_offset, offset);
  1110. }
  1111. }
  1112. index_table->first_dts = -max_temporal_offset;
  1113. return 0;
  1114. }
  1115. /**
  1116. * Sorts and collects index table segments into index tables.
  1117. * Also computes PTSes if possible.
  1118. */
  1119. static int mxf_compute_index_tables(MXFContext *mxf)
  1120. {
  1121. int i, j, k, ret, nb_sorted_segments;
  1122. MXFIndexTableSegment **sorted_segments = NULL;
  1123. if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
  1124. nb_sorted_segments <= 0) {
  1125. av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
  1126. return 0;
  1127. }
  1128. /* sanity check and count unique BodySIDs/IndexSIDs */
  1129. for (i = 0; i < nb_sorted_segments; i++) {
  1130. if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
  1131. mxf->nb_index_tables++;
  1132. else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
  1133. av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
  1134. ret = AVERROR_INVALIDDATA;
  1135. goto finish_decoding_index;
  1136. }
  1137. }
  1138. mxf->index_tables = av_mallocz_array(mxf->nb_index_tables,
  1139. sizeof(*mxf->index_tables));
  1140. if (!mxf->index_tables) {
  1141. av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
  1142. ret = AVERROR(ENOMEM);
  1143. goto finish_decoding_index;
  1144. }
  1145. /* distribute sorted segments to index tables */
  1146. for (i = j = 0; i < nb_sorted_segments; i++) {
  1147. if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
  1148. /* next IndexSID */
  1149. j++;
  1150. }
  1151. mxf->index_tables[j].nb_segments++;
  1152. }
  1153. for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
  1154. MXFIndexTable *t = &mxf->index_tables[j];
  1155. t->segments = av_mallocz_array(t->nb_segments,
  1156. sizeof(*t->segments));
  1157. if (!t->segments) {
  1158. av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment"
  1159. " pointer array\n");
  1160. ret = AVERROR(ENOMEM);
  1161. goto finish_decoding_index;
  1162. }
  1163. if (sorted_segments[i]->index_start_position)
  1164. av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
  1165. sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
  1166. memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
  1167. t->index_sid = sorted_segments[i]->index_sid;
  1168. t->body_sid = sorted_segments[i]->body_sid;
  1169. if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
  1170. goto finish_decoding_index;
  1171. /* fix zero IndexDurations */
  1172. for (k = 0; k < t->nb_segments; k++) {
  1173. if (t->segments[k]->index_duration)
  1174. continue;
  1175. if (t->nb_segments > 1)
  1176. av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
  1177. t->index_sid, k);
  1178. if (mxf->fc->nb_streams <= 0) {
  1179. av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
  1180. break;
  1181. }
  1182. /* assume the first stream's duration is reasonable
  1183. * leave index_duration = 0 on further segments in case we have any (unlikely)
  1184. */
  1185. t->segments[k]->index_duration = mxf->fc->streams[0]->duration;
  1186. break;
  1187. }
  1188. }
  1189. ret = 0;
  1190. finish_decoding_index:
  1191. av_free(sorted_segments);
  1192. return ret;
  1193. }
  1194. static int mxf_is_intra_only(MXFDescriptor *d)
  1195. {
  1196. return mxf_get_codec_ul(mxf_intra_only_essence_container_uls,
  1197. &d->essence_container_ul)->id != AV_CODEC_ID_NONE ||
  1198. mxf_get_codec_ul(mxf_intra_only_picture_essence_coding_uls,
  1199. &d->essence_codec_ul)->id != AV_CODEC_ID_NONE;
  1200. }
  1201. static int mxf_parse_structural_metadata(MXFContext *mxf)
  1202. {
  1203. MXFPackage *material_package = NULL;
  1204. MXFPackage *temp_package = NULL;
  1205. int i, j, k, ret;
  1206. av_dlog(mxf->fc, "metadata sets count %d\n", mxf->metadata_sets_count);
  1207. /* TODO: handle multiple material packages (OP3x) */
  1208. for (i = 0; i < mxf->packages_count; i++) {
  1209. material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
  1210. if (material_package) break;
  1211. }
  1212. if (!material_package) {
  1213. av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
  1214. return AVERROR_INVALIDDATA;
  1215. }
  1216. for (i = 0; i < material_package->tracks_count; i++) {
  1217. MXFPackage *source_package = NULL;
  1218. MXFTrack *material_track = NULL;
  1219. MXFTrack *source_track = NULL;
  1220. MXFTrack *temp_track = NULL;
  1221. MXFDescriptor *descriptor = NULL;
  1222. MXFStructuralComponent *component = NULL;
  1223. UID *essence_container_ul = NULL;
  1224. const MXFCodecUL *codec_ul = NULL;
  1225. const MXFCodecUL *container_ul = NULL;
  1226. const MXFCodecUL *pix_fmt_ul = NULL;
  1227. AVStream *st;
  1228. if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
  1229. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
  1230. continue;
  1231. }
  1232. if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
  1233. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
  1234. continue;
  1235. }
  1236. /* TODO: handle multiple source clips */
  1237. for (j = 0; j < material_track->sequence->structural_components_count; j++) {
  1238. /* TODO: handle timecode component */
  1239. component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], SourceClip);
  1240. if (!component)
  1241. continue;
  1242. for (k = 0; k < mxf->packages_count; k++) {
  1243. temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[k], SourcePackage);
  1244. if (!temp_package)
  1245. continue;
  1246. if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)) {
  1247. source_package = temp_package;
  1248. break;
  1249. }
  1250. }
  1251. if (!source_package) {
  1252. av_dlog(mxf->fc, "material track %d: no corresponding source package found\n", material_track->track_id);
  1253. break;
  1254. }
  1255. for (k = 0; k < source_package->tracks_count; k++) {
  1256. if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
  1257. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
  1258. ret = AVERROR_INVALIDDATA;
  1259. goto fail_and_free;
  1260. }
  1261. if (temp_track->track_id == component->source_track_id) {
  1262. source_track = temp_track;
  1263. break;
  1264. }
  1265. }
  1266. if (!source_track) {
  1267. av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
  1268. break;
  1269. }
  1270. }
  1271. if (!source_track || !component)
  1272. continue;
  1273. if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
  1274. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
  1275. ret = AVERROR_INVALIDDATA;
  1276. goto fail_and_free;
  1277. }
  1278. /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
  1279. * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
  1280. if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
  1281. av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
  1282. continue;
  1283. }
  1284. st = avformat_new_stream(mxf->fc, NULL);
  1285. if (!st) {
  1286. av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
  1287. ret = AVERROR(ENOMEM);
  1288. goto fail_and_free;
  1289. }
  1290. st->id = source_track->track_id;
  1291. st->priv_data = source_track;
  1292. source_track->original_duration = st->duration = component->duration;
  1293. if (st->duration == -1)
  1294. st->duration = AV_NOPTS_VALUE;
  1295. st->start_time = component->start_position;
  1296. if (material_track->edit_rate.num <= 0 ||
  1297. material_track->edit_rate.den <= 0) {
  1298. av_log(mxf->fc, AV_LOG_WARNING,
  1299. "Invalid edit rate (%d/%d) found on stream #%d, "
  1300. "defaulting to 25/1\n",
  1301. material_track->edit_rate.num,
  1302. material_track->edit_rate.den, st->index);
  1303. material_track->edit_rate = (AVRational){25, 1};
  1304. }
  1305. avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
  1306. /* ensure SourceTrack EditRate == MaterialTrack EditRate since only
  1307. * the former is accessible via st->priv_data */
  1308. source_track->edit_rate = material_track->edit_rate;
  1309. PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
  1310. codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
  1311. st->codec->codec_type = codec_ul->id;
  1312. source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
  1313. if (source_package->descriptor) {
  1314. if (source_package->descriptor->type == MultipleDescriptor) {
  1315. for (j = 0; j < source_package->descriptor->sub_descriptors_count; j++) {
  1316. MXFDescriptor *sub_descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor->sub_descriptors_refs[j], Descriptor);
  1317. if (!sub_descriptor) {
  1318. av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
  1319. continue;
  1320. }
  1321. if (sub_descriptor->linked_track_id == source_track->track_id) {
  1322. descriptor = sub_descriptor;
  1323. break;
  1324. }
  1325. }
  1326. } else if (source_package->descriptor->type == Descriptor)
  1327. descriptor = source_package->descriptor;
  1328. }
  1329. if (!descriptor) {
  1330. av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
  1331. continue;
  1332. }
  1333. PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
  1334. PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
  1335. essence_container_ul = &descriptor->essence_container_ul;
  1336. /* HACK: replacing the original key with mxf_encrypted_essence_container
  1337. * is not allowed according to s429-6, try to find correct information anyway */
  1338. if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
  1339. av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
  1340. for (k = 0; k < mxf->metadata_sets_count; k++) {
  1341. MXFMetadataSet *metadata = mxf->metadata_sets[k];
  1342. if (metadata->type == CryptoContext) {
  1343. essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
  1344. break;
  1345. }
  1346. }
  1347. }
  1348. /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
  1349. codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
  1350. st->codec->codec_id = codec_ul->id;
  1351. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1352. source_track->intra_only = mxf_is_intra_only(descriptor);
  1353. container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
  1354. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1355. st->codec->codec_id = container_ul->id;
  1356. st->codec->width = descriptor->width;
  1357. /* Field height, not frame height */
  1358. st->codec->height = descriptor->height;
  1359. switch (descriptor->frame_layout) {
  1360. case SegmentedFrame:
  1361. /* This one is a weird layout I don't fully understand. */
  1362. av_log(mxf->fc, AV_LOG_INFO,
  1363. "SegmentedFrame layout isn't currently supported\n");
  1364. break;
  1365. case FullFrame:
  1366. st->codec->field_order = AV_FIELD_PROGRESSIVE;
  1367. break;
  1368. case OneField:
  1369. /* Every other line is stored and needs to be duplicated. */
  1370. av_log(mxf->fc, AV_LOG_INFO,
  1371. "OneField frame layout isn't currently supported\n");
  1372. break;
  1373. /* The correct thing to do here is fall through, but by
  1374. * breaking we might be able to decode some streams at half
  1375. * the vertical resolution, rather than not al all.
  1376. * It's also for compatibility with the old behavior. */
  1377. case SeparateFields:
  1378. case MixedFields:
  1379. switch (descriptor->field_dominance) {
  1380. case MXF_TFF:
  1381. st->codec->field_order = AV_FIELD_TT;
  1382. break;
  1383. case MXF_BFF:
  1384. st->codec->field_order = AV_FIELD_BB;
  1385. break;
  1386. default:
  1387. avpriv_request_sample(mxf->fc,
  1388. "Field dominance %d support",
  1389. descriptor->field_dominance);
  1390. break;
  1391. }
  1392. /* Turn field height into frame height. */
  1393. st->codec->height *= 2;
  1394. default:
  1395. av_log(mxf->fc, AV_LOG_INFO,
  1396. "Unknown frame layout type: %d\n",
  1397. descriptor->frame_layout);
  1398. }
  1399. if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
  1400. st->codec->pix_fmt = descriptor->pix_fmt;
  1401. if (st->codec->pix_fmt == AV_PIX_FMT_NONE) {
  1402. pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls,
  1403. &descriptor->essence_codec_ul);
  1404. st->codec->pix_fmt = pix_fmt_ul->id;
  1405. if (st->codec->pix_fmt == AV_PIX_FMT_NONE) {
  1406. /* support files created before RP224v10 by defaulting to UYVY422
  1407. if subsampling is 4:2:2 and component depth is 8-bit */
  1408. if (descriptor->horiz_subsampling == 2 &&
  1409. descriptor->vert_subsampling == 1 &&
  1410. descriptor->component_depth == 8) {
  1411. st->codec->pix_fmt = AV_PIX_FMT_UYVY422;
  1412. }
  1413. }
  1414. }
  1415. }
  1416. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1417. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  1418. container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
  1419. if (st->codec->codec_id == AV_CODEC_ID_NONE)
  1420. st->codec->codec_id = container_ul->id;
  1421. st->codec->channels = descriptor->channels;
  1422. st->codec->bits_per_coded_sample = descriptor->bits_per_sample;
  1423. if (descriptor->sample_rate.den > 0) {
  1424. st->codec->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
  1425. avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
  1426. } else {
  1427. av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) "
  1428. "found for stream #%d, time base forced to 1/48000\n",
  1429. descriptor->sample_rate.num, descriptor->sample_rate.den,
  1430. st->index);
  1431. avpriv_set_pts_info(st, 64, 1, 48000);
  1432. }
  1433. /* if duration is set, rescale it from EditRate to SampleRate */
  1434. if (st->duration != AV_NOPTS_VALUE)
  1435. st->duration = av_rescale_q(st->duration,
  1436. av_inv_q(material_track->edit_rate),
  1437. st->time_base);
  1438. /* TODO: implement AV_CODEC_ID_RAWAUDIO */
  1439. if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
  1440. if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
  1441. st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
  1442. else if (descriptor->bits_per_sample == 32)
  1443. st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
  1444. } else if (st->codec->codec_id == AV_CODEC_ID_PCM_S16BE) {
  1445. if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
  1446. st->codec->codec_id = AV_CODEC_ID_PCM_S24BE;
  1447. else if (descriptor->bits_per_sample == 32)
  1448. st->codec->codec_id = AV_CODEC_ID_PCM_S32BE;
  1449. } else if (st->codec->codec_id == AV_CODEC_ID_MP2) {
  1450. st->need_parsing = AVSTREAM_PARSE_FULL;
  1451. }
  1452. }
  1453. if (descriptor->extradata) {
  1454. st->codec->extradata = av_mallocz(descriptor->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1455. if (st->codec->extradata) {
  1456. memcpy(st->codec->extradata, descriptor->extradata, descriptor->extradata_size);
  1457. st->codec->extradata_size = descriptor->extradata_size;
  1458. }
  1459. } else if (st->codec->codec_id == AV_CODEC_ID_H264) {
  1460. ret = ff_generate_avci_extradata(st);
  1461. if (ret < 0)
  1462. return ret;
  1463. }
  1464. if (st->codec->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) {
  1465. /* TODO: decode timestamps */
  1466. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  1467. }
  1468. }
  1469. ret = 0;
  1470. fail_and_free:
  1471. return ret;
  1472. }
  1473. static int mxf_read_utf16_string(AVIOContext *pb, int size, char** str)
  1474. {
  1475. int ret;
  1476. size_t buf_size;
  1477. if (size < 0)
  1478. return AVERROR(EINVAL);
  1479. buf_size = size + size / 2 + 1;
  1480. *str = av_malloc(buf_size);
  1481. if (!*str)
  1482. return AVERROR(ENOMEM);
  1483. if ((ret = avio_get_str16be(pb, size, *str, buf_size)) < 0) {
  1484. av_freep(str);
  1485. return ret;
  1486. }
  1487. return ret;
  1488. }
  1489. static int mxf_uid_to_str(UID uid, char **str)
  1490. {
  1491. int i;
  1492. char *p;
  1493. p = *str = av_mallocz(sizeof(UID) * 2 + 4 + 1);
  1494. if (!p)
  1495. return AVERROR(ENOMEM);
  1496. for (i = 0; i < sizeof(UID); i++) {
  1497. snprintf(p, 2 + 1, "%.2x", uid[i]);
  1498. p += 2;
  1499. if (i == 3 || i == 5 || i == 7 || i == 9) {
  1500. snprintf(p, 1 + 1, "-");
  1501. p++;
  1502. }
  1503. }
  1504. return 0;
  1505. }
  1506. static int mxf_timestamp_to_str(uint64_t timestamp, char **str)
  1507. {
  1508. struct tm time = { 0 };
  1509. time.tm_year = (timestamp >> 48) - 1900;
  1510. time.tm_mon = (timestamp >> 40 & 0xFF) - 1;
  1511. time.tm_mday = (timestamp >> 32 & 0xFF);
  1512. time.tm_hour = (timestamp >> 24 & 0xFF);
  1513. time.tm_min = (timestamp >> 16 & 0xFF);
  1514. time.tm_sec = (timestamp >> 8 & 0xFF);
  1515. /* msvcrt versions of strftime calls the invalid parameter handler
  1516. * (aborting the process if one isn't set) if the parameters are out
  1517. * of range. */
  1518. time.tm_mon = av_clip(time.tm_mon, 0, 11);
  1519. time.tm_mday = av_clip(time.tm_mday, 1, 31);
  1520. time.tm_hour = av_clip(time.tm_hour, 0, 23);
  1521. time.tm_min = av_clip(time.tm_min, 0, 59);
  1522. time.tm_sec = av_clip(time.tm_sec, 0, 59);
  1523. *str = av_mallocz(32);
  1524. if (!*str)
  1525. return AVERROR(ENOMEM);
  1526. strftime(*str, 32, "%Y-%m-%d %H:%M:%S", &time);
  1527. return 0;
  1528. }
  1529. #define SET_STR_METADATA(pb, name, str) do { \
  1530. if ((ret = mxf_read_utf16_string(pb, size, &str)) < 0) \
  1531. return ret; \
  1532. av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
  1533. } while (0)
  1534. #define SET_UID_METADATA(pb, name, var, str) do { \
  1535. avio_read(pb, var, 16); \
  1536. if ((ret = mxf_uid_to_str(var, &str)) < 0) \
  1537. return ret; \
  1538. av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
  1539. } while (0)
  1540. #define SET_TS_METADATA(pb, name, var, str) do { \
  1541. var = avio_rb64(pb); \
  1542. if ((ret = mxf_timestamp_to_str(var, &str)) < 0) \
  1543. return ret; \
  1544. av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
  1545. } while (0)
  1546. static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset)
  1547. {
  1548. MXFContext *mxf = arg;
  1549. AVFormatContext *s = mxf->fc;
  1550. int ret;
  1551. UID uid = { 0 };
  1552. char *str = NULL;
  1553. uint64_t ts;
  1554. switch (tag) {
  1555. case 0x3C01:
  1556. SET_STR_METADATA(pb, "company_name", str);
  1557. break;
  1558. case 0x3C02:
  1559. SET_STR_METADATA(pb, "product_name", str);
  1560. break;
  1561. case 0x3C04:
  1562. SET_STR_METADATA(pb, "product_version", str);
  1563. break;
  1564. case 0x3C05:
  1565. SET_UID_METADATA(pb, "product_uid", uid, str);
  1566. break;
  1567. case 0x3C06:
  1568. SET_TS_METADATA(pb, "modification_date", ts, str);
  1569. break;
  1570. case 0x3C08:
  1571. SET_STR_METADATA(pb, "application_platform", str);
  1572. break;
  1573. case 0x3C09:
  1574. SET_UID_METADATA(pb, "generation_uid", uid, str);
  1575. break;
  1576. case 0x3C0A:
  1577. SET_UID_METADATA(pb, "uid", uid, str);
  1578. break;
  1579. }
  1580. return 0;
  1581. }
  1582. static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
  1583. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
  1584. // { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2f,0x00 }, mxf_read_preface_pack },
  1585. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
  1586. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
  1587. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
  1588. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
  1589. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
  1590. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
  1591. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
  1592. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
  1593. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
  1594. { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
  1595. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x30,0x00 }, mxf_read_identification_metadata },
  1596. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
  1597. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_source_package, sizeof(MXFPackage), SourcePackage },
  1598. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_material_package, sizeof(MXFPackage), MaterialPackage },
  1599. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0F,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
  1600. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
  1601. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
  1602. { { 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 */
  1603. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
  1604. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
  1605. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG 2 Video */
  1606. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
  1607. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
  1608. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
  1609. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
  1610. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
  1611. { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
  1612. { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
  1613. };
  1614. static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
  1615. {
  1616. AVIOContext *pb = mxf->fc->pb;
  1617. MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
  1618. uint64_t klv_end = avio_tell(pb) + klv->length;
  1619. if (!ctx)
  1620. return AVERROR(ENOMEM);
  1621. while (avio_tell(pb) + 4 < klv_end && !pb->eof_reached) {
  1622. int ret;
  1623. int tag = avio_rb16(pb);
  1624. int size = avio_rb16(pb); /* KLV specified by 0x53 */
  1625. uint64_t next = avio_tell(pb) + size;
  1626. UID uid = {0};
  1627. av_dlog(mxf->fc, "local tag %#04x size %d\n", tag, size);
  1628. if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
  1629. av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
  1630. continue;
  1631. }
  1632. if (tag > 0x7FFF) { /* dynamic tag */
  1633. int i;
  1634. for (i = 0; i < mxf->local_tags_count; i++) {
  1635. int local_tag = AV_RB16(mxf->local_tags+i*18);
  1636. if (local_tag == tag) {
  1637. memcpy(uid, mxf->local_tags+i*18+2, 16);
  1638. av_dlog(mxf->fc, "local tag %#04x\n", local_tag);
  1639. PRINT_KEY(mxf->fc, "uid", uid);
  1640. }
  1641. }
  1642. }
  1643. if (ctx_size && tag == 0x3C0A)
  1644. avio_read(pb, ctx->uid, 16);
  1645. else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0)
  1646. return ret;
  1647. /* Accept the 64k local set limit being exceeded (Avid). Don't accept
  1648. * it extending past the end of the KLV though (zzuf5.mxf). */
  1649. if (avio_tell(pb) > klv_end) {
  1650. if (ctx_size)
  1651. av_free(ctx);
  1652. av_log(mxf->fc, AV_LOG_ERROR,
  1653. "local tag %#04x extends past end of local set @ %#"PRIx64"\n",
  1654. tag, klv->offset);
  1655. return AVERROR_INVALIDDATA;
  1656. } else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */
  1657. avio_seek(pb, next, SEEK_SET);
  1658. }
  1659. if (ctx_size) ctx->type = type;
  1660. return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
  1661. }
  1662. /**
  1663. * Seeks to the previous partition, if possible
  1664. * @return <= 0 if we should stop parsing, > 0 if we should keep going
  1665. */
  1666. static int mxf_seek_to_previous_partition(MXFContext *mxf)
  1667. {
  1668. AVIOContext *pb = mxf->fc->pb;
  1669. if (!mxf->current_partition ||
  1670. mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
  1671. return 0; /* we've parsed all partitions */
  1672. /* seek to previous partition */
  1673. avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
  1674. mxf->current_partition = NULL;
  1675. av_dlog(mxf->fc, "seeking to previous partition\n");
  1676. return 1;
  1677. }
  1678. /**
  1679. * Called when essence is encountered
  1680. * @return <= 0 if we should stop parsing, > 0 if we should keep going
  1681. */
  1682. static int mxf_parse_handle_essence(MXFContext *mxf)
  1683. {
  1684. AVIOContext *pb = mxf->fc->pb;
  1685. int64_t ret;
  1686. if (mxf->parsing_backward) {
  1687. return mxf_seek_to_previous_partition(mxf);
  1688. } else {
  1689. uint64_t offset = mxf->footer_partition ? mxf->footer_partition
  1690. : mxf->last_partition;
  1691. if (!offset) {
  1692. av_dlog(mxf->fc, "no last partition\n");
  1693. return 0;
  1694. }
  1695. av_dlog(mxf->fc, "seeking to last partition\n");
  1696. /* remember where we were so we don't end up seeking further back than this */
  1697. mxf->last_forward_tell = avio_tell(pb);
  1698. if (!pb->seekable) {
  1699. av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing last partition\n");
  1700. return -1;
  1701. }
  1702. /* seek to last partition and parse backward */
  1703. if ((ret = avio_seek(pb, mxf->run_in + offset, SEEK_SET)) < 0) {
  1704. av_log(mxf->fc, AV_LOG_ERROR,
  1705. "failed to seek to last partition @ 0x%" PRIx64
  1706. " (%"PRId64") - partial file?\n",
  1707. mxf->run_in + offset, ret);
  1708. return ret;
  1709. }
  1710. mxf->current_partition = NULL;
  1711. mxf->parsing_backward = 1;
  1712. }
  1713. return 1;
  1714. }
  1715. /**
  1716. * Called when the next partition or EOF is encountered
  1717. * @return <= 0 if we should stop parsing, > 0 if we should keep going
  1718. */
  1719. static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
  1720. {
  1721. return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
  1722. }
  1723. /**
  1724. * Figure out the proper offset and length of the essence container
  1725. * in each partition
  1726. */
  1727. static void mxf_compute_essence_containers(MXFContext *mxf)
  1728. {
  1729. int x;
  1730. /* everything is already correct */
  1731. if (mxf->op == OPAtom)
  1732. return;
  1733. for (x = 0; x < mxf->partitions_count; x++) {
  1734. MXFPartition *p = &mxf->partitions[x];
  1735. if (!p->body_sid)
  1736. continue; /* BodySID == 0 -> no essence */
  1737. if (x >= mxf->partitions_count - 1)
  1738. break; /* last partition - can't compute length (and we don't need to) */
  1739. /* essence container spans to the next partition */
  1740. p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
  1741. if (p->essence_length < 0) {
  1742. /* next ThisPartition < essence_offset */
  1743. p->essence_length = 0;
  1744. av_log(mxf->fc, AV_LOG_ERROR,
  1745. "partition %i: bad ThisPartition = %"PRIX64"\n",
  1746. x+1, mxf->partitions[x+1].this_partition);
  1747. }
  1748. }
  1749. }
  1750. static int64_t round_to_kag(int64_t position, int kag_size)
  1751. {
  1752. /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */
  1753. /* NOTE: kag_size may be any integer between 1 - 2^10 */
  1754. int64_t ret = (position / kag_size) * kag_size;
  1755. return ret == position ? ret : ret + kag_size;
  1756. }
  1757. static inline void compute_partition_essence_offset(AVFormatContext *s,
  1758. MXFContext *mxf,
  1759. KLVPacket *klv)
  1760. {
  1761. MXFPartition *cur_part = mxf->current_partition;
  1762. /* for OP1a we compute essence_offset
  1763. * for OPAtom we point essence_offset after the KL
  1764. * (usually op1a_essence_offset + 20 or 25)
  1765. * TODO: for OP1a we could eliminate this entire if statement, always
  1766. * stopping parsing at op1a_essence_offset
  1767. * for OPAtom we still need the actual essence_offset though
  1768. * (the KL's length can vary)
  1769. */
  1770. int64_t op1a_essence_offset =
  1771. round_to_kag(cur_part->this_partition + cur_part->pack_length,
  1772. cur_part->kag_size) +
  1773. round_to_kag(cur_part->header_byte_count, cur_part->kag_size) +
  1774. round_to_kag(cur_part->index_byte_count, cur_part->kag_size);
  1775. if (mxf->op == OPAtom) {
  1776. /* point essence_offset to the actual data
  1777. * OPAtom has all the essence in one big KLV
  1778. */
  1779. cur_part->essence_offset = avio_tell(s->pb);
  1780. cur_part->essence_length = klv->length;
  1781. } else {
  1782. /* NOTE: op1a_essence_offset may be less than to klv.offset
  1783. * (C0023S01.mxf) */
  1784. cur_part->essence_offset = op1a_essence_offset;
  1785. }
  1786. }
  1787. static int is_pcm(enum AVCodecID codec_id)
  1788. {
  1789. /* we only care about "normal" PCM codecs until we get samples */
  1790. return codec_id >= AV_CODEC_ID_PCM_S16LE && codec_id < AV_CODEC_ID_PCM_S24DAUD;
  1791. }
  1792. /**
  1793. * Deal with the case where for some audio atoms EditUnitByteCount is
  1794. * very small (2, 4..). In those cases we should read more than one
  1795. * sample per call to mxf_read_packet().
  1796. */
  1797. static void mxf_handle_small_eubc(AVFormatContext *s)
  1798. {
  1799. MXFContext *mxf = s->priv_data;
  1800. /* assuming non-OPAtom == frame wrapped
  1801. * no sane writer would wrap 2 byte PCM packets with 20 byte headers.. */
  1802. if (mxf->op != OPAtom)
  1803. return;
  1804. /* expect PCM with exactly one index table segment and a small (< 32) EUBC */
  1805. if (s->nb_streams != 1 ||
  1806. s->streams[0]->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
  1807. !is_pcm(s->streams[0]->codec->codec_id) ||
  1808. mxf->nb_index_tables != 1 ||
  1809. mxf->index_tables[0].nb_segments != 1 ||
  1810. mxf->index_tables[0].segments[0]->edit_unit_byte_count >= 32)
  1811. return;
  1812. /* arbitrarily default to 48 kHz PAL audio frame size */
  1813. /* TODO: We could compute this from the ratio between the audio
  1814. * and video edit rates for 48 kHz NTSC we could use the
  1815. * 1802-1802-1802-1802-1801 pattern. */
  1816. mxf->edit_units_per_packet = 1920;
  1817. }
  1818. static void mxf_read_random_index_pack(AVFormatContext *s)
  1819. {
  1820. MXFContext *mxf = s->priv_data;
  1821. uint32_t length;
  1822. int64_t file_size;
  1823. KLVPacket klv;
  1824. if (!s->pb->seekable)
  1825. return;
  1826. file_size = avio_size(s->pb);
  1827. avio_seek(s->pb, file_size - 4, SEEK_SET);
  1828. length = avio_rb32(s->pb);
  1829. if (length <= 32 || length >= FFMIN(file_size, INT_MAX))
  1830. goto end;
  1831. avio_seek(s->pb, file_size - length, SEEK_SET);
  1832. if (klv_read_packet(&klv, s->pb) < 0 ||
  1833. !IS_KLV_KEY(klv.key, mxf_random_index_pack_key) ||
  1834. klv.length != length - 20)
  1835. goto end;
  1836. avio_skip(s->pb, klv.length - 12);
  1837. mxf->last_partition = avio_rb64(s->pb);
  1838. end:
  1839. avio_seek(s->pb, mxf->run_in, SEEK_SET);
  1840. }
  1841. static int mxf_read_header(AVFormatContext *s)
  1842. {
  1843. MXFContext *mxf = s->priv_data;
  1844. KLVPacket klv;
  1845. int64_t essence_offset = 0;
  1846. int ret;
  1847. mxf->last_forward_tell = INT64_MAX;
  1848. mxf->edit_units_per_packet = 1;
  1849. if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
  1850. av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
  1851. return AVERROR_INVALIDDATA;
  1852. }
  1853. avio_seek(s->pb, -14, SEEK_CUR);
  1854. mxf->fc = s;
  1855. mxf->run_in = avio_tell(s->pb);
  1856. mxf_read_random_index_pack(s);
  1857. while (!s->pb->eof_reached) {
  1858. const MXFMetadataReadTableEntry *metadata;
  1859. if (klv_read_packet(&klv, s->pb) < 0) {
  1860. /* EOF - seek to previous partition or stop */
  1861. if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
  1862. break;
  1863. else
  1864. continue;
  1865. }
  1866. PRINT_KEY(s, "read header", klv.key);
  1867. av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
  1868. if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
  1869. IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
  1870. IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||
  1871. IS_KLV_KEY(klv.key, mxf_system_item_key)) {
  1872. if (!mxf->current_partition) {
  1873. av_log(mxf->fc, AV_LOG_ERROR,
  1874. "found essence prior to first PartitionPack\n");
  1875. return AVERROR_INVALIDDATA;
  1876. }
  1877. if (!mxf->current_partition->essence_offset) {
  1878. compute_partition_essence_offset(s, mxf, &klv);
  1879. }
  1880. if (!essence_offset)
  1881. essence_offset = klv.offset;
  1882. /* seek to footer, previous partition or stop */
  1883. if (mxf_parse_handle_essence(mxf) <= 0)
  1884. break;
  1885. continue;
  1886. } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&
  1887. klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {
  1888. /* next partition pack - keep going, seek to previous partition or stop */
  1889. if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
  1890. break;
  1891. else if (mxf->parsing_backward)
  1892. continue;
  1893. /* we're still parsing forward. proceed to parsing this partition pack */
  1894. }
  1895. for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
  1896. if (IS_KLV_KEY(klv.key, metadata->key)) {
  1897. int res;
  1898. if (klv.key[5] == 0x53) {
  1899. res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);
  1900. } else {
  1901. uint64_t next = avio_tell(s->pb) + klv.length;
  1902. res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
  1903. /* only seek forward, else this can loop for a long time */
  1904. if (avio_tell(s->pb) > next) {
  1905. av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
  1906. klv.offset);
  1907. return AVERROR_INVALIDDATA;
  1908. }
  1909. avio_seek(s->pb, next, SEEK_SET);
  1910. }
  1911. if (res < 0) {
  1912. av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
  1913. return res;
  1914. }
  1915. break;
  1916. }
  1917. }
  1918. if (!metadata->read)
  1919. avio_skip(s->pb, klv.length);
  1920. }
  1921. /* FIXME avoid seek */
  1922. if (!essence_offset) {
  1923. av_log(s, AV_LOG_ERROR, "no essence\n");
  1924. return AVERROR_INVALIDDATA;
  1925. }
  1926. avio_seek(s->pb, essence_offset, SEEK_SET);
  1927. mxf_compute_essence_containers(mxf);
  1928. /* we need to do this before computing the index tables
  1929. * to be able to fill in zero IndexDurations with st->duration */
  1930. if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
  1931. return ret;
  1932. if ((ret = mxf_compute_index_tables(mxf)) < 0)
  1933. return ret;
  1934. if (mxf->nb_index_tables > 1) {
  1935. /* TODO: look up which IndexSID to use via EssenceContainerData */
  1936. av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
  1937. mxf->nb_index_tables, mxf->index_tables[0].index_sid);
  1938. } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {
  1939. av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
  1940. return AVERROR_INVALIDDATA;
  1941. }
  1942. mxf_handle_small_eubc(s);
  1943. return 0;
  1944. }
  1945. /**
  1946. * Sets mxf->current_edit_unit based on what offset we're currently at.
  1947. * @return next_ofs if OK, <0 on error
  1948. */
  1949. static int64_t mxf_set_current_edit_unit(MXFContext *mxf, int64_t current_offset)
  1950. {
  1951. int64_t last_ofs = -1, next_ofs = -1;
  1952. MXFIndexTable *t = &mxf->index_tables[0];
  1953. /* this is called from the OP1a demuxing logic, which means there
  1954. * may be no index tables */
  1955. if (mxf->nb_index_tables <= 0)
  1956. return -1;
  1957. /* find mxf->current_edit_unit so that the next edit unit starts ahead
  1958. * of current_offset */
  1959. while (mxf->current_edit_unit >= 0) {
  1960. if (mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1,
  1961. NULL, &next_ofs, 0) < 0)
  1962. return -1;
  1963. if (next_ofs <= last_ofs) {
  1964. /* large next_ofs didn't change or current_edit_unit wrapped
  1965. * around this fixes the infinite loop on zzuf3.mxf */
  1966. av_log(mxf->fc, AV_LOG_ERROR,
  1967. "next_ofs didn't change. not deriving packet timestamps\n");
  1968. return -1;
  1969. }
  1970. if (next_ofs > current_offset)
  1971. break;
  1972. last_ofs = next_ofs;
  1973. mxf->current_edit_unit++;
  1974. }
  1975. /* not checking mxf->current_edit_unit >= t->nb_ptses here since CBR files
  1976. * may lack IndexEntryArrays */
  1977. if (mxf->current_edit_unit < 0)
  1978. return -1;
  1979. return next_ofs;
  1980. }
  1981. static int mxf_compute_sample_count(MXFContext *mxf, int stream_index,
  1982. uint64_t *sample_count)
  1983. {
  1984. int i, total = 0, size = 0;
  1985. AVStream *st = mxf->fc->streams[stream_index];
  1986. MXFTrack *track = st->priv_data;
  1987. AVRational time_base = av_inv_q(track->edit_rate);
  1988. AVRational sample_rate = av_inv_q(st->time_base);
  1989. const MXFSamplesPerFrame *spf = NULL;
  1990. if ((sample_rate.num / sample_rate.den) == 48000)
  1991. spf = ff_mxf_get_samples_per_frame(mxf->fc, time_base);
  1992. if (!spf) {
  1993. int remainder = (sample_rate.num * time_base.num) %
  1994. (time_base.den * sample_rate.den);
  1995. *sample_count = av_q2d(av_mul_q((AVRational){mxf->current_edit_unit, 1},
  1996. av_mul_q(sample_rate, time_base)));
  1997. if (remainder)
  1998. av_log(mxf->fc, AV_LOG_WARNING,
  1999. "seeking detected on stream #%d with time base (%d/%d) and "
  2000. "sample rate (%d/%d), audio pts won't be accurate.\n",
  2001. stream_index, time_base.num, time_base.den,
  2002. sample_rate.num, sample_rate.den);
  2003. return 0;
  2004. }
  2005. while (spf->samples_per_frame[size]) {
  2006. total += spf->samples_per_frame[size];
  2007. size++;
  2008. }
  2009. if (!size)
  2010. return 0;
  2011. *sample_count = (mxf->current_edit_unit / size) * (uint64_t)total;
  2012. for (i = 0; i < mxf->current_edit_unit % size; i++) {
  2013. *sample_count += spf->samples_per_frame[i];
  2014. }
  2015. return 0;
  2016. }
  2017. static int mxf_set_audio_pts(MXFContext *mxf, AVCodecContext *codec,
  2018. AVPacket *pkt)
  2019. {
  2020. MXFTrack *track = mxf->fc->streams[pkt->stream_index]->priv_data;
  2021. int64_t bits_per_sample = av_get_bits_per_sample(codec->codec_id);
  2022. pkt->pts = track->sample_count;
  2023. if (codec->channels <= 0 || codec->channels * bits_per_sample < 8)
  2024. return AVERROR_INVALIDDATA;
  2025. track->sample_count += pkt->size / (codec->channels * bits_per_sample / 8);
  2026. return 0;
  2027. }
  2028. static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
  2029. {
  2030. KLVPacket klv;
  2031. MXFContext *mxf = s->priv_data;
  2032. int ret;
  2033. while (!s->pb->eof_reached) {
  2034. if ((ret = klv_read_packet(&klv, s->pb)) < 0)
  2035. return ret;
  2036. PRINT_KEY(s, "read packet", klv.key);
  2037. av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
  2038. if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
  2039. ret = mxf_decrypt_triplet(s, pkt, &klv);
  2040. if (ret < 0) {
  2041. av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
  2042. return ret;
  2043. }
  2044. return 0;
  2045. }
  2046. if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
  2047. IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
  2048. int index = mxf_get_stream_index(s, &klv);
  2049. int64_t next_ofs, next_klv;
  2050. AVStream *st;
  2051. MXFTrack *track;
  2052. AVCodecContext *codec;
  2053. if (index < 0) {
  2054. av_log(s, AV_LOG_ERROR,
  2055. "error getting stream index %"PRIu32"\n",
  2056. AV_RB32(klv.key + 12));
  2057. goto skip;
  2058. }
  2059. st = s->streams[index];
  2060. track = st->priv_data;
  2061. if (s->streams[index]->discard == AVDISCARD_ALL)
  2062. goto skip;
  2063. next_klv = avio_tell(s->pb) + klv.length;
  2064. next_ofs = mxf_set_current_edit_unit(mxf, klv.offset);
  2065. if (next_ofs >= 0 && next_klv > next_ofs) {
  2066. /* if this check is hit then it's possible OPAtom was treated
  2067. * as OP1a truncate the packet since it's probably very large
  2068. * (>2 GiB is common) */
  2069. avpriv_request_sample(s,
  2070. "OPAtom misinterpreted as OP1a?"
  2071. "KLV for edit unit %i extending into "
  2072. "next edit unit",
  2073. mxf->current_edit_unit);
  2074. klv.length = next_ofs - avio_tell(s->pb);
  2075. }
  2076. /* check for 8 channels AES3 element */
  2077. if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
  2078. ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index],
  2079. pkt, klv.length);
  2080. if (ret < 0) {
  2081. av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
  2082. return ret;
  2083. }
  2084. } else {
  2085. ret = av_get_packet(s->pb, pkt, klv.length);
  2086. if (ret < 0)
  2087. return ret;
  2088. }
  2089. pkt->stream_index = index;
  2090. pkt->pos = klv.offset;
  2091. codec = s->streams[index]->codec;
  2092. if (codec->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) {
  2093. /* mxf->current_edit_unit good - see if we have an
  2094. * index table to derive timestamps from */
  2095. MXFIndexTable *t = &mxf->index_tables[0];
  2096. if (mxf->nb_index_tables >= 1 &&
  2097. mxf->current_edit_unit < t->nb_ptses) {
  2098. pkt->dts = mxf->current_edit_unit + t->first_dts;
  2099. pkt->pts = t->ptses[mxf->current_edit_unit];
  2100. } else if (track->intra_only) {
  2101. /* intra-only -> PTS = EditUnit.
  2102. * let utils.c figure out DTS since it can be
  2103. * < PTS if low_delay = 0 (Sony IMX30) */
  2104. pkt->pts = mxf->current_edit_unit;
  2105. }
  2106. } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  2107. ret = mxf_set_audio_pts(mxf, codec, pkt);
  2108. if (ret < 0)
  2109. return ret;
  2110. }
  2111. /* seek for truncated packets */
  2112. avio_seek(s->pb, next_klv, SEEK_SET);
  2113. return 0;
  2114. } else
  2115. skip:
  2116. avio_skip(s->pb, klv.length);
  2117. }
  2118. return AVERROR_EOF;
  2119. }
  2120. static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
  2121. {
  2122. MXFContext *mxf = s->priv_data;
  2123. int ret, size;
  2124. int64_t ret64, pos, next_pos;
  2125. AVStream *st;
  2126. MXFIndexTable *t;
  2127. int edit_units;
  2128. if (mxf->op != OPAtom)
  2129. return mxf_read_packet_old(s, pkt);
  2130. /* OPAtom - clip wrapped demuxing */
  2131. /* NOTE: mxf_read_header() makes sure nb_index_tables > 0 for OPAtom */
  2132. st = s->streams[0];
  2133. t = &mxf->index_tables[0];
  2134. if (mxf->current_edit_unit >= st->duration)
  2135. return AVERROR_EOF;
  2136. edit_units = FFMIN(mxf->edit_units_per_packet, st->duration - mxf->current_edit_unit);
  2137. if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit, NULL, &pos, 1)) < 0)
  2138. return ret;
  2139. /* compute size by finding the next edit unit or the end of the essence container
  2140. * not pretty, but it works */
  2141. if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + edit_units, NULL, &next_pos, 0)) < 0 &&
  2142. (next_pos = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
  2143. av_log(s, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
  2144. return AVERROR_INVALIDDATA;
  2145. }
  2146. if ((size = next_pos - pos) <= 0) {
  2147. av_log(s, AV_LOG_ERROR, "bad size: %i\n", size);
  2148. return AVERROR_INVALIDDATA;
  2149. }
  2150. if ((ret64 = avio_seek(s->pb, pos, SEEK_SET)) < 0)
  2151. return ret64;
  2152. if ((ret = av_get_packet(s->pb, pkt, size)) != size)
  2153. return ret < 0 ? ret : AVERROR_EOF;
  2154. pkt->stream_index = 0;
  2155. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses &&
  2156. mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) {
  2157. pkt->dts = mxf->current_edit_unit + t->first_dts;
  2158. pkt->pts = t->ptses[mxf->current_edit_unit];
  2159. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  2160. int ret = mxf_set_audio_pts(mxf, st->codec, pkt);
  2161. if (ret < 0)
  2162. return ret;
  2163. }
  2164. mxf->current_edit_unit += edit_units;
  2165. return 0;
  2166. }
  2167. static int mxf_read_close(AVFormatContext *s)
  2168. {
  2169. MXFContext *mxf = s->priv_data;
  2170. MXFIndexTableSegment *seg;
  2171. int i;
  2172. av_freep(&mxf->packages_refs);
  2173. for (i = 0; i < s->nb_streams; i++)
  2174. s->streams[i]->priv_data = NULL;
  2175. for (i = 0; i < mxf->metadata_sets_count; i++) {
  2176. switch (mxf->metadata_sets[i]->type) {
  2177. case Descriptor:
  2178. av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->extradata);
  2179. break;
  2180. case MultipleDescriptor:
  2181. av_freep(&((MXFDescriptor *)mxf->metadata_sets[i])->sub_descriptors_refs);
  2182. break;
  2183. case Sequence:
  2184. av_freep(&((MXFSequence *)mxf->metadata_sets[i])->structural_components_refs);
  2185. break;
  2186. case SourcePackage:
  2187. case MaterialPackage:
  2188. av_freep(&((MXFPackage *)mxf->metadata_sets[i])->tracks_refs);
  2189. break;
  2190. case IndexTableSegment:
  2191. seg = (MXFIndexTableSegment *)mxf->metadata_sets[i];
  2192. av_freep(&seg->temporal_offset_entries);
  2193. av_freep(&seg->flag_entries);
  2194. av_freep(&seg->stream_offset_entries);
  2195. break;
  2196. default:
  2197. break;
  2198. }
  2199. av_freep(&mxf->metadata_sets[i]);
  2200. }
  2201. av_freep(&mxf->partitions);
  2202. av_freep(&mxf->metadata_sets);
  2203. av_freep(&mxf->aesc);
  2204. av_freep(&mxf->local_tags);
  2205. for (i = 0; i < mxf->nb_index_tables; i++) {
  2206. av_freep(&mxf->index_tables[i].segments);
  2207. av_freep(&mxf->index_tables[i].ptses);
  2208. av_freep(&mxf->index_tables[i].fake_index);
  2209. }
  2210. av_freep(&mxf->index_tables);
  2211. return 0;
  2212. }
  2213. static int mxf_probe(AVProbeData *p) {
  2214. uint8_t *bufp = p->buf;
  2215. uint8_t *end = p->buf + p->buf_size;
  2216. if (p->buf_size < sizeof(mxf_header_partition_pack_key))
  2217. return 0;
  2218. /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
  2219. end -= sizeof(mxf_header_partition_pack_key);
  2220. for (; bufp < end; bufp++) {
  2221. if (IS_KLV_KEY(bufp, mxf_header_partition_pack_key))
  2222. return AVPROBE_SCORE_MAX;
  2223. }
  2224. return 0;
  2225. }
  2226. /* rudimentary byte seek */
  2227. /* XXX: use MXF Index */
  2228. static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  2229. {
  2230. AVStream *st = s->streams[stream_index];
  2231. int64_t seconds;
  2232. MXFContext* mxf = s->priv_data;
  2233. int64_t seekpos;
  2234. int i, ret;
  2235. MXFIndexTable *t;
  2236. MXFTrack *source_track = st->priv_data;
  2237. /* if audio then truncate sample_time to EditRate */
  2238. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  2239. sample_time = av_rescale_q(sample_time, st->time_base,
  2240. av_inv_q(source_track->edit_rate));
  2241. if (mxf->nb_index_tables <= 0) {
  2242. if (!s->bit_rate)
  2243. return AVERROR_INVALIDDATA;
  2244. if (sample_time < 0)
  2245. sample_time = 0;
  2246. seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
  2247. seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);
  2248. if (seekpos < 0)
  2249. return seekpos;
  2250. ff_update_cur_dts(s, st, sample_time);
  2251. mxf->current_edit_unit = sample_time;
  2252. } else {
  2253. t = &mxf->index_tables[0];
  2254. /* clamp above zero, else ff_index_search_timestamp() returns negative
  2255. * this also means we allow seeking before the start */
  2256. sample_time = FFMAX(sample_time, 0);
  2257. if (t->fake_index) {
  2258. /* behave as if we have a proper index */
  2259. if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
  2260. return sample_time;
  2261. } else {
  2262. /* no IndexEntryArray (one or more CBR segments)
  2263. * make sure we don't seek past the end */
  2264. sample_time = FFMIN(sample_time, source_track->original_duration - 1);
  2265. }
  2266. if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) << 0)
  2267. return ret;
  2268. ff_update_cur_dts(s, st, sample_time);
  2269. mxf->current_edit_unit = sample_time;
  2270. avio_seek(s->pb, seekpos, SEEK_SET);
  2271. }
  2272. // Update all tracks sample count
  2273. for (i = 0; i < s->nb_streams; i++) {
  2274. AVStream *cur_st = s->streams[i];
  2275. MXFTrack *cur_track = cur_st->priv_data;
  2276. uint64_t current_sample_count = 0;
  2277. if (cur_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  2278. ret = mxf_compute_sample_count(mxf, i, &current_sample_count);
  2279. if (ret < 0)
  2280. return ret;
  2281. cur_track->sample_count = current_sample_count;
  2282. }
  2283. }
  2284. return 0;
  2285. }
  2286. AVInputFormat ff_mxf_demuxer = {
  2287. .name = "mxf",
  2288. .long_name = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
  2289. .priv_data_size = sizeof(MXFContext),
  2290. .read_probe = mxf_probe,
  2291. .read_header = mxf_read_header,
  2292. .read_packet = mxf_read_packet,
  2293. .read_close = mxf_read_close,
  2294. .read_seek = mxf_read_seek,
  2295. };