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.

2257 lines
85KB

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