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.

2652 lines
100KB

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