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.

2749 lines
88KB

  1. /*
  2. * Matroska file demuxer (no muxer yet)
  3. * Copyright (c) 2003-2004 The ffmpeg Project
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file matroskadec.c
  23. * Matroska file demuxer
  24. * by Ronald Bultje <rbultje@ronald.bitfreak.net>
  25. * with a little help from Moritz Bunkus <moritz@bunkus.org>
  26. * Specs available on the matroska project page:
  27. * http://www.matroska.org/.
  28. */
  29. #include "avformat.h"
  30. /* For codec_get_id(). */
  31. #include "riff.h"
  32. #include "intfloat_readwrite.h"
  33. #include "matroska.h"
  34. typedef struct Track {
  35. MatroskaTrackType type;
  36. /* Unique track number and track ID. stream_index is the index that
  37. * the calling app uses for this track. */
  38. uint32_t num;
  39. uint32_t uid;
  40. int stream_index;
  41. char *name;
  42. char language[4];
  43. char *codec_id;
  44. char *codec_name;
  45. unsigned char *codec_priv;
  46. int codec_priv_size;
  47. uint64_t default_duration;
  48. MatroskaTrackFlags flags;
  49. } MatroskaTrack;
  50. typedef struct MatroskaVideoTrack {
  51. MatroskaTrack track;
  52. int pixel_width;
  53. int pixel_height;
  54. int display_width;
  55. int display_height;
  56. uint32_t fourcc;
  57. MatroskaAspectRatioMode ar_mode;
  58. MatroskaEyeMode eye_mode;
  59. //..
  60. } MatroskaVideoTrack;
  61. typedef struct MatroskaAudioTrack {
  62. MatroskaTrack track;
  63. int channels;
  64. int bitdepth;
  65. int internal_samplerate;
  66. int samplerate;
  67. int block_align;
  68. /* real audio header */
  69. int coded_framesize;
  70. int sub_packet_h;
  71. int frame_size;
  72. int sub_packet_size;
  73. int sub_packet_cnt;
  74. int pkt_cnt;
  75. uint8_t *buf;
  76. //..
  77. } MatroskaAudioTrack;
  78. typedef struct MatroskaSubtitleTrack {
  79. MatroskaTrack track;
  80. int ass;
  81. //..
  82. } MatroskaSubtitleTrack;
  83. #define MAX_TRACK_SIZE (FFMAX(FFMAX(sizeof(MatroskaVideoTrack), \
  84. sizeof(MatroskaAudioTrack)), \
  85. sizeof(MatroskaSubtitleTrack)))
  86. typedef struct MatroskaLevel {
  87. uint64_t start;
  88. uint64_t length;
  89. } MatroskaLevel;
  90. typedef struct MatroskaDemuxIndex {
  91. uint64_t pos; /* of the corresponding *cluster*! */
  92. uint16_t track; /* reference to 'num' */
  93. uint64_t time; /* in nanoseconds */
  94. } MatroskaDemuxIndex;
  95. typedef struct MatroskaDemuxContext {
  96. AVFormatContext *ctx;
  97. /* ebml stuff */
  98. int num_levels;
  99. MatroskaLevel levels[EBML_MAX_DEPTH];
  100. int level_up;
  101. /* matroska stuff */
  102. char *writing_app;
  103. char *muxing_app;
  104. int64_t created;
  105. /* timescale in the file */
  106. int64_t time_scale;
  107. /* num_streams is the number of streams that av_new_stream() was called
  108. * for ( = that are available to the calling program). */
  109. int num_tracks;
  110. int num_streams;
  111. MatroskaTrack *tracks[MAX_STREAMS];
  112. /* cache for ID peeking */
  113. uint32_t peek_id;
  114. /* byte position of the segment inside the stream */
  115. offset_t segment_start;
  116. /* The packet queue. */
  117. AVPacket **packets;
  118. int num_packets;
  119. /* have we already parse metadata/cues/clusters? */
  120. int metadata_parsed;
  121. int index_parsed;
  122. int done;
  123. /* The index for seeking. */
  124. int num_indexes;
  125. MatroskaDemuxIndex *index;
  126. /* What to skip before effectively reading a packet. */
  127. int skip_to_keyframe;
  128. AVStream *skip_to_stream;
  129. } MatroskaDemuxContext;
  130. /*
  131. * The first few functions handle EBML file parsing. The rest
  132. * is the document interpretation. Matroska really just is a
  133. * EBML file.
  134. */
  135. /*
  136. * Return: the amount of levels in the hierarchy that the
  137. * current element lies higher than the previous one.
  138. * The opposite isn't done - that's auto-done using master
  139. * element reading.
  140. */
  141. static int
  142. ebml_read_element_level_up (MatroskaDemuxContext *matroska)
  143. {
  144. ByteIOContext *pb = &matroska->ctx->pb;
  145. offset_t pos = url_ftell(pb);
  146. int num = 0;
  147. while (matroska->num_levels > 0) {
  148. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  149. if (pos >= level->start + level->length) {
  150. matroska->num_levels--;
  151. num++;
  152. } else {
  153. break;
  154. }
  155. }
  156. return num;
  157. }
  158. /*
  159. * Read: an "EBML number", which is defined as a variable-length
  160. * array of bytes. The first byte indicates the length by giving a
  161. * number of 0-bits followed by a one. The position of the first
  162. * "one" bit inside the first byte indicates the length of this
  163. * number.
  164. * Returns: num. of bytes read. < 0 on error.
  165. */
  166. static int
  167. ebml_read_num (MatroskaDemuxContext *matroska,
  168. int max_size,
  169. uint64_t *number)
  170. {
  171. ByteIOContext *pb = &matroska->ctx->pb;
  172. int len_mask = 0x80, read = 1, n = 1;
  173. int64_t total = 0;
  174. /* the first byte tells us the length in bytes - get_byte() can normally
  175. * return 0, but since that's not a valid first ebmlID byte, we can
  176. * use it safely here to catch EOS. */
  177. if (!(total = get_byte(pb))) {
  178. /* we might encounter EOS here */
  179. if (!url_feof(pb)) {
  180. offset_t pos = url_ftell(pb);
  181. av_log(matroska->ctx, AV_LOG_ERROR,
  182. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  183. pos, pos);
  184. }
  185. return AVERROR(EIO); /* EOS or actual I/O error */
  186. }
  187. /* get the length of the EBML number */
  188. while (read <= max_size && !(total & len_mask)) {
  189. read++;
  190. len_mask >>= 1;
  191. }
  192. if (read > max_size) {
  193. offset_t pos = url_ftell(pb) - 1;
  194. av_log(matroska->ctx, AV_LOG_ERROR,
  195. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  196. (uint8_t) total, pos, pos);
  197. return AVERROR_INVALIDDATA;
  198. }
  199. /* read out length */
  200. total &= ~len_mask;
  201. while (n++ < read)
  202. total = (total << 8) | get_byte(pb);
  203. *number = total;
  204. return read;
  205. }
  206. /*
  207. * Read: the element content data ID.
  208. * Return: the number of bytes read or < 0 on error.
  209. */
  210. static int
  211. ebml_read_element_id (MatroskaDemuxContext *matroska,
  212. uint32_t *id,
  213. int *level_up)
  214. {
  215. int read;
  216. uint64_t total;
  217. /* if we re-call this, use our cached ID */
  218. if (matroska->peek_id != 0) {
  219. if (level_up)
  220. *level_up = 0;
  221. *id = matroska->peek_id;
  222. return 0;
  223. }
  224. /* read out the "EBML number", include tag in ID */
  225. if ((read = ebml_read_num(matroska, 4, &total)) < 0)
  226. return read;
  227. *id = matroska->peek_id = total | (1 << (read * 7));
  228. /* level tracking */
  229. if (level_up)
  230. *level_up = ebml_read_element_level_up(matroska);
  231. return read;
  232. }
  233. /*
  234. * Read: element content length.
  235. * Return: the number of bytes read or < 0 on error.
  236. */
  237. static int
  238. ebml_read_element_length (MatroskaDemuxContext *matroska,
  239. uint64_t *length)
  240. {
  241. /* clear cache since we're now beyond that data point */
  242. matroska->peek_id = 0;
  243. /* read out the "EBML number", include tag in ID */
  244. return ebml_read_num(matroska, 8, length);
  245. }
  246. /*
  247. * Return: the ID of the next element, or 0 on error.
  248. * Level_up contains the amount of levels that this
  249. * next element lies higher than the previous one.
  250. */
  251. static uint32_t
  252. ebml_peek_id (MatroskaDemuxContext *matroska,
  253. int *level_up)
  254. {
  255. uint32_t id;
  256. if (ebml_read_element_id(matroska, &id, level_up) < 0)
  257. return 0;
  258. return id;
  259. }
  260. /*
  261. * Seek to a given offset.
  262. * 0 is success, -1 is failure.
  263. */
  264. static int
  265. ebml_read_seek (MatroskaDemuxContext *matroska,
  266. offset_t offset)
  267. {
  268. ByteIOContext *pb = &matroska->ctx->pb;
  269. /* clear ID cache, if any */
  270. matroska->peek_id = 0;
  271. return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
  272. }
  273. /*
  274. * Skip the next element.
  275. * 0 is success, -1 is failure.
  276. */
  277. static int
  278. ebml_read_skip (MatroskaDemuxContext *matroska)
  279. {
  280. ByteIOContext *pb = &matroska->ctx->pb;
  281. uint32_t id;
  282. uint64_t length;
  283. int res;
  284. if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
  285. (res = ebml_read_element_length(matroska, &length)) < 0)
  286. return res;
  287. url_fskip(pb, length);
  288. return 0;
  289. }
  290. /*
  291. * Read the next element as an unsigned int.
  292. * 0 is success, < 0 is failure.
  293. */
  294. static int
  295. ebml_read_uint (MatroskaDemuxContext *matroska,
  296. uint32_t *id,
  297. uint64_t *num)
  298. {
  299. ByteIOContext *pb = &matroska->ctx->pb;
  300. int n = 0, size, res;
  301. uint64_t rlength;
  302. if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
  303. (res = ebml_read_element_length(matroska, &rlength)) < 0)
  304. return res;
  305. size = rlength;
  306. if (size < 1 || size > 8) {
  307. offset_t pos = url_ftell(pb);
  308. av_log(matroska->ctx, AV_LOG_ERROR,
  309. "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
  310. size, pos, pos);
  311. return AVERROR_INVALIDDATA;
  312. }
  313. /* big-endian ordening; build up number */
  314. *num = 0;
  315. while (n++ < size)
  316. *num = (*num << 8) | get_byte(pb);
  317. return 0;
  318. }
  319. /*
  320. * Read the next element as a signed int.
  321. * 0 is success, < 0 is failure.
  322. */
  323. static int
  324. ebml_read_sint (MatroskaDemuxContext *matroska,
  325. uint32_t *id,
  326. int64_t *num)
  327. {
  328. ByteIOContext *pb = &matroska->ctx->pb;
  329. int size, n = 1, negative = 0, res;
  330. uint64_t rlength;
  331. if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
  332. (res = ebml_read_element_length(matroska, &rlength)) < 0)
  333. return res;
  334. size = rlength;
  335. if (size < 1 || size > 8) {
  336. offset_t pos = url_ftell(pb);
  337. av_log(matroska->ctx, AV_LOG_ERROR,
  338. "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
  339. size, pos, pos);
  340. return AVERROR_INVALIDDATA;
  341. }
  342. if ((*num = get_byte(pb)) & 0x80) {
  343. negative = 1;
  344. *num &= ~0x80;
  345. }
  346. while (n++ < size)
  347. *num = (*num << 8) | get_byte(pb);
  348. /* make signed */
  349. if (negative)
  350. *num = *num - (1LL << ((8 * size) - 1));
  351. return 0;
  352. }
  353. /*
  354. * Read the next element as a float.
  355. * 0 is success, < 0 is failure.
  356. */
  357. static int
  358. ebml_read_float (MatroskaDemuxContext *matroska,
  359. uint32_t *id,
  360. double *num)
  361. {
  362. ByteIOContext *pb = &matroska->ctx->pb;
  363. int size, res;
  364. uint64_t rlength;
  365. if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
  366. (res = ebml_read_element_length(matroska, &rlength)) < 0)
  367. return res;
  368. size = rlength;
  369. if (size == 4) {
  370. *num= av_int2flt(get_be32(pb));
  371. } else if(size==8){
  372. *num= av_int2dbl(get_be64(pb));
  373. } else{
  374. offset_t pos = url_ftell(pb);
  375. av_log(matroska->ctx, AV_LOG_ERROR,
  376. "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
  377. size, pos, pos);
  378. return AVERROR_INVALIDDATA;
  379. }
  380. return 0;
  381. }
  382. /*
  383. * Read the next element as an ASCII string.
  384. * 0 is success, < 0 is failure.
  385. */
  386. static int
  387. ebml_read_ascii (MatroskaDemuxContext *matroska,
  388. uint32_t *id,
  389. char **str)
  390. {
  391. ByteIOContext *pb = &matroska->ctx->pb;
  392. int size, res;
  393. uint64_t rlength;
  394. if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
  395. (res = ebml_read_element_length(matroska, &rlength)) < 0)
  396. return res;
  397. size = rlength;
  398. /* ebml strings are usually not 0-terminated, so we allocate one
  399. * byte more, read the string and NULL-terminate it ourselves. */
  400. if (size < 0 || !(*str = av_malloc(size + 1))) {
  401. av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
  402. return AVERROR(ENOMEM);
  403. }
  404. if (get_buffer(pb, (uint8_t *) *str, size) != size) {
  405. offset_t pos = url_ftell(pb);
  406. av_log(matroska->ctx, AV_LOG_ERROR,
  407. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
  408. return AVERROR(EIO);
  409. }
  410. (*str)[size] = '\0';
  411. return 0;
  412. }
  413. /*
  414. * Read the next element as a UTF-8 string.
  415. * 0 is success, < 0 is failure.
  416. */
  417. static int
  418. ebml_read_utf8 (MatroskaDemuxContext *matroska,
  419. uint32_t *id,
  420. char **str)
  421. {
  422. return ebml_read_ascii(matroska, id, str);
  423. }
  424. /*
  425. * Read the next element as a date (nanoseconds since 1/1/2000).
  426. * 0 is success, < 0 is failure.
  427. */
  428. static int
  429. ebml_read_date (MatroskaDemuxContext *matroska,
  430. uint32_t *id,
  431. int64_t *date)
  432. {
  433. return ebml_read_sint(matroska, id, date);
  434. }
  435. /*
  436. * Read the next element, but only the header. The contents
  437. * are supposed to be sub-elements which can be read separately.
  438. * 0 is success, < 0 is failure.
  439. */
  440. static int
  441. ebml_read_master (MatroskaDemuxContext *matroska,
  442. uint32_t *id)
  443. {
  444. ByteIOContext *pb = &matroska->ctx->pb;
  445. uint64_t length;
  446. MatroskaLevel *level;
  447. int res;
  448. if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
  449. (res = ebml_read_element_length(matroska, &length)) < 0)
  450. return res;
  451. /* protect... (Heaven forbids that the '>' is true) */
  452. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  453. av_log(matroska->ctx, AV_LOG_ERROR,
  454. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  455. return AVERROR(ENOSYS);
  456. }
  457. /* remember level */
  458. level = &matroska->levels[matroska->num_levels++];
  459. level->start = url_ftell(pb);
  460. level->length = length;
  461. return 0;
  462. }
  463. /*
  464. * Read the next element as binary data.
  465. * 0 is success, < 0 is failure.
  466. */
  467. static int
  468. ebml_read_binary (MatroskaDemuxContext *matroska,
  469. uint32_t *id,
  470. uint8_t **binary,
  471. int *size)
  472. {
  473. ByteIOContext *pb = &matroska->ctx->pb;
  474. uint64_t rlength;
  475. int res;
  476. if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
  477. (res = ebml_read_element_length(matroska, &rlength)) < 0)
  478. return res;
  479. *size = rlength;
  480. if (!(*binary = av_malloc(*size))) {
  481. av_log(matroska->ctx, AV_LOG_ERROR,
  482. "Memory allocation error\n");
  483. return AVERROR(ENOMEM);
  484. }
  485. if (get_buffer(pb, *binary, *size) != *size) {
  486. offset_t pos = url_ftell(pb);
  487. av_log(matroska->ctx, AV_LOG_ERROR,
  488. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
  489. return AVERROR(EIO);
  490. }
  491. return 0;
  492. }
  493. /*
  494. * Read signed/unsigned "EBML" numbers.
  495. * Return: number of bytes processed, < 0 on error.
  496. * XXX: use ebml_read_num().
  497. */
  498. static int
  499. matroska_ebmlnum_uint (uint8_t *data,
  500. uint32_t size,
  501. uint64_t *num)
  502. {
  503. int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
  504. uint64_t total;
  505. if (size <= 0)
  506. return AVERROR_INVALIDDATA;
  507. total = data[0];
  508. while (read <= 8 && !(total & len_mask)) {
  509. read++;
  510. len_mask >>= 1;
  511. }
  512. if (read > 8)
  513. return AVERROR_INVALIDDATA;
  514. if ((total &= (len_mask - 1)) == len_mask - 1)
  515. num_ffs++;
  516. if (size < read)
  517. return AVERROR_INVALIDDATA;
  518. while (n < read) {
  519. if (data[n] == 0xff)
  520. num_ffs++;
  521. total = (total << 8) | data[n];
  522. n++;
  523. }
  524. if (read == num_ffs)
  525. *num = (uint64_t)-1;
  526. else
  527. *num = total;
  528. return read;
  529. }
  530. /*
  531. * Same as above, but signed.
  532. */
  533. static int
  534. matroska_ebmlnum_sint (uint8_t *data,
  535. uint32_t size,
  536. int64_t *num)
  537. {
  538. uint64_t unum;
  539. int res;
  540. /* read as unsigned number first */
  541. if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
  542. return res;
  543. /* make signed (weird way) */
  544. if (unum == (uint64_t)-1)
  545. *num = INT64_MAX;
  546. else
  547. *num = unum - ((1LL << ((7 * res) - 1)) - 1);
  548. return res;
  549. }
  550. /*
  551. * Read an EBML header.
  552. * 0 is success, < 0 is failure.
  553. */
  554. static int
  555. ebml_read_header (MatroskaDemuxContext *matroska,
  556. char **doctype,
  557. int *version)
  558. {
  559. uint32_t id;
  560. int level_up, res = 0;
  561. /* default init */
  562. if (doctype)
  563. *doctype = NULL;
  564. if (version)
  565. *version = 1;
  566. if (!(id = ebml_peek_id(matroska, &level_up)) ||
  567. level_up != 0 || id != EBML_ID_HEADER) {
  568. av_log(matroska->ctx, AV_LOG_ERROR,
  569. "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
  570. return AVERROR_INVALIDDATA;
  571. }
  572. if ((res = ebml_read_master(matroska, &id)) < 0)
  573. return res;
  574. while (res == 0) {
  575. if (!(id = ebml_peek_id(matroska, &level_up)))
  576. return AVERROR(EIO);
  577. /* end-of-header */
  578. if (level_up)
  579. break;
  580. switch (id) {
  581. /* is our read version uptodate? */
  582. case EBML_ID_EBMLREADVERSION: {
  583. uint64_t num;
  584. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  585. return res;
  586. if (num > EBML_VERSION) {
  587. av_log(matroska->ctx, AV_LOG_ERROR,
  588. "EBML version %"PRIu64" (> %d) is not supported\n",
  589. num, EBML_VERSION);
  590. return AVERROR_INVALIDDATA;
  591. }
  592. break;
  593. }
  594. /* we only handle 8 byte lengths at max */
  595. case EBML_ID_EBMLMAXSIZELENGTH: {
  596. uint64_t num;
  597. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  598. return res;
  599. if (num > sizeof(uint64_t)) {
  600. av_log(matroska->ctx, AV_LOG_ERROR,
  601. "Integers of size %"PRIu64" (> %zd) not supported\n",
  602. num, sizeof(uint64_t));
  603. return AVERROR_INVALIDDATA;
  604. }
  605. break;
  606. }
  607. /* we handle 4 byte IDs at max */
  608. case EBML_ID_EBMLMAXIDLENGTH: {
  609. uint64_t num;
  610. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  611. return res;
  612. if (num > sizeof(uint32_t)) {
  613. av_log(matroska->ctx, AV_LOG_ERROR,
  614. "IDs of size %"PRIu64" (> %zu) not supported\n",
  615. num, sizeof(uint32_t));
  616. return AVERROR_INVALIDDATA;
  617. }
  618. break;
  619. }
  620. case EBML_ID_DOCTYPE: {
  621. char *text;
  622. if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
  623. return res;
  624. if (doctype) {
  625. if (*doctype)
  626. av_free(*doctype);
  627. *doctype = text;
  628. } else
  629. av_free(text);
  630. break;
  631. }
  632. case EBML_ID_DOCTYPEREADVERSION: {
  633. uint64_t num;
  634. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  635. return res;
  636. if (version)
  637. *version = num;
  638. break;
  639. }
  640. default:
  641. av_log(matroska->ctx, AV_LOG_INFO,
  642. "Unknown data type 0x%x in EBML header", id);
  643. /* pass-through */
  644. case EBML_ID_VOID:
  645. /* we ignore these two, as they don't tell us anything we
  646. * care about */
  647. case EBML_ID_EBMLVERSION:
  648. case EBML_ID_DOCTYPEVERSION:
  649. res = ebml_read_skip (matroska);
  650. break;
  651. }
  652. }
  653. return 0;
  654. }
  655. static int
  656. matroska_find_track_by_num (MatroskaDemuxContext *matroska,
  657. int num)
  658. {
  659. int i;
  660. for (i = 0; i < matroska->num_tracks; i++)
  661. if (matroska->tracks[i]->num == num)
  662. return i;
  663. return -1;
  664. }
  665. /*
  666. * Put one packet in an application-supplied AVPacket struct.
  667. * Returns 0 on success or -1 on failure.
  668. */
  669. static int
  670. matroska_deliver_packet (MatroskaDemuxContext *matroska,
  671. AVPacket *pkt)
  672. {
  673. if (matroska->num_packets > 0) {
  674. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  675. av_free(matroska->packets[0]);
  676. if (matroska->num_packets > 1) {
  677. memmove(&matroska->packets[0], &matroska->packets[1],
  678. (matroska->num_packets - 1) * sizeof(AVPacket *));
  679. matroska->packets =
  680. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  681. sizeof(AVPacket *));
  682. } else {
  683. av_freep(&matroska->packets);
  684. }
  685. matroska->num_packets--;
  686. return 0;
  687. }
  688. return -1;
  689. }
  690. /*
  691. * Put a packet into our internal queue. Will be delivered to the
  692. * user/application during the next get_packet() call.
  693. */
  694. static void
  695. matroska_queue_packet (MatroskaDemuxContext *matroska,
  696. AVPacket *pkt)
  697. {
  698. matroska->packets =
  699. av_realloc(matroska->packets, (matroska->num_packets + 1) *
  700. sizeof(AVPacket *));
  701. matroska->packets[matroska->num_packets] = pkt;
  702. matroska->num_packets++;
  703. }
  704. /*
  705. * Autodetecting...
  706. */
  707. static int
  708. matroska_probe (AVProbeData *p)
  709. {
  710. uint64_t total = 0;
  711. int len_mask = 0x80, size = 1, n = 1;
  712. uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
  713. /* ebml header? */
  714. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  715. return 0;
  716. /* length of header */
  717. total = p->buf[4];
  718. while (size <= 8 && !(total & len_mask)) {
  719. size++;
  720. len_mask >>= 1;
  721. }
  722. if (size > 8)
  723. return 0;
  724. total &= (len_mask - 1);
  725. while (n < size)
  726. total = (total << 8) | p->buf[4 + n++];
  727. /* does the probe data contain the whole header? */
  728. if (p->buf_size < 4 + size + total)
  729. return 0;
  730. /* the header must contain the document type 'matroska'. For now,
  731. * we don't parse the whole header but simply check for the
  732. * availability of that array of characters inside the header.
  733. * Not fully fool-proof, but good enough. */
  734. for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
  735. if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
  736. return AVPROBE_SCORE_MAX;
  737. return 0;
  738. }
  739. /*
  740. * From here on, it's all XML-style DTD stuff... Needs no comments.
  741. */
  742. static int
  743. matroska_parse_info (MatroskaDemuxContext *matroska)
  744. {
  745. int res = 0;
  746. uint32_t id;
  747. av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
  748. while (res == 0) {
  749. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  750. res = AVERROR(EIO);
  751. break;
  752. } else if (matroska->level_up) {
  753. matroska->level_up--;
  754. break;
  755. }
  756. switch (id) {
  757. /* cluster timecode */
  758. case MATROSKA_ID_TIMECODESCALE: {
  759. uint64_t num;
  760. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  761. break;
  762. matroska->time_scale = num;
  763. break;
  764. }
  765. case MATROSKA_ID_DURATION: {
  766. double num;
  767. if ((res = ebml_read_float(matroska, &id, &num)) < 0)
  768. break;
  769. matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
  770. break;
  771. }
  772. case MATROSKA_ID_TITLE: {
  773. char *text;
  774. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  775. break;
  776. strncpy(matroska->ctx->title, text,
  777. sizeof(matroska->ctx->title)-1);
  778. av_free(text);
  779. break;
  780. }
  781. case MATROSKA_ID_WRITINGAPP: {
  782. char *text;
  783. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  784. break;
  785. matroska->writing_app = text;
  786. break;
  787. }
  788. case MATROSKA_ID_MUXINGAPP: {
  789. char *text;
  790. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  791. break;
  792. matroska->muxing_app = text;
  793. break;
  794. }
  795. case MATROSKA_ID_DATEUTC: {
  796. int64_t time;
  797. if ((res = ebml_read_date(matroska, &id, &time)) < 0)
  798. break;
  799. matroska->created = time;
  800. break;
  801. }
  802. default:
  803. av_log(matroska->ctx, AV_LOG_INFO,
  804. "Unknown entry 0x%x in info header\n", id);
  805. /* fall-through */
  806. case EBML_ID_VOID:
  807. res = ebml_read_skip(matroska);
  808. break;
  809. }
  810. if (matroska->level_up) {
  811. matroska->level_up--;
  812. break;
  813. }
  814. }
  815. return res;
  816. }
  817. static int
  818. matroska_add_stream (MatroskaDemuxContext *matroska)
  819. {
  820. int res = 0;
  821. uint32_t id;
  822. MatroskaTrack *track;
  823. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
  824. /* Allocate a generic track. As soon as we know its type we'll realloc. */
  825. track = av_mallocz(MAX_TRACK_SIZE);
  826. matroska->num_tracks++;
  827. strcpy(track->language, "eng");
  828. /* start with the master */
  829. if ((res = ebml_read_master(matroska, &id)) < 0)
  830. return res;
  831. /* try reading the trackentry headers */
  832. while (res == 0) {
  833. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  834. res = AVERROR(EIO);
  835. break;
  836. } else if (matroska->level_up > 0) {
  837. matroska->level_up--;
  838. break;
  839. }
  840. switch (id) {
  841. /* track number (unique stream ID) */
  842. case MATROSKA_ID_TRACKNUMBER: {
  843. uint64_t num;
  844. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  845. break;
  846. track->num = num;
  847. break;
  848. }
  849. /* track UID (unique identifier) */
  850. case MATROSKA_ID_TRACKUID: {
  851. uint64_t num;
  852. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  853. break;
  854. track->uid = num;
  855. break;
  856. }
  857. /* track type (video, audio, combined, subtitle, etc.) */
  858. case MATROSKA_ID_TRACKTYPE: {
  859. uint64_t num;
  860. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  861. break;
  862. if (track->type && track->type != num) {
  863. av_log(matroska->ctx, AV_LOG_INFO,
  864. "More than one tracktype in an entry - skip\n");
  865. break;
  866. }
  867. track->type = num;
  868. switch (track->type) {
  869. case MATROSKA_TRACK_TYPE_VIDEO:
  870. case MATROSKA_TRACK_TYPE_AUDIO:
  871. case MATROSKA_TRACK_TYPE_SUBTITLE:
  872. break;
  873. case MATROSKA_TRACK_TYPE_COMPLEX:
  874. case MATROSKA_TRACK_TYPE_LOGO:
  875. case MATROSKA_TRACK_TYPE_CONTROL:
  876. default:
  877. av_log(matroska->ctx, AV_LOG_INFO,
  878. "Unknown or unsupported track type 0x%x\n",
  879. track->type);
  880. track->type = 0;
  881. break;
  882. }
  883. matroska->tracks[matroska->num_tracks - 1] = track;
  884. break;
  885. }
  886. /* tracktype specific stuff for video */
  887. case MATROSKA_ID_TRACKVIDEO: {
  888. MatroskaVideoTrack *videotrack;
  889. if (!track->type)
  890. track->type = MATROSKA_TRACK_TYPE_VIDEO;
  891. if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
  892. av_log(matroska->ctx, AV_LOG_INFO,
  893. "video data in non-video track - ignoring\n");
  894. res = AVERROR_INVALIDDATA;
  895. break;
  896. } else if ((res = ebml_read_master(matroska, &id)) < 0)
  897. break;
  898. videotrack = (MatroskaVideoTrack *)track;
  899. while (res == 0) {
  900. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  901. res = AVERROR(EIO);
  902. break;
  903. } else if (matroska->level_up > 0) {
  904. matroska->level_up--;
  905. break;
  906. }
  907. switch (id) {
  908. /* fixme, this should be one-up, but I get it here */
  909. case MATROSKA_ID_TRACKDEFAULTDURATION: {
  910. uint64_t num;
  911. if ((res = ebml_read_uint (matroska, &id,
  912. &num)) < 0)
  913. break;
  914. track->default_duration = num/matroska->time_scale;
  915. break;
  916. }
  917. /* video framerate */
  918. case MATROSKA_ID_VIDEOFRAMERATE: {
  919. double num;
  920. if ((res = ebml_read_float(matroska, &id,
  921. &num)) < 0)
  922. break;
  923. track->default_duration = 1000000000/(matroska->time_scale*num);
  924. break;
  925. }
  926. /* width of the size to display the video at */
  927. case MATROSKA_ID_VIDEODISPLAYWIDTH: {
  928. uint64_t num;
  929. if ((res = ebml_read_uint(matroska, &id,
  930. &num)) < 0)
  931. break;
  932. videotrack->display_width = num;
  933. break;
  934. }
  935. /* height of the size to display the video at */
  936. case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
  937. uint64_t num;
  938. if ((res = ebml_read_uint(matroska, &id,
  939. &num)) < 0)
  940. break;
  941. videotrack->display_height = num;
  942. break;
  943. }
  944. /* width of the video in the file */
  945. case MATROSKA_ID_VIDEOPIXELWIDTH: {
  946. uint64_t num;
  947. if ((res = ebml_read_uint(matroska, &id,
  948. &num)) < 0)
  949. break;
  950. videotrack->pixel_width = num;
  951. break;
  952. }
  953. /* height of the video in the file */
  954. case MATROSKA_ID_VIDEOPIXELHEIGHT: {
  955. uint64_t num;
  956. if ((res = ebml_read_uint(matroska, &id,
  957. &num)) < 0)
  958. break;
  959. videotrack->pixel_height = num;
  960. break;
  961. }
  962. /* whether the video is interlaced */
  963. case MATROSKA_ID_VIDEOFLAGINTERLACED: {
  964. uint64_t num;
  965. if ((res = ebml_read_uint(matroska, &id,
  966. &num)) < 0)
  967. break;
  968. if (num)
  969. track->flags |=
  970. MATROSKA_VIDEOTRACK_INTERLACED;
  971. else
  972. track->flags &=
  973. ~MATROSKA_VIDEOTRACK_INTERLACED;
  974. break;
  975. }
  976. /* stereo mode (whether the video has two streams,
  977. * where one is for the left eye and the other for
  978. * the right eye, which creates a 3D-like
  979. * effect) */
  980. case MATROSKA_ID_VIDEOSTEREOMODE: {
  981. uint64_t num;
  982. if ((res = ebml_read_uint(matroska, &id,
  983. &num)) < 0)
  984. break;
  985. if (num != MATROSKA_EYE_MODE_MONO &&
  986. num != MATROSKA_EYE_MODE_LEFT &&
  987. num != MATROSKA_EYE_MODE_RIGHT &&
  988. num != MATROSKA_EYE_MODE_BOTH) {
  989. av_log(matroska->ctx, AV_LOG_INFO,
  990. "Ignoring unknown eye mode 0x%x\n",
  991. (uint32_t) num);
  992. break;
  993. }
  994. videotrack->eye_mode = num;
  995. break;
  996. }
  997. /* aspect ratio behaviour */
  998. case MATROSKA_ID_VIDEOASPECTRATIO: {
  999. uint64_t num;
  1000. if ((res = ebml_read_uint(matroska, &id,
  1001. &num)) < 0)
  1002. break;
  1003. if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
  1004. num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
  1005. num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
  1006. av_log(matroska->ctx, AV_LOG_INFO,
  1007. "Ignoring unknown aspect ratio 0x%x\n",
  1008. (uint32_t) num);
  1009. break;
  1010. }
  1011. videotrack->ar_mode = num;
  1012. break;
  1013. }
  1014. /* colourspace (only matters for raw video)
  1015. * fourcc */
  1016. case MATROSKA_ID_VIDEOCOLOURSPACE: {
  1017. uint64_t num;
  1018. if ((res = ebml_read_uint(matroska, &id,
  1019. &num)) < 0)
  1020. break;
  1021. videotrack->fourcc = num;
  1022. break;
  1023. }
  1024. default:
  1025. av_log(matroska->ctx, AV_LOG_INFO,
  1026. "Unknown video track header entry "
  1027. "0x%x - ignoring\n", id);
  1028. /* pass-through */
  1029. case EBML_ID_VOID:
  1030. res = ebml_read_skip(matroska);
  1031. break;
  1032. }
  1033. if (matroska->level_up) {
  1034. matroska->level_up--;
  1035. break;
  1036. }
  1037. }
  1038. break;
  1039. }
  1040. /* tracktype specific stuff for audio */
  1041. case MATROSKA_ID_TRACKAUDIO: {
  1042. MatroskaAudioTrack *audiotrack;
  1043. if (!track->type)
  1044. track->type = MATROSKA_TRACK_TYPE_AUDIO;
  1045. if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
  1046. av_log(matroska->ctx, AV_LOG_INFO,
  1047. "audio data in non-audio track - ignoring\n");
  1048. res = AVERROR_INVALIDDATA;
  1049. break;
  1050. } else if ((res = ebml_read_master(matroska, &id)) < 0)
  1051. break;
  1052. audiotrack = (MatroskaAudioTrack *)track;
  1053. audiotrack->channels = 1;
  1054. audiotrack->samplerate = 8000;
  1055. while (res == 0) {
  1056. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1057. res = AVERROR(EIO);
  1058. break;
  1059. } else if (matroska->level_up > 0) {
  1060. matroska->level_up--;
  1061. break;
  1062. }
  1063. switch (id) {
  1064. /* samplerate */
  1065. case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
  1066. double num;
  1067. if ((res = ebml_read_float(matroska, &id,
  1068. &num)) < 0)
  1069. break;
  1070. audiotrack->internal_samplerate =
  1071. audiotrack->samplerate = num;
  1072. break;
  1073. }
  1074. case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
  1075. double num;
  1076. if ((res = ebml_read_float(matroska, &id,
  1077. &num)) < 0)
  1078. break;
  1079. audiotrack->samplerate = num;
  1080. break;
  1081. }
  1082. /* bitdepth */
  1083. case MATROSKA_ID_AUDIOBITDEPTH: {
  1084. uint64_t num;
  1085. if ((res = ebml_read_uint(matroska, &id,
  1086. &num)) < 0)
  1087. break;
  1088. audiotrack->bitdepth = num;
  1089. break;
  1090. }
  1091. /* channels */
  1092. case MATROSKA_ID_AUDIOCHANNELS: {
  1093. uint64_t num;
  1094. if ((res = ebml_read_uint(matroska, &id,
  1095. &num)) < 0)
  1096. break;
  1097. audiotrack->channels = num;
  1098. break;
  1099. }
  1100. default:
  1101. av_log(matroska->ctx, AV_LOG_INFO,
  1102. "Unknown audio track header entry "
  1103. "0x%x - ignoring\n", id);
  1104. /* pass-through */
  1105. case EBML_ID_VOID:
  1106. res = ebml_read_skip(matroska);
  1107. break;
  1108. }
  1109. if (matroska->level_up) {
  1110. matroska->level_up--;
  1111. break;
  1112. }
  1113. }
  1114. break;
  1115. }
  1116. /* codec identifier */
  1117. case MATROSKA_ID_CODECID: {
  1118. char *text;
  1119. if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
  1120. break;
  1121. track->codec_id = text;
  1122. break;
  1123. }
  1124. /* codec private data */
  1125. case MATROSKA_ID_CODECPRIVATE: {
  1126. uint8_t *data;
  1127. int size;
  1128. if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
  1129. break;
  1130. track->codec_priv = data;
  1131. track->codec_priv_size = size;
  1132. break;
  1133. }
  1134. /* name of the codec */
  1135. case MATROSKA_ID_CODECNAME: {
  1136. char *text;
  1137. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  1138. break;
  1139. track->codec_name = text;
  1140. break;
  1141. }
  1142. /* name of this track */
  1143. case MATROSKA_ID_TRACKNAME: {
  1144. char *text;
  1145. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  1146. break;
  1147. track->name = text;
  1148. break;
  1149. }
  1150. /* language (matters for audio/subtitles, mostly) */
  1151. case MATROSKA_ID_TRACKLANGUAGE: {
  1152. char *text, *end;
  1153. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  1154. break;
  1155. if ((end = strchr(text, '-')))
  1156. *end = '\0';
  1157. if (strlen(text) == 3)
  1158. strcpy(track->language, text);
  1159. av_free(text);
  1160. break;
  1161. }
  1162. /* whether this is actually used */
  1163. case MATROSKA_ID_TRACKFLAGENABLED: {
  1164. uint64_t num;
  1165. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1166. break;
  1167. if (num)
  1168. track->flags |= MATROSKA_TRACK_ENABLED;
  1169. else
  1170. track->flags &= ~MATROSKA_TRACK_ENABLED;
  1171. break;
  1172. }
  1173. /* whether it's the default for this track type */
  1174. case MATROSKA_ID_TRACKFLAGDEFAULT: {
  1175. uint64_t num;
  1176. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1177. break;
  1178. if (num)
  1179. track->flags |= MATROSKA_TRACK_DEFAULT;
  1180. else
  1181. track->flags &= ~MATROSKA_TRACK_DEFAULT;
  1182. break;
  1183. }
  1184. /* lacing (like MPEG, where blocks don't end/start on frame
  1185. * boundaries) */
  1186. case MATROSKA_ID_TRACKFLAGLACING: {
  1187. uint64_t num;
  1188. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1189. break;
  1190. if (num)
  1191. track->flags |= MATROSKA_TRACK_LACING;
  1192. else
  1193. track->flags &= ~MATROSKA_TRACK_LACING;
  1194. break;
  1195. }
  1196. /* default length (in time) of one data block in this track */
  1197. case MATROSKA_ID_TRACKDEFAULTDURATION: {
  1198. uint64_t num;
  1199. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1200. break;
  1201. track->default_duration = num / matroska->time_scale;
  1202. break;
  1203. }
  1204. default:
  1205. av_log(matroska->ctx, AV_LOG_INFO,
  1206. "Unknown track header entry 0x%x - ignoring\n", id);
  1207. /* pass-through */
  1208. case EBML_ID_VOID:
  1209. /* we ignore these because they're nothing useful. */
  1210. case MATROSKA_ID_CODECINFOURL:
  1211. case MATROSKA_ID_CODECDOWNLOADURL:
  1212. case MATROSKA_ID_TRACKMINCACHE:
  1213. case MATROSKA_ID_TRACKMAXCACHE:
  1214. res = ebml_read_skip(matroska);
  1215. break;
  1216. }
  1217. if (matroska->level_up) {
  1218. matroska->level_up--;
  1219. break;
  1220. }
  1221. }
  1222. return res;
  1223. }
  1224. static int
  1225. matroska_parse_tracks (MatroskaDemuxContext *matroska)
  1226. {
  1227. int res = 0;
  1228. uint32_t id;
  1229. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
  1230. while (res == 0) {
  1231. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1232. res = AVERROR(EIO);
  1233. break;
  1234. } else if (matroska->level_up) {
  1235. matroska->level_up--;
  1236. break;
  1237. }
  1238. switch (id) {
  1239. /* one track within the "all-tracks" header */
  1240. case MATROSKA_ID_TRACKENTRY:
  1241. res = matroska_add_stream(matroska);
  1242. break;
  1243. default:
  1244. av_log(matroska->ctx, AV_LOG_INFO,
  1245. "Unknown entry 0x%x in track header\n", id);
  1246. /* fall-through */
  1247. case EBML_ID_VOID:
  1248. res = ebml_read_skip(matroska);
  1249. break;
  1250. }
  1251. if (matroska->level_up) {
  1252. matroska->level_up--;
  1253. break;
  1254. }
  1255. }
  1256. return res;
  1257. }
  1258. static int
  1259. matroska_parse_index (MatroskaDemuxContext *matroska)
  1260. {
  1261. int res = 0;
  1262. uint32_t id;
  1263. MatroskaDemuxIndex idx;
  1264. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
  1265. while (res == 0) {
  1266. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1267. res = AVERROR(EIO);
  1268. break;
  1269. } else if (matroska->level_up) {
  1270. matroska->level_up--;
  1271. break;
  1272. }
  1273. switch (id) {
  1274. /* one single index entry ('point') */
  1275. case MATROSKA_ID_POINTENTRY:
  1276. if ((res = ebml_read_master(matroska, &id)) < 0)
  1277. break;
  1278. /* in the end, we hope to fill one entry with a
  1279. * timestamp, a file position and a tracknum */
  1280. idx.pos = (uint64_t) -1;
  1281. idx.time = (uint64_t) -1;
  1282. idx.track = (uint16_t) -1;
  1283. while (res == 0) {
  1284. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1285. res = AVERROR(EIO);
  1286. break;
  1287. } else if (matroska->level_up) {
  1288. matroska->level_up--;
  1289. break;
  1290. }
  1291. switch (id) {
  1292. /* one single index entry ('point') */
  1293. case MATROSKA_ID_CUETIME: {
  1294. uint64_t time;
  1295. if ((res = ebml_read_uint(matroska, &id,
  1296. &time)) < 0)
  1297. break;
  1298. idx.time = time * matroska->time_scale;
  1299. break;
  1300. }
  1301. /* position in the file + track to which it
  1302. * belongs */
  1303. case MATROSKA_ID_CUETRACKPOSITION:
  1304. if ((res = ebml_read_master(matroska, &id)) < 0)
  1305. break;
  1306. while (res == 0) {
  1307. if (!(id = ebml_peek_id (matroska,
  1308. &matroska->level_up))) {
  1309. res = AVERROR(EIO);
  1310. break;
  1311. } else if (matroska->level_up) {
  1312. matroska->level_up--;
  1313. break;
  1314. }
  1315. switch (id) {
  1316. /* track number */
  1317. case MATROSKA_ID_CUETRACK: {
  1318. uint64_t num;
  1319. if ((res = ebml_read_uint(matroska,
  1320. &id, &num)) < 0)
  1321. break;
  1322. idx.track = num;
  1323. break;
  1324. }
  1325. /* position in file */
  1326. case MATROSKA_ID_CUECLUSTERPOSITION: {
  1327. uint64_t num;
  1328. if ((res = ebml_read_uint(matroska,
  1329. &id, &num)) < 0)
  1330. break;
  1331. idx.pos = num+matroska->segment_start;
  1332. break;
  1333. }
  1334. default:
  1335. av_log(matroska->ctx, AV_LOG_INFO,
  1336. "Unknown entry 0x%x in "
  1337. "CuesTrackPositions\n", id);
  1338. /* fall-through */
  1339. case EBML_ID_VOID:
  1340. res = ebml_read_skip(matroska);
  1341. break;
  1342. }
  1343. if (matroska->level_up) {
  1344. matroska->level_up--;
  1345. break;
  1346. }
  1347. }
  1348. break;
  1349. default:
  1350. av_log(matroska->ctx, AV_LOG_INFO,
  1351. "Unknown entry 0x%x in cuespoint "
  1352. "index\n", id);
  1353. /* fall-through */
  1354. case EBML_ID_VOID:
  1355. res = ebml_read_skip(matroska);
  1356. break;
  1357. }
  1358. if (matroska->level_up) {
  1359. matroska->level_up--;
  1360. break;
  1361. }
  1362. }
  1363. /* so let's see if we got what we wanted */
  1364. if (idx.pos != (uint64_t) -1 &&
  1365. idx.time != (uint64_t) -1 &&
  1366. idx.track != (uint16_t) -1) {
  1367. if (matroska->num_indexes % 32 == 0) {
  1368. /* re-allocate bigger index */
  1369. matroska->index =
  1370. av_realloc(matroska->index,
  1371. (matroska->num_indexes + 32) *
  1372. sizeof(MatroskaDemuxIndex));
  1373. }
  1374. matroska->index[matroska->num_indexes] = idx;
  1375. matroska->num_indexes++;
  1376. }
  1377. break;
  1378. default:
  1379. av_log(matroska->ctx, AV_LOG_INFO,
  1380. "Unknown entry 0x%x in cues header\n", id);
  1381. /* fall-through */
  1382. case EBML_ID_VOID:
  1383. res = ebml_read_skip(matroska);
  1384. break;
  1385. }
  1386. if (matroska->level_up) {
  1387. matroska->level_up--;
  1388. break;
  1389. }
  1390. }
  1391. return res;
  1392. }
  1393. static int
  1394. matroska_parse_metadata (MatroskaDemuxContext *matroska)
  1395. {
  1396. int res = 0;
  1397. uint32_t id;
  1398. while (res == 0) {
  1399. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1400. res = AVERROR(EIO);
  1401. break;
  1402. } else if (matroska->level_up) {
  1403. matroska->level_up--;
  1404. break;
  1405. }
  1406. switch (id) {
  1407. /* Hm, this is unsupported... */
  1408. default:
  1409. av_log(matroska->ctx, AV_LOG_INFO,
  1410. "Unknown entry 0x%x in metadata header\n", id);
  1411. /* fall-through */
  1412. case EBML_ID_VOID:
  1413. res = ebml_read_skip(matroska);
  1414. break;
  1415. }
  1416. if (matroska->level_up) {
  1417. matroska->level_up--;
  1418. break;
  1419. }
  1420. }
  1421. return res;
  1422. }
  1423. static int
  1424. matroska_parse_seekhead (MatroskaDemuxContext *matroska)
  1425. {
  1426. int res = 0;
  1427. uint32_t id;
  1428. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
  1429. while (res == 0) {
  1430. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1431. res = AVERROR(EIO);
  1432. break;
  1433. } else if (matroska->level_up) {
  1434. matroska->level_up--;
  1435. break;
  1436. }
  1437. switch (id) {
  1438. case MATROSKA_ID_SEEKENTRY: {
  1439. uint32_t seek_id = 0, peek_id_cache = 0;
  1440. uint64_t seek_pos = (uint64_t) -1, t;
  1441. if ((res = ebml_read_master(matroska, &id)) < 0)
  1442. break;
  1443. while (res == 0) {
  1444. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1445. res = AVERROR(EIO);
  1446. break;
  1447. } else if (matroska->level_up) {
  1448. matroska->level_up--;
  1449. break;
  1450. }
  1451. switch (id) {
  1452. case MATROSKA_ID_SEEKID:
  1453. res = ebml_read_uint(matroska, &id, &t);
  1454. seek_id = t;
  1455. break;
  1456. case MATROSKA_ID_SEEKPOSITION:
  1457. res = ebml_read_uint(matroska, &id, &seek_pos);
  1458. break;
  1459. default:
  1460. av_log(matroska->ctx, AV_LOG_INFO,
  1461. "Unknown seekhead ID 0x%x\n", id);
  1462. /* fall-through */
  1463. case EBML_ID_VOID:
  1464. res = ebml_read_skip(matroska);
  1465. break;
  1466. }
  1467. if (matroska->level_up) {
  1468. matroska->level_up--;
  1469. break;
  1470. }
  1471. }
  1472. if (!seek_id || seek_pos == (uint64_t) -1) {
  1473. av_log(matroska->ctx, AV_LOG_INFO,
  1474. "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
  1475. seek_id, seek_pos);
  1476. break;
  1477. }
  1478. switch (seek_id) {
  1479. case MATROSKA_ID_CUES:
  1480. case MATROSKA_ID_TAGS: {
  1481. uint32_t level_up = matroska->level_up;
  1482. offset_t before_pos;
  1483. uint64_t length;
  1484. MatroskaLevel level;
  1485. /* remember the peeked ID and the current position */
  1486. peek_id_cache = matroska->peek_id;
  1487. before_pos = url_ftell(&matroska->ctx->pb);
  1488. /* seek */
  1489. if ((res = ebml_read_seek(matroska, seek_pos +
  1490. matroska->segment_start)) < 0)
  1491. return res;
  1492. /* we don't want to lose our seekhead level, so we add
  1493. * a dummy. This is a crude hack. */
  1494. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1495. av_log(matroska->ctx, AV_LOG_INFO,
  1496. "Max EBML element depth (%d) reached, "
  1497. "cannot parse further.\n", EBML_MAX_DEPTH);
  1498. return AVERROR_UNKNOWN;
  1499. }
  1500. level.start = 0;
  1501. level.length = (uint64_t)-1;
  1502. matroska->levels[matroska->num_levels] = level;
  1503. matroska->num_levels++;
  1504. /* check ID */
  1505. if (!(id = ebml_peek_id (matroska,
  1506. &matroska->level_up)))
  1507. goto finish;
  1508. if (id != seek_id) {
  1509. av_log(matroska->ctx, AV_LOG_INFO,
  1510. "We looked for ID=0x%x but got "
  1511. "ID=0x%x (pos=%"PRIu64")",
  1512. seek_id, id, seek_pos +
  1513. matroska->segment_start);
  1514. goto finish;
  1515. }
  1516. /* read master + parse */
  1517. if ((res = ebml_read_master(matroska, &id)) < 0)
  1518. goto finish;
  1519. switch (id) {
  1520. case MATROSKA_ID_CUES:
  1521. if (!(res = matroska_parse_index(matroska)) ||
  1522. url_feof(&matroska->ctx->pb)) {
  1523. matroska->index_parsed = 1;
  1524. res = 0;
  1525. }
  1526. break;
  1527. case MATROSKA_ID_TAGS:
  1528. if (!(res = matroska_parse_metadata(matroska)) ||
  1529. url_feof(&matroska->ctx->pb)) {
  1530. matroska->metadata_parsed = 1;
  1531. res = 0;
  1532. }
  1533. break;
  1534. }
  1535. finish:
  1536. /* remove dummy level */
  1537. while (matroska->num_levels) {
  1538. matroska->num_levels--;
  1539. length =
  1540. matroska->levels[matroska->num_levels].length;
  1541. if (length == (uint64_t)-1)
  1542. break;
  1543. }
  1544. /* seek back */
  1545. if ((res = ebml_read_seek(matroska, before_pos)) < 0)
  1546. return res;
  1547. matroska->peek_id = peek_id_cache;
  1548. matroska->level_up = level_up;
  1549. break;
  1550. }
  1551. default:
  1552. av_log(matroska->ctx, AV_LOG_INFO,
  1553. "Ignoring seekhead entry for ID=0x%x\n",
  1554. seek_id);
  1555. break;
  1556. }
  1557. break;
  1558. }
  1559. default:
  1560. av_log(matroska->ctx, AV_LOG_INFO,
  1561. "Unknown seekhead ID 0x%x\n", id);
  1562. /* fall-through */
  1563. case EBML_ID_VOID:
  1564. res = ebml_read_skip(matroska);
  1565. break;
  1566. }
  1567. if (matroska->level_up) {
  1568. matroska->level_up--;
  1569. break;
  1570. }
  1571. }
  1572. return res;
  1573. }
  1574. #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
  1575. static int
  1576. matroska_aac_profile (char *codec_id)
  1577. {
  1578. static const char *aac_profiles[] = {
  1579. "MAIN", "LC", "SSR"
  1580. };
  1581. int profile;
  1582. for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
  1583. if (strstr(codec_id, aac_profiles[profile]))
  1584. break;
  1585. return profile + 1;
  1586. }
  1587. static int
  1588. matroska_aac_sri (int samplerate)
  1589. {
  1590. static const int aac_sample_rates[] = {
  1591. 96000, 88200, 64000, 48000, 44100, 32000,
  1592. 24000, 22050, 16000, 12000, 11025, 8000,
  1593. };
  1594. int sri;
  1595. for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
  1596. if (aac_sample_rates[sri] == samplerate)
  1597. break;
  1598. return sri;
  1599. }
  1600. static int
  1601. matroska_read_header (AVFormatContext *s,
  1602. AVFormatParameters *ap)
  1603. {
  1604. MatroskaDemuxContext *matroska = s->priv_data;
  1605. char *doctype;
  1606. int version, last_level, res = 0;
  1607. uint32_t id;
  1608. matroska->ctx = s;
  1609. /* First read the EBML header. */
  1610. doctype = NULL;
  1611. if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
  1612. return res;
  1613. if ((doctype == NULL) || strcmp(doctype, "matroska")) {
  1614. av_log(matroska->ctx, AV_LOG_ERROR,
  1615. "Wrong EBML doctype ('%s' != 'matroska').\n",
  1616. doctype ? doctype : "(none)");
  1617. if (doctype)
  1618. av_free(doctype);
  1619. return AVERROR_NOFMT;
  1620. }
  1621. av_free(doctype);
  1622. if (version > 2) {
  1623. av_log(matroska->ctx, AV_LOG_ERROR,
  1624. "Matroska demuxer version 2 too old for file version %d\n",
  1625. version);
  1626. return AVERROR_NOFMT;
  1627. }
  1628. /* The next thing is a segment. */
  1629. while (1) {
  1630. if (!(id = ebml_peek_id(matroska, &last_level)))
  1631. return AVERROR(EIO);
  1632. if (id == MATROSKA_ID_SEGMENT)
  1633. break;
  1634. /* oi! */
  1635. av_log(matroska->ctx, AV_LOG_INFO,
  1636. "Expected a Segment ID (0x%x), but received 0x%x!\n",
  1637. MATROSKA_ID_SEGMENT, id);
  1638. if ((res = ebml_read_skip(matroska)) < 0)
  1639. return res;
  1640. }
  1641. /* We now have a Matroska segment.
  1642. * Seeks are from the beginning of the segment,
  1643. * after the segment ID/length. */
  1644. if ((res = ebml_read_master(matroska, &id)) < 0)
  1645. return res;
  1646. matroska->segment_start = url_ftell(&s->pb);
  1647. matroska->time_scale = 1000000;
  1648. /* we've found our segment, start reading the different contents in here */
  1649. while (res == 0) {
  1650. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1651. res = AVERROR(EIO);
  1652. break;
  1653. } else if (matroska->level_up) {
  1654. matroska->level_up--;
  1655. break;
  1656. }
  1657. switch (id) {
  1658. /* stream info */
  1659. case MATROSKA_ID_INFO: {
  1660. if ((res = ebml_read_master(matroska, &id)) < 0)
  1661. break;
  1662. res = matroska_parse_info(matroska);
  1663. break;
  1664. }
  1665. /* track info headers */
  1666. case MATROSKA_ID_TRACKS: {
  1667. if ((res = ebml_read_master(matroska, &id)) < 0)
  1668. break;
  1669. res = matroska_parse_tracks(matroska);
  1670. break;
  1671. }
  1672. /* stream index */
  1673. case MATROSKA_ID_CUES: {
  1674. if (!matroska->index_parsed) {
  1675. if ((res = ebml_read_master(matroska, &id)) < 0)
  1676. break;
  1677. res = matroska_parse_index(matroska);
  1678. } else
  1679. res = ebml_read_skip(matroska);
  1680. break;
  1681. }
  1682. /* metadata */
  1683. case MATROSKA_ID_TAGS: {
  1684. if (!matroska->metadata_parsed) {
  1685. if ((res = ebml_read_master(matroska, &id)) < 0)
  1686. break;
  1687. res = matroska_parse_metadata(matroska);
  1688. } else
  1689. res = ebml_read_skip(matroska);
  1690. break;
  1691. }
  1692. /* file index (if seekable, seek to Cues/Tags to parse it) */
  1693. case MATROSKA_ID_SEEKHEAD: {
  1694. if ((res = ebml_read_master(matroska, &id)) < 0)
  1695. break;
  1696. res = matroska_parse_seekhead(matroska);
  1697. break;
  1698. }
  1699. case MATROSKA_ID_CLUSTER: {
  1700. /* Do not read the master - this will be done in the next
  1701. * call to matroska_read_packet. */
  1702. res = 1;
  1703. break;
  1704. }
  1705. default:
  1706. av_log(matroska->ctx, AV_LOG_INFO,
  1707. "Unknown matroska file header ID 0x%x\n", id);
  1708. /* fall-through */
  1709. case EBML_ID_VOID:
  1710. res = ebml_read_skip(matroska);
  1711. break;
  1712. }
  1713. if (matroska->level_up) {
  1714. matroska->level_up--;
  1715. break;
  1716. }
  1717. }
  1718. /* Have we found a cluster? */
  1719. if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
  1720. int i, j;
  1721. MatroskaTrack *track;
  1722. AVStream *st;
  1723. for (i = 0; i < matroska->num_tracks; i++) {
  1724. enum CodecID codec_id = CODEC_ID_NONE;
  1725. uint8_t *extradata = NULL;
  1726. int extradata_size = 0;
  1727. int extradata_offset = 0;
  1728. track = matroska->tracks[i];
  1729. track->stream_index = -1;
  1730. /* Apply some sanity checks. */
  1731. if (track->codec_id == NULL)
  1732. continue;
  1733. for(j=0; ff_mkv_codec_tags[j].str; j++){
  1734. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1735. strlen(ff_mkv_codec_tags[j].str))){
  1736. codec_id= ff_mkv_codec_tags[j].id;
  1737. break;
  1738. }
  1739. }
  1740. /* Set the FourCC from the CodecID. */
  1741. /* This is the MS compatibility mode which stores a
  1742. * BITMAPINFOHEADER in the CodecPrivate. */
  1743. if (!strcmp(track->codec_id,
  1744. MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
  1745. (track->codec_priv_size >= 40) &&
  1746. (track->codec_priv != NULL)) {
  1747. MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
  1748. /* Offset of biCompression. Stored in LE. */
  1749. vtrack->fourcc = AV_RL32(track->codec_priv + 16);
  1750. codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
  1751. }
  1752. /* This is the MS compatibility mode which stores a
  1753. * WAVEFORMATEX in the CodecPrivate. */
  1754. else if (!strcmp(track->codec_id,
  1755. MATROSKA_CODEC_ID_AUDIO_ACM) &&
  1756. (track->codec_priv_size >= 18) &&
  1757. (track->codec_priv != NULL)) {
  1758. uint16_t tag;
  1759. /* Offset of wFormatTag. Stored in LE. */
  1760. tag = AV_RL16(track->codec_priv);
  1761. codec_id = codec_get_id(codec_wav_tags, tag);
  1762. }
  1763. else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
  1764. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
  1765. int profile = matroska_aac_profile(track->codec_id);
  1766. int sri = matroska_aac_sri(audiotrack->internal_samplerate);
  1767. extradata = av_malloc(5);
  1768. if (extradata == NULL)
  1769. return AVERROR(ENOMEM);
  1770. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1771. extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
  1772. if (strstr(track->codec_id, "SBR")) {
  1773. sri = matroska_aac_sri(audiotrack->samplerate);
  1774. extradata[2] = 0x56;
  1775. extradata[3] = 0xE5;
  1776. extradata[4] = 0x80 | (sri<<3);
  1777. extradata_size = 5;
  1778. } else {
  1779. extradata_size = 2;
  1780. }
  1781. track->default_duration = 1024*1000 / audiotrack->internal_samplerate;
  1782. }
  1783. else if (codec_id == CODEC_ID_TTA) {
  1784. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
  1785. ByteIOContext b;
  1786. extradata_size = 30;
  1787. extradata = av_mallocz(extradata_size);
  1788. if (extradata == NULL)
  1789. return AVERROR(ENOMEM);
  1790. init_put_byte(&b, extradata, extradata_size, 1,
  1791. NULL, NULL, NULL, NULL);
  1792. put_buffer(&b, (uint8_t *) "TTA1", 4);
  1793. put_le16(&b, 1);
  1794. put_le16(&b, audiotrack->channels);
  1795. put_le16(&b, audiotrack->bitdepth);
  1796. put_le32(&b, audiotrack->samplerate);
  1797. put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
  1798. }
  1799. else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1800. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1801. extradata_offset = 26;
  1802. track->codec_priv_size -= extradata_offset;
  1803. track->flags |= MATROSKA_TRACK_REAL_V;
  1804. }
  1805. else if (codec_id == CODEC_ID_RA_144) {
  1806. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1807. audiotrack->samplerate = 8000;
  1808. audiotrack->channels = 1;
  1809. }
  1810. else if (codec_id == CODEC_ID_RA_288 ||
  1811. codec_id == CODEC_ID_COOK ||
  1812. codec_id == CODEC_ID_ATRAC3) {
  1813. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1814. ByteIOContext b;
  1815. init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
  1816. NULL, NULL, NULL, NULL);
  1817. url_fskip(&b, 24);
  1818. audiotrack->coded_framesize = get_be32(&b);
  1819. url_fskip(&b, 12);
  1820. audiotrack->sub_packet_h = get_be16(&b);
  1821. audiotrack->frame_size = get_be16(&b);
  1822. audiotrack->sub_packet_size = get_be16(&b);
  1823. audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
  1824. if (codec_id == CODEC_ID_RA_288) {
  1825. audiotrack->block_align = audiotrack->coded_framesize;
  1826. track->codec_priv_size = 0;
  1827. } else {
  1828. audiotrack->block_align = audiotrack->sub_packet_size;
  1829. extradata_offset = 78;
  1830. track->codec_priv_size -= extradata_offset;
  1831. }
  1832. }
  1833. else if (codec_id == CODEC_ID_TEXT) {
  1834. MatroskaSubtitleTrack *subtrack=(MatroskaSubtitleTrack *)track;
  1835. if (!strcmp(track->codec_id, "S_TEXT/ASS") ||
  1836. !strcmp(track->codec_id, "S_TEXT/SSA") ||
  1837. !strcmp(track->codec_id, "S_ASS") ||
  1838. !strcmp(track->codec_id, "S_SSA"))
  1839. subtrack->ass = 1;
  1840. }
  1841. if (codec_id == CODEC_ID_NONE) {
  1842. av_log(matroska->ctx, AV_LOG_INFO,
  1843. "Unknown/unsupported CodecID %s.\n",
  1844. track->codec_id);
  1845. }
  1846. track->stream_index = matroska->num_streams;
  1847. matroska->num_streams++;
  1848. st = av_new_stream(s, track->stream_index);
  1849. if (st == NULL)
  1850. return AVERROR(ENOMEM);
  1851. av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1852. st->codec->codec_id = codec_id;
  1853. st->start_time = 0;
  1854. if (strcmp(track->language, "und"))
  1855. strcpy(st->language, track->language);
  1856. if (track->default_duration)
  1857. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1858. track->default_duration, 1000, 30000);
  1859. if(extradata){
  1860. st->codec->extradata = extradata;
  1861. st->codec->extradata_size = extradata_size;
  1862. } else if(track->codec_priv && track->codec_priv_size > 0){
  1863. st->codec->extradata = av_malloc(track->codec_priv_size);
  1864. if(st->codec->extradata == NULL)
  1865. return AVERROR(ENOMEM);
  1866. st->codec->extradata_size = track->codec_priv_size;
  1867. memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
  1868. track->codec_priv_size);
  1869. }
  1870. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1871. MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
  1872. st->codec->codec_type = CODEC_TYPE_VIDEO;
  1873. st->codec->codec_tag = videotrack->fourcc;
  1874. st->codec->width = videotrack->pixel_width;
  1875. st->codec->height = videotrack->pixel_height;
  1876. if (videotrack->display_width == 0)
  1877. videotrack->display_width= videotrack->pixel_width;
  1878. if (videotrack->display_height == 0)
  1879. videotrack->display_height= videotrack->pixel_height;
  1880. av_reduce(&st->codec->sample_aspect_ratio.num,
  1881. &st->codec->sample_aspect_ratio.den,
  1882. st->codec->height * videotrack->display_width,
  1883. st->codec-> width * videotrack->display_height,
  1884. 255);
  1885. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1886. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1887. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1888. st->codec->codec_type = CODEC_TYPE_AUDIO;
  1889. st->codec->sample_rate = audiotrack->samplerate;
  1890. st->codec->channels = audiotrack->channels;
  1891. st->codec->block_align = audiotrack->block_align;
  1892. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1893. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  1894. }
  1895. /* What do we do with private data? E.g. for Vorbis. */
  1896. }
  1897. res = 0;
  1898. }
  1899. if (matroska->index_parsed) {
  1900. int i, track, stream;
  1901. for (i=0; i<matroska->num_indexes; i++) {
  1902. MatroskaDemuxIndex *idx = &matroska->index[i];
  1903. track = matroska_find_track_by_num(matroska, idx->track);
  1904. stream = matroska->tracks[track]->stream_index;
  1905. if (stream >= 0)
  1906. av_add_index_entry(matroska->ctx->streams[stream],
  1907. idx->pos, idx->time/matroska->time_scale,
  1908. 0, 0, AVINDEX_KEYFRAME);
  1909. }
  1910. }
  1911. return res;
  1912. }
  1913. static inline int
  1914. rv_offset(uint8_t *data, int slice, int slices)
  1915. {
  1916. return AV_RL32(data+8*slice+4) + 8*slices;
  1917. }
  1918. static int
  1919. matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
  1920. int64_t pos, uint64_t cluster_time, uint64_t duration,
  1921. int is_keyframe, int is_bframe)
  1922. {
  1923. int res = 0;
  1924. int track;
  1925. AVStream *st;
  1926. AVPacket *pkt;
  1927. uint8_t *origdata = data;
  1928. int16_t block_time;
  1929. uint32_t *lace_size = NULL;
  1930. int n, flags, laces = 0;
  1931. uint64_t num;
  1932. /* first byte(s): tracknum */
  1933. if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
  1934. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1935. av_free(origdata);
  1936. return res;
  1937. }
  1938. data += n;
  1939. size -= n;
  1940. /* fetch track from num */
  1941. track = matroska_find_track_by_num(matroska, num);
  1942. if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
  1943. av_log(matroska->ctx, AV_LOG_INFO,
  1944. "Invalid stream %d or size %u\n", track, size);
  1945. av_free(origdata);
  1946. return res;
  1947. }
  1948. if (matroska->tracks[track]->stream_index < 0)
  1949. return res;
  1950. st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
  1951. if (st->discard >= AVDISCARD_ALL) {
  1952. av_free(origdata);
  1953. return res;
  1954. }
  1955. if (duration == AV_NOPTS_VALUE)
  1956. duration = matroska->tracks[track]->default_duration;
  1957. /* block_time (relative to cluster time) */
  1958. block_time = AV_RB16(data);
  1959. data += 2;
  1960. flags = *data++;
  1961. size -= 3;
  1962. if (is_keyframe == -1)
  1963. is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
  1964. if (matroska->skip_to_keyframe) {
  1965. if (!is_keyframe || st != matroska->skip_to_stream)
  1966. return res;
  1967. matroska->skip_to_keyframe = 0;
  1968. }
  1969. switch ((flags & 0x06) >> 1) {
  1970. case 0x0: /* no lacing */
  1971. laces = 1;
  1972. lace_size = av_mallocz(sizeof(int));
  1973. lace_size[0] = size;
  1974. break;
  1975. case 0x1: /* xiph lacing */
  1976. case 0x2: /* fixed-size lacing */
  1977. case 0x3: /* EBML lacing */
  1978. if (size == 0) {
  1979. res = -1;
  1980. break;
  1981. }
  1982. laces = (*data) + 1;
  1983. data += 1;
  1984. size -= 1;
  1985. lace_size = av_mallocz(laces * sizeof(int));
  1986. switch ((flags & 0x06) >> 1) {
  1987. case 0x1: /* xiph lacing */ {
  1988. uint8_t temp;
  1989. uint32_t total = 0;
  1990. for (n = 0; res == 0 && n < laces - 1; n++) {
  1991. while (1) {
  1992. if (size == 0) {
  1993. res = -1;
  1994. break;
  1995. }
  1996. temp = *data;
  1997. lace_size[n] += temp;
  1998. data += 1;
  1999. size -= 1;
  2000. if (temp != 0xff)
  2001. break;
  2002. }
  2003. total += lace_size[n];
  2004. }
  2005. lace_size[n] = size - total;
  2006. break;
  2007. }
  2008. case 0x2: /* fixed-size lacing */
  2009. for (n = 0; n < laces; n++)
  2010. lace_size[n] = size / laces;
  2011. break;
  2012. case 0x3: /* EBML lacing */ {
  2013. uint32_t total;
  2014. n = matroska_ebmlnum_uint(data, size, &num);
  2015. if (n < 0) {
  2016. av_log(matroska->ctx, AV_LOG_INFO,
  2017. "EBML block data error\n");
  2018. break;
  2019. }
  2020. data += n;
  2021. size -= n;
  2022. total = lace_size[0] = num;
  2023. for (n = 1; res == 0 && n < laces - 1; n++) {
  2024. int64_t snum;
  2025. int r;
  2026. r = matroska_ebmlnum_sint (data, size, &snum);
  2027. if (r < 0) {
  2028. av_log(matroska->ctx, AV_LOG_INFO,
  2029. "EBML block data error\n");
  2030. break;
  2031. }
  2032. data += r;
  2033. size -= r;
  2034. lace_size[n] = lace_size[n - 1] + snum;
  2035. total += lace_size[n];
  2036. }
  2037. lace_size[n] = size - total;
  2038. break;
  2039. }
  2040. }
  2041. break;
  2042. }
  2043. if (res == 0) {
  2044. int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
  2045. uint64_t timecode = AV_NOPTS_VALUE;
  2046. if (cluster_time != (uint64_t)-1 && cluster_time + block_time >= 0)
  2047. timecode = cluster_time + block_time;
  2048. for (n = 0; n < laces; n++) {
  2049. int slice, slices = 1;
  2050. if (real_v) {
  2051. slices = *data++ + 1;
  2052. lace_size[n]--;
  2053. }
  2054. for (slice=0; slice<slices; slice++) {
  2055. int slice_size, slice_offset = 0;
  2056. if (real_v)
  2057. slice_offset = rv_offset(data, slice, slices);
  2058. if (slice+1 == slices)
  2059. slice_size = lace_size[n] - slice_offset;
  2060. else
  2061. slice_size = rv_offset(data, slice+1, slices) - slice_offset;
  2062. if (st->codec->codec_id == CODEC_ID_RA_288 ||
  2063. st->codec->codec_id == CODEC_ID_COOK ||
  2064. st->codec->codec_id == CODEC_ID_ATRAC3) {
  2065. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
  2066. int a = st->codec->block_align;
  2067. int sps = audiotrack->sub_packet_size;
  2068. int cfs = audiotrack->coded_framesize;
  2069. int h = audiotrack->sub_packet_h;
  2070. int y = audiotrack->sub_packet_cnt;
  2071. int w = audiotrack->frame_size;
  2072. int x;
  2073. if (!audiotrack->pkt_cnt) {
  2074. if (st->codec->codec_id == CODEC_ID_RA_288)
  2075. for (x=0; x<h/2; x++)
  2076. memcpy(audiotrack->buf+x*2*w+y*cfs,
  2077. data+x*cfs, cfs);
  2078. else
  2079. for (x=0; x<w/sps; x++)
  2080. memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  2081. if (++audiotrack->sub_packet_cnt >= h) {
  2082. audiotrack->sub_packet_cnt = 0;
  2083. audiotrack->pkt_cnt = h*w / a;
  2084. }
  2085. }
  2086. while (audiotrack->pkt_cnt) {
  2087. pkt = av_mallocz(sizeof(AVPacket));
  2088. av_new_packet(pkt, a);
  2089. memcpy(pkt->data, audiotrack->buf
  2090. + a * (h*w / a - audiotrack->pkt_cnt--), a);
  2091. pkt->pos = pos;
  2092. pkt->stream_index = matroska->tracks[track]->stream_index;
  2093. matroska_queue_packet(matroska, pkt);
  2094. }
  2095. } else {
  2096. int offset = 0;
  2097. if (st->codec->codec_id == CODEC_ID_TEXT
  2098. && ((MatroskaSubtitleTrack *)(matroska->tracks[track]))->ass) {
  2099. int i;
  2100. for (i=0; i<8 && data[slice_offset+offset]; offset++)
  2101. if (data[slice_offset+offset] == ',')
  2102. i++;
  2103. }
  2104. pkt = av_mallocz(sizeof(AVPacket));
  2105. /* XXX: prevent data copy... */
  2106. if (av_new_packet(pkt, slice_size-offset) < 0) {
  2107. res = AVERROR(ENOMEM);
  2108. n = laces-1;
  2109. break;
  2110. }
  2111. memcpy (pkt->data, data+slice_offset+offset, slice_size-offset);
  2112. if (n == 0)
  2113. pkt->flags = is_keyframe;
  2114. pkt->stream_index = matroska->tracks[track]->stream_index;
  2115. pkt->pts = timecode;
  2116. pkt->pos = pos;
  2117. pkt->duration = duration;
  2118. matroska_queue_packet(matroska, pkt);
  2119. }
  2120. if (timecode != AV_NOPTS_VALUE)
  2121. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  2122. }
  2123. data += lace_size[n];
  2124. }
  2125. }
  2126. av_free(lace_size);
  2127. av_free(origdata);
  2128. return res;
  2129. }
  2130. static int
  2131. matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
  2132. uint64_t cluster_time)
  2133. {
  2134. int res = 0;
  2135. uint32_t id;
  2136. int is_bframe = 0;
  2137. int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
  2138. uint64_t duration = AV_NOPTS_VALUE;
  2139. uint8_t *data;
  2140. int size = 0;
  2141. int64_t pos = 0;
  2142. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
  2143. while (res == 0) {
  2144. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2145. res = AVERROR(EIO);
  2146. break;
  2147. } else if (matroska->level_up) {
  2148. matroska->level_up--;
  2149. break;
  2150. }
  2151. switch (id) {
  2152. /* one block inside the group. Note, block parsing is one
  2153. * of the harder things, so this code is a bit complicated.
  2154. * See http://www.matroska.org/ for documentation. */
  2155. case MATROSKA_ID_BLOCK: {
  2156. pos = url_ftell(&matroska->ctx->pb);
  2157. res = ebml_read_binary(matroska, &id, &data, &size);
  2158. break;
  2159. }
  2160. case MATROSKA_ID_BLOCKDURATION: {
  2161. if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
  2162. break;
  2163. break;
  2164. }
  2165. case MATROSKA_ID_BLOCKREFERENCE: {
  2166. int64_t num;
  2167. /* We've found a reference, so not even the first frame in
  2168. * the lace is a key frame. */
  2169. is_keyframe = 0;
  2170. if (last_num_packets != matroska->num_packets)
  2171. matroska->packets[last_num_packets]->flags = 0;
  2172. if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
  2173. break;
  2174. if (num > 0)
  2175. is_bframe = 1;
  2176. break;
  2177. }
  2178. default:
  2179. av_log(matroska->ctx, AV_LOG_INFO,
  2180. "Unknown entry 0x%x in blockgroup data\n", id);
  2181. /* fall-through */
  2182. case EBML_ID_VOID:
  2183. res = ebml_read_skip(matroska);
  2184. break;
  2185. }
  2186. if (matroska->level_up) {
  2187. matroska->level_up--;
  2188. break;
  2189. }
  2190. }
  2191. if (res)
  2192. return res;
  2193. if (size > 0)
  2194. res = matroska_parse_block(matroska, data, size, pos, cluster_time,
  2195. duration, is_keyframe, is_bframe);
  2196. return res;
  2197. }
  2198. static int
  2199. matroska_parse_cluster (MatroskaDemuxContext *matroska)
  2200. {
  2201. int res = 0;
  2202. uint32_t id;
  2203. uint64_t cluster_time = 0;
  2204. uint8_t *data;
  2205. int64_t pos;
  2206. int size;
  2207. av_log(matroska->ctx, AV_LOG_DEBUG,
  2208. "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
  2209. while (res == 0) {
  2210. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2211. res = AVERROR(EIO);
  2212. break;
  2213. } else if (matroska->level_up) {
  2214. matroska->level_up--;
  2215. break;
  2216. }
  2217. switch (id) {
  2218. /* cluster timecode */
  2219. case MATROSKA_ID_CLUSTERTIMECODE: {
  2220. uint64_t num;
  2221. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  2222. break;
  2223. cluster_time = num;
  2224. break;
  2225. }
  2226. /* a group of blocks inside a cluster */
  2227. case MATROSKA_ID_BLOCKGROUP:
  2228. if ((res = ebml_read_master(matroska, &id)) < 0)
  2229. break;
  2230. res = matroska_parse_blockgroup(matroska, cluster_time);
  2231. break;
  2232. case MATROSKA_ID_SIMPLEBLOCK:
  2233. pos = url_ftell(&matroska->ctx->pb);
  2234. res = ebml_read_binary(matroska, &id, &data, &size);
  2235. if (res == 0)
  2236. res = matroska_parse_block(matroska, data, size, pos,
  2237. cluster_time, AV_NOPTS_VALUE,
  2238. -1, 0);
  2239. break;
  2240. default:
  2241. av_log(matroska->ctx, AV_LOG_INFO,
  2242. "Unknown entry 0x%x in cluster data\n", id);
  2243. /* fall-through */
  2244. case EBML_ID_VOID:
  2245. res = ebml_read_skip(matroska);
  2246. break;
  2247. }
  2248. if (matroska->level_up) {
  2249. matroska->level_up--;
  2250. break;
  2251. }
  2252. }
  2253. return res;
  2254. }
  2255. static int
  2256. matroska_read_packet (AVFormatContext *s,
  2257. AVPacket *pkt)
  2258. {
  2259. MatroskaDemuxContext *matroska = s->priv_data;
  2260. int res;
  2261. uint32_t id;
  2262. /* Read stream until we have a packet queued. */
  2263. while (matroska_deliver_packet(matroska, pkt)) {
  2264. /* Have we already reached the end? */
  2265. if (matroska->done)
  2266. return AVERROR(EIO);
  2267. res = 0;
  2268. while (res == 0) {
  2269. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2270. return AVERROR(EIO);
  2271. } else if (matroska->level_up) {
  2272. matroska->level_up--;
  2273. break;
  2274. }
  2275. switch (id) {
  2276. case MATROSKA_ID_CLUSTER:
  2277. if ((res = ebml_read_master(matroska, &id)) < 0)
  2278. break;
  2279. if ((res = matroska_parse_cluster(matroska)) == 0)
  2280. res = 1; /* Parsed one cluster, let's get out. */
  2281. break;
  2282. default:
  2283. case EBML_ID_VOID:
  2284. res = ebml_read_skip(matroska);
  2285. break;
  2286. }
  2287. if (matroska->level_up) {
  2288. matroska->level_up--;
  2289. break;
  2290. }
  2291. }
  2292. if (res == -1)
  2293. matroska->done = 1;
  2294. }
  2295. return 0;
  2296. }
  2297. static int
  2298. matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
  2299. int flags)
  2300. {
  2301. MatroskaDemuxContext *matroska = s->priv_data;
  2302. AVStream *st = s->streams[stream_index];
  2303. int index;
  2304. /* find index entry */
  2305. index = av_index_search_timestamp(st, timestamp, flags);
  2306. if (index < 0)
  2307. return 0;
  2308. /* do the seek */
  2309. url_fseek(&s->pb, st->index_entries[index].pos, SEEK_SET);
  2310. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2311. matroska->skip_to_stream = st;
  2312. matroska->num_packets = 0;
  2313. matroska->peek_id = 0;
  2314. return 0;
  2315. }
  2316. static int
  2317. matroska_read_close (AVFormatContext *s)
  2318. {
  2319. MatroskaDemuxContext *matroska = s->priv_data;
  2320. int n = 0;
  2321. av_free(matroska->writing_app);
  2322. av_free(matroska->muxing_app);
  2323. av_free(matroska->index);
  2324. if (matroska->packets != NULL) {
  2325. for (n = 0; n < matroska->num_packets; n++) {
  2326. av_free_packet(matroska->packets[n]);
  2327. av_free(matroska->packets[n]);
  2328. }
  2329. av_free(matroska->packets);
  2330. }
  2331. for (n = 0; n < matroska->num_tracks; n++) {
  2332. MatroskaTrack *track = matroska->tracks[n];
  2333. av_free(track->codec_id);
  2334. av_free(track->codec_name);
  2335. av_free(track->codec_priv);
  2336. av_free(track->name);
  2337. if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  2338. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  2339. av_free(audiotrack->buf);
  2340. }
  2341. av_free(track);
  2342. }
  2343. return 0;
  2344. }
  2345. AVInputFormat matroska_demuxer = {
  2346. "matroska",
  2347. "Matroska file format",
  2348. sizeof(MatroskaDemuxContext),
  2349. matroska_probe,
  2350. matroska_read_header,
  2351. matroska_read_packet,
  2352. matroska_read_close,
  2353. matroska_read_seek,
  2354. };