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.

2588 lines
96KB

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