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.

2723 lines
86KB

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