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.

2846 lines
90KB

  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. static int
  1592. matroska_parse_attachments(AVFormatContext *s)
  1593. {
  1594. MatroskaDemuxContext *matroska = s->priv_data;
  1595. int res = 0;
  1596. uint32_t id;
  1597. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing attachments...\n");
  1598. while (res == 0) {
  1599. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1600. res = AVERROR(EIO);
  1601. break;
  1602. } else if (matroska->level_up) {
  1603. matroska->level_up--;
  1604. break;
  1605. }
  1606. switch (id) {
  1607. case MATROSKA_ID_ATTACHEDFILE: {
  1608. char* name = NULL;
  1609. char* mime = NULL;
  1610. uint8_t* data = NULL;
  1611. int i, data_size = 0;
  1612. AVStream *st;
  1613. if ((res = ebml_read_master(matroska, &id)) < 0)
  1614. break;
  1615. while (res == 0) {
  1616. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1617. res = AVERROR(EIO);
  1618. break;
  1619. } else if (matroska->level_up) {
  1620. matroska->level_up--;
  1621. break;
  1622. }
  1623. switch (id) {
  1624. case MATROSKA_ID_FILENAME:
  1625. res = ebml_read_utf8 (matroska, &id, &name);
  1626. break;
  1627. case MATROSKA_ID_FILEMIMETYPE:
  1628. res = ebml_read_ascii (matroska, &id, &mime);
  1629. break;
  1630. case MATROSKA_ID_FILEDATA:
  1631. res = ebml_read_binary(matroska, &id, &data, &data_size);
  1632. break;
  1633. default:
  1634. av_log(matroska->ctx, AV_LOG_INFO,
  1635. "Unknown attachedfile ID 0x%x\n", id);
  1636. case EBML_ID_VOID:
  1637. res = ebml_read_skip(matroska);
  1638. break;
  1639. }
  1640. if (matroska->level_up) {
  1641. matroska->level_up--;
  1642. break;
  1643. }
  1644. }
  1645. if (!(name && mime && data && data_size > 0)) {
  1646. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1647. break;
  1648. }
  1649. st = av_new_stream(s, matroska->num_streams++);
  1650. if (st == NULL)
  1651. return AVERROR(ENOMEM);
  1652. st->filename = av_strdup(name);
  1653. st->codec->codec_id = CODEC_ID_NONE;
  1654. st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
  1655. st->codec->extradata = av_malloc(data_size);
  1656. if(st->codec->extradata == NULL)
  1657. return AVERROR(ENOMEM);
  1658. st->codec->extradata_size = data_size;
  1659. memcpy(st->codec->extradata, data, data_size);
  1660. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1661. if (!strncmp(ff_mkv_mime_tags[i].str, mime,
  1662. strlen(ff_mkv_mime_tags[i].str))) {
  1663. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1664. break;
  1665. }
  1666. }
  1667. av_log(matroska->ctx, AV_LOG_DEBUG, "new attachment: %s, %s, size %d \n", name, mime, data_size);
  1668. break;
  1669. }
  1670. default:
  1671. av_log(matroska->ctx, AV_LOG_INFO,
  1672. "Unknown attachments ID 0x%x\n", id);
  1673. /* fall-through */
  1674. case EBML_ID_VOID:
  1675. res = ebml_read_skip(matroska);
  1676. break;
  1677. }
  1678. if (matroska->level_up) {
  1679. matroska->level_up--;
  1680. break;
  1681. }
  1682. }
  1683. return res;
  1684. }
  1685. #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
  1686. static int
  1687. matroska_aac_profile (char *codec_id)
  1688. {
  1689. static const char *aac_profiles[] = {
  1690. "MAIN", "LC", "SSR"
  1691. };
  1692. int profile;
  1693. for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
  1694. if (strstr(codec_id, aac_profiles[profile]))
  1695. break;
  1696. return profile + 1;
  1697. }
  1698. static int
  1699. matroska_aac_sri (int samplerate)
  1700. {
  1701. static const int aac_sample_rates[] = {
  1702. 96000, 88200, 64000, 48000, 44100, 32000,
  1703. 24000, 22050, 16000, 12000, 11025, 8000,
  1704. };
  1705. int sri;
  1706. for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
  1707. if (aac_sample_rates[sri] == samplerate)
  1708. break;
  1709. return sri;
  1710. }
  1711. static int
  1712. matroska_read_header (AVFormatContext *s,
  1713. AVFormatParameters *ap)
  1714. {
  1715. MatroskaDemuxContext *matroska = s->priv_data;
  1716. char *doctype;
  1717. int version, last_level, res = 0;
  1718. uint32_t id;
  1719. matroska->ctx = s;
  1720. /* First read the EBML header. */
  1721. doctype = NULL;
  1722. if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
  1723. return res;
  1724. if ((doctype == NULL) || strcmp(doctype, "matroska")) {
  1725. av_log(matroska->ctx, AV_LOG_ERROR,
  1726. "Wrong EBML doctype ('%s' != 'matroska').\n",
  1727. doctype ? doctype : "(none)");
  1728. if (doctype)
  1729. av_free(doctype);
  1730. return AVERROR_NOFMT;
  1731. }
  1732. av_free(doctype);
  1733. if (version > 2) {
  1734. av_log(matroska->ctx, AV_LOG_ERROR,
  1735. "Matroska demuxer version 2 too old for file version %d\n",
  1736. version);
  1737. return AVERROR_NOFMT;
  1738. }
  1739. /* The next thing is a segment. */
  1740. while (1) {
  1741. if (!(id = ebml_peek_id(matroska, &last_level)))
  1742. return AVERROR(EIO);
  1743. if (id == MATROSKA_ID_SEGMENT)
  1744. break;
  1745. /* oi! */
  1746. av_log(matroska->ctx, AV_LOG_INFO,
  1747. "Expected a Segment ID (0x%x), but received 0x%x!\n",
  1748. MATROSKA_ID_SEGMENT, id);
  1749. if ((res = ebml_read_skip(matroska)) < 0)
  1750. return res;
  1751. }
  1752. /* We now have a Matroska segment.
  1753. * Seeks are from the beginning of the segment,
  1754. * after the segment ID/length. */
  1755. if ((res = ebml_read_master(matroska, &id)) < 0)
  1756. return res;
  1757. matroska->segment_start = url_ftell(s->pb);
  1758. matroska->time_scale = 1000000;
  1759. /* we've found our segment, start reading the different contents in here */
  1760. while (res == 0) {
  1761. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1762. res = AVERROR(EIO);
  1763. break;
  1764. } else if (matroska->level_up) {
  1765. matroska->level_up--;
  1766. break;
  1767. }
  1768. switch (id) {
  1769. /* stream info */
  1770. case MATROSKA_ID_INFO: {
  1771. if ((res = ebml_read_master(matroska, &id)) < 0)
  1772. break;
  1773. res = matroska_parse_info(matroska);
  1774. break;
  1775. }
  1776. /* track info headers */
  1777. case MATROSKA_ID_TRACKS: {
  1778. if ((res = ebml_read_master(matroska, &id)) < 0)
  1779. break;
  1780. res = matroska_parse_tracks(matroska);
  1781. break;
  1782. }
  1783. /* stream index */
  1784. case MATROSKA_ID_CUES: {
  1785. if (!matroska->index_parsed) {
  1786. if ((res = ebml_read_master(matroska, &id)) < 0)
  1787. break;
  1788. res = matroska_parse_index(matroska);
  1789. } else
  1790. res = ebml_read_skip(matroska);
  1791. break;
  1792. }
  1793. /* metadata */
  1794. case MATROSKA_ID_TAGS: {
  1795. if (!matroska->metadata_parsed) {
  1796. if ((res = ebml_read_master(matroska, &id)) < 0)
  1797. break;
  1798. res = matroska_parse_metadata(matroska);
  1799. } else
  1800. res = ebml_read_skip(matroska);
  1801. break;
  1802. }
  1803. /* file index (if seekable, seek to Cues/Tags to parse it) */
  1804. case MATROSKA_ID_SEEKHEAD: {
  1805. if ((res = ebml_read_master(matroska, &id)) < 0)
  1806. break;
  1807. res = matroska_parse_seekhead(matroska);
  1808. break;
  1809. }
  1810. case MATROSKA_ID_ATTACHMENTS: {
  1811. if ((res = ebml_read_master(matroska, &id)) < 0)
  1812. break;
  1813. res = matroska_parse_attachments(s);
  1814. break;
  1815. }
  1816. case MATROSKA_ID_CLUSTER: {
  1817. /* Do not read the master - this will be done in the next
  1818. * call to matroska_read_packet. */
  1819. res = 1;
  1820. break;
  1821. }
  1822. default:
  1823. av_log(matroska->ctx, AV_LOG_INFO,
  1824. "Unknown matroska file header ID 0x%x\n", id);
  1825. /* fall-through */
  1826. case EBML_ID_VOID:
  1827. res = ebml_read_skip(matroska);
  1828. break;
  1829. }
  1830. if (matroska->level_up) {
  1831. matroska->level_up--;
  1832. break;
  1833. }
  1834. }
  1835. /* Have we found a cluster? */
  1836. if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
  1837. int i, j;
  1838. MatroskaTrack *track;
  1839. AVStream *st;
  1840. for (i = 0; i < matroska->num_tracks; i++) {
  1841. enum CodecID codec_id = CODEC_ID_NONE;
  1842. uint8_t *extradata = NULL;
  1843. int extradata_size = 0;
  1844. int extradata_offset = 0;
  1845. track = matroska->tracks[i];
  1846. track->stream_index = -1;
  1847. /* Apply some sanity checks. */
  1848. if (track->codec_id == NULL)
  1849. continue;
  1850. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1851. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1852. strlen(ff_mkv_codec_tags[j].str))){
  1853. codec_id= ff_mkv_codec_tags[j].id;
  1854. break;
  1855. }
  1856. }
  1857. /* Set the FourCC from the CodecID. */
  1858. /* This is the MS compatibility mode which stores a
  1859. * BITMAPINFOHEADER in the CodecPrivate. */
  1860. if (!strcmp(track->codec_id,
  1861. MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
  1862. (track->codec_priv_size >= 40) &&
  1863. (track->codec_priv != NULL)) {
  1864. MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
  1865. /* Offset of biCompression. Stored in LE. */
  1866. vtrack->fourcc = AV_RL32(track->codec_priv + 16);
  1867. codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
  1868. }
  1869. /* This is the MS compatibility mode which stores a
  1870. * WAVEFORMATEX in the CodecPrivate. */
  1871. else if (!strcmp(track->codec_id,
  1872. MATROSKA_CODEC_ID_AUDIO_ACM) &&
  1873. (track->codec_priv_size >= 18) &&
  1874. (track->codec_priv != NULL)) {
  1875. uint16_t tag;
  1876. /* Offset of wFormatTag. Stored in LE. */
  1877. tag = AV_RL16(track->codec_priv);
  1878. codec_id = codec_get_id(codec_wav_tags, tag);
  1879. }
  1880. else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
  1881. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
  1882. int profile = matroska_aac_profile(track->codec_id);
  1883. int sri = matroska_aac_sri(audiotrack->internal_samplerate);
  1884. extradata = av_malloc(5);
  1885. if (extradata == NULL)
  1886. return AVERROR(ENOMEM);
  1887. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1888. extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
  1889. if (strstr(track->codec_id, "SBR")) {
  1890. sri = matroska_aac_sri(audiotrack->samplerate);
  1891. extradata[2] = 0x56;
  1892. extradata[3] = 0xE5;
  1893. extradata[4] = 0x80 | (sri<<3);
  1894. extradata_size = 5;
  1895. } else {
  1896. extradata_size = 2;
  1897. }
  1898. }
  1899. else if (codec_id == CODEC_ID_TTA) {
  1900. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
  1901. ByteIOContext b;
  1902. extradata_size = 30;
  1903. extradata = av_mallocz(extradata_size);
  1904. if (extradata == NULL)
  1905. return AVERROR(ENOMEM);
  1906. init_put_byte(&b, extradata, extradata_size, 1,
  1907. NULL, NULL, NULL, NULL);
  1908. put_buffer(&b, "TTA1", 4);
  1909. put_le16(&b, 1);
  1910. put_le16(&b, audiotrack->channels);
  1911. put_le16(&b, audiotrack->bitdepth);
  1912. put_le32(&b, audiotrack->samplerate);
  1913. put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
  1914. }
  1915. else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1916. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1917. extradata_offset = 26;
  1918. track->codec_priv_size -= extradata_offset;
  1919. }
  1920. else if (codec_id == CODEC_ID_RA_144) {
  1921. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1922. audiotrack->samplerate = 8000;
  1923. audiotrack->channels = 1;
  1924. }
  1925. else if (codec_id == CODEC_ID_RA_288 ||
  1926. codec_id == CODEC_ID_COOK ||
  1927. codec_id == CODEC_ID_ATRAC3) {
  1928. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1929. ByteIOContext b;
  1930. init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
  1931. NULL, NULL, NULL, NULL);
  1932. url_fskip(&b, 24);
  1933. audiotrack->coded_framesize = get_be32(&b);
  1934. url_fskip(&b, 12);
  1935. audiotrack->sub_packet_h = get_be16(&b);
  1936. audiotrack->frame_size = get_be16(&b);
  1937. audiotrack->sub_packet_size = get_be16(&b);
  1938. audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
  1939. if (codec_id == CODEC_ID_RA_288) {
  1940. audiotrack->block_align = audiotrack->coded_framesize;
  1941. track->codec_priv_size = 0;
  1942. } else {
  1943. audiotrack->block_align = audiotrack->sub_packet_size;
  1944. extradata_offset = 78;
  1945. track->codec_priv_size -= extradata_offset;
  1946. }
  1947. }
  1948. if (codec_id == CODEC_ID_NONE) {
  1949. av_log(matroska->ctx, AV_LOG_INFO,
  1950. "Unknown/unsupported CodecID %s.\n",
  1951. track->codec_id);
  1952. }
  1953. track->stream_index = matroska->num_streams;
  1954. matroska->num_streams++;
  1955. st = av_new_stream(s, track->stream_index);
  1956. if (st == NULL)
  1957. return AVERROR(ENOMEM);
  1958. av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1959. st->codec->codec_id = codec_id;
  1960. st->start_time = 0;
  1961. if (strcmp(track->language, "und"))
  1962. strcpy(st->language, track->language);
  1963. if (track->flags & MATROSKA_TRACK_DEFAULT)
  1964. st->disposition |= AV_DISPOSITION_DEFAULT;
  1965. if (track->default_duration)
  1966. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1967. track->default_duration, 1000000000, 30000);
  1968. if(extradata){
  1969. st->codec->extradata = extradata;
  1970. st->codec->extradata_size = extradata_size;
  1971. } else if(track->codec_priv && track->codec_priv_size > 0){
  1972. st->codec->extradata = av_malloc(track->codec_priv_size);
  1973. if(st->codec->extradata == NULL)
  1974. return AVERROR(ENOMEM);
  1975. st->codec->extradata_size = track->codec_priv_size;
  1976. memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
  1977. track->codec_priv_size);
  1978. }
  1979. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1980. MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
  1981. st->codec->codec_type = CODEC_TYPE_VIDEO;
  1982. st->codec->codec_tag = videotrack->fourcc;
  1983. st->codec->width = videotrack->pixel_width;
  1984. st->codec->height = videotrack->pixel_height;
  1985. if (videotrack->display_width == 0)
  1986. videotrack->display_width= videotrack->pixel_width;
  1987. if (videotrack->display_height == 0)
  1988. videotrack->display_height= videotrack->pixel_height;
  1989. av_reduce(&st->codec->sample_aspect_ratio.num,
  1990. &st->codec->sample_aspect_ratio.den,
  1991. st->codec->height * videotrack->display_width,
  1992. st->codec-> width * videotrack->display_height,
  1993. 255);
  1994. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1995. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1996. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1997. st->codec->codec_type = CODEC_TYPE_AUDIO;
  1998. st->codec->sample_rate = audiotrack->samplerate;
  1999. st->codec->channels = audiotrack->channels;
  2000. st->codec->block_align = audiotrack->block_align;
  2001. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  2002. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  2003. }
  2004. /* What do we do with private data? E.g. for Vorbis. */
  2005. }
  2006. res = 0;
  2007. }
  2008. if (matroska->index_parsed) {
  2009. int i, track, stream;
  2010. for (i=0; i<matroska->num_indexes; i++) {
  2011. MatroskaDemuxIndex *idx = &matroska->index[i];
  2012. track = matroska_find_track_by_num(matroska, idx->track);
  2013. stream = matroska->tracks[track]->stream_index;
  2014. if (stream >= 0)
  2015. av_add_index_entry(matroska->ctx->streams[stream],
  2016. idx->pos, idx->time/matroska->time_scale,
  2017. 0, 0, AVINDEX_KEYFRAME);
  2018. }
  2019. }
  2020. return res;
  2021. }
  2022. static int
  2023. matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
  2024. int64_t pos, uint64_t cluster_time, uint64_t duration,
  2025. int is_keyframe, int is_bframe)
  2026. {
  2027. int res = 0;
  2028. int track;
  2029. AVStream *st;
  2030. AVPacket *pkt;
  2031. uint8_t *origdata = data;
  2032. int16_t block_time;
  2033. uint32_t *lace_size = NULL;
  2034. int n, flags, laces = 0;
  2035. uint64_t num;
  2036. /* first byte(s): tracknum */
  2037. if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
  2038. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  2039. av_free(origdata);
  2040. return res;
  2041. }
  2042. data += n;
  2043. size -= n;
  2044. /* fetch track from num */
  2045. track = matroska_find_track_by_num(matroska, num);
  2046. if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
  2047. av_log(matroska->ctx, AV_LOG_INFO,
  2048. "Invalid stream %d or size %u\n", track, size);
  2049. av_free(origdata);
  2050. return res;
  2051. }
  2052. if (matroska->tracks[track]->stream_index < 0) {
  2053. av_free(origdata);
  2054. return res;
  2055. }
  2056. st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
  2057. if (st->discard >= AVDISCARD_ALL) {
  2058. av_free(origdata);
  2059. return res;
  2060. }
  2061. if (duration == AV_NOPTS_VALUE)
  2062. duration = matroska->tracks[track]->default_duration / matroska->time_scale;
  2063. /* block_time (relative to cluster time) */
  2064. block_time = AV_RB16(data);
  2065. data += 2;
  2066. flags = *data++;
  2067. size -= 3;
  2068. if (is_keyframe == -1)
  2069. is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
  2070. if (matroska->skip_to_keyframe) {
  2071. if (!is_keyframe || st != matroska->skip_to_stream) {
  2072. av_free(origdata);
  2073. return res;
  2074. }
  2075. matroska->skip_to_keyframe = 0;
  2076. }
  2077. switch ((flags & 0x06) >> 1) {
  2078. case 0x0: /* no lacing */
  2079. laces = 1;
  2080. lace_size = av_mallocz(sizeof(int));
  2081. lace_size[0] = size;
  2082. break;
  2083. case 0x1: /* xiph lacing */
  2084. case 0x2: /* fixed-size lacing */
  2085. case 0x3: /* EBML lacing */
  2086. if (size == 0) {
  2087. res = -1;
  2088. break;
  2089. }
  2090. laces = (*data) + 1;
  2091. data += 1;
  2092. size -= 1;
  2093. lace_size = av_mallocz(laces * sizeof(int));
  2094. switch ((flags & 0x06) >> 1) {
  2095. case 0x1: /* xiph lacing */ {
  2096. uint8_t temp;
  2097. uint32_t total = 0;
  2098. for (n = 0; res == 0 && n < laces - 1; n++) {
  2099. while (1) {
  2100. if (size == 0) {
  2101. res = -1;
  2102. break;
  2103. }
  2104. temp = *data;
  2105. lace_size[n] += temp;
  2106. data += 1;
  2107. size -= 1;
  2108. if (temp != 0xff)
  2109. break;
  2110. }
  2111. total += lace_size[n];
  2112. }
  2113. lace_size[n] = size - total;
  2114. break;
  2115. }
  2116. case 0x2: /* fixed-size lacing */
  2117. for (n = 0; n < laces; n++)
  2118. lace_size[n] = size / laces;
  2119. break;
  2120. case 0x3: /* EBML lacing */ {
  2121. uint32_t total;
  2122. n = matroska_ebmlnum_uint(data, size, &num);
  2123. if (n < 0) {
  2124. av_log(matroska->ctx, AV_LOG_INFO,
  2125. "EBML block data error\n");
  2126. break;
  2127. }
  2128. data += n;
  2129. size -= n;
  2130. total = lace_size[0] = num;
  2131. for (n = 1; res == 0 && n < laces - 1; n++) {
  2132. int64_t snum;
  2133. int r;
  2134. r = matroska_ebmlnum_sint (data, size, &snum);
  2135. if (r < 0) {
  2136. av_log(matroska->ctx, AV_LOG_INFO,
  2137. "EBML block data error\n");
  2138. break;
  2139. }
  2140. data += r;
  2141. size -= r;
  2142. lace_size[n] = lace_size[n - 1] + snum;
  2143. total += lace_size[n];
  2144. }
  2145. lace_size[n] = size - total;
  2146. break;
  2147. }
  2148. }
  2149. break;
  2150. }
  2151. if (res == 0) {
  2152. uint64_t timecode = AV_NOPTS_VALUE;
  2153. if (cluster_time != (uint64_t)-1
  2154. && (block_time >= 0 || cluster_time >= -block_time))
  2155. timecode = cluster_time + block_time;
  2156. for (n = 0; n < laces; n++) {
  2157. if (st->codec->codec_id == CODEC_ID_RA_288 ||
  2158. st->codec->codec_id == CODEC_ID_COOK ||
  2159. st->codec->codec_id == CODEC_ID_ATRAC3) {
  2160. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
  2161. int a = st->codec->block_align;
  2162. int sps = audiotrack->sub_packet_size;
  2163. int cfs = audiotrack->coded_framesize;
  2164. int h = audiotrack->sub_packet_h;
  2165. int y = audiotrack->sub_packet_cnt;
  2166. int w = audiotrack->frame_size;
  2167. int x;
  2168. if (!audiotrack->pkt_cnt) {
  2169. if (st->codec->codec_id == CODEC_ID_RA_288)
  2170. for (x=0; x<h/2; x++)
  2171. memcpy(audiotrack->buf+x*2*w+y*cfs,
  2172. data+x*cfs, cfs);
  2173. else
  2174. for (x=0; x<w/sps; x++)
  2175. memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  2176. if (++audiotrack->sub_packet_cnt >= h) {
  2177. audiotrack->sub_packet_cnt = 0;
  2178. audiotrack->pkt_cnt = h*w / a;
  2179. }
  2180. }
  2181. while (audiotrack->pkt_cnt) {
  2182. pkt = av_mallocz(sizeof(AVPacket));
  2183. av_new_packet(pkt, a);
  2184. memcpy(pkt->data, audiotrack->buf
  2185. + a * (h*w / a - audiotrack->pkt_cnt--), a);
  2186. pkt->pos = pos;
  2187. pkt->stream_index = matroska->tracks[track]->stream_index;
  2188. matroska_queue_packet(matroska, pkt);
  2189. }
  2190. } else {
  2191. int offset = 0;
  2192. pkt = av_mallocz(sizeof(AVPacket));
  2193. /* XXX: prevent data copy... */
  2194. if (av_new_packet(pkt, lace_size[n]-offset) < 0) {
  2195. res = AVERROR(ENOMEM);
  2196. n = laces-1;
  2197. break;
  2198. }
  2199. memcpy (pkt->data, data+offset, lace_size[n]-offset);
  2200. if (n == 0)
  2201. pkt->flags = is_keyframe;
  2202. pkt->stream_index = matroska->tracks[track]->stream_index;
  2203. pkt->pts = timecode;
  2204. pkt->pos = pos;
  2205. pkt->duration = duration;
  2206. matroska_queue_packet(matroska, pkt);
  2207. }
  2208. if (timecode != AV_NOPTS_VALUE)
  2209. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  2210. data += lace_size[n];
  2211. }
  2212. }
  2213. av_free(lace_size);
  2214. av_free(origdata);
  2215. return res;
  2216. }
  2217. static int
  2218. matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
  2219. uint64_t cluster_time)
  2220. {
  2221. int res = 0;
  2222. uint32_t id;
  2223. int is_bframe = 0;
  2224. int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
  2225. uint64_t duration = AV_NOPTS_VALUE;
  2226. uint8_t *data;
  2227. int size = 0;
  2228. int64_t pos = 0;
  2229. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
  2230. while (res == 0) {
  2231. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2232. res = AVERROR(EIO);
  2233. break;
  2234. } else if (matroska->level_up) {
  2235. matroska->level_up--;
  2236. break;
  2237. }
  2238. switch (id) {
  2239. /* one block inside the group. Note, block parsing is one
  2240. * of the harder things, so this code is a bit complicated.
  2241. * See http://www.matroska.org/ for documentation. */
  2242. case MATROSKA_ID_BLOCK: {
  2243. pos = url_ftell(matroska->ctx->pb);
  2244. res = ebml_read_binary(matroska, &id, &data, &size);
  2245. break;
  2246. }
  2247. case MATROSKA_ID_BLOCKDURATION: {
  2248. if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
  2249. break;
  2250. break;
  2251. }
  2252. case MATROSKA_ID_BLOCKREFERENCE: {
  2253. int64_t num;
  2254. /* We've found a reference, so not even the first frame in
  2255. * the lace is a key frame. */
  2256. is_keyframe = 0;
  2257. if (last_num_packets != matroska->num_packets)
  2258. matroska->packets[last_num_packets]->flags = 0;
  2259. if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
  2260. break;
  2261. if (num > 0)
  2262. is_bframe = 1;
  2263. break;
  2264. }
  2265. default:
  2266. av_log(matroska->ctx, AV_LOG_INFO,
  2267. "Unknown entry 0x%x in blockgroup data\n", id);
  2268. /* fall-through */
  2269. case EBML_ID_VOID:
  2270. res = ebml_read_skip(matroska);
  2271. break;
  2272. }
  2273. if (matroska->level_up) {
  2274. matroska->level_up--;
  2275. break;
  2276. }
  2277. }
  2278. if (res)
  2279. return res;
  2280. if (size > 0)
  2281. res = matroska_parse_block(matroska, data, size, pos, cluster_time,
  2282. duration, is_keyframe, is_bframe);
  2283. return res;
  2284. }
  2285. static int
  2286. matroska_parse_cluster (MatroskaDemuxContext *matroska)
  2287. {
  2288. int res = 0;
  2289. uint32_t id;
  2290. uint64_t cluster_time = 0;
  2291. uint8_t *data;
  2292. int64_t pos;
  2293. int size;
  2294. av_log(matroska->ctx, AV_LOG_DEBUG,
  2295. "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
  2296. while (res == 0) {
  2297. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2298. res = AVERROR(EIO);
  2299. break;
  2300. } else if (matroska->level_up) {
  2301. matroska->level_up--;
  2302. break;
  2303. }
  2304. switch (id) {
  2305. /* cluster timecode */
  2306. case MATROSKA_ID_CLUSTERTIMECODE: {
  2307. uint64_t num;
  2308. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  2309. break;
  2310. cluster_time = num;
  2311. break;
  2312. }
  2313. /* a group of blocks inside a cluster */
  2314. case MATROSKA_ID_BLOCKGROUP:
  2315. if ((res = ebml_read_master(matroska, &id)) < 0)
  2316. break;
  2317. res = matroska_parse_blockgroup(matroska, cluster_time);
  2318. break;
  2319. case MATROSKA_ID_SIMPLEBLOCK:
  2320. pos = url_ftell(matroska->ctx->pb);
  2321. res = ebml_read_binary(matroska, &id, &data, &size);
  2322. if (res == 0)
  2323. res = matroska_parse_block(matroska, data, size, pos,
  2324. cluster_time, AV_NOPTS_VALUE,
  2325. -1, 0);
  2326. break;
  2327. default:
  2328. av_log(matroska->ctx, AV_LOG_INFO,
  2329. "Unknown entry 0x%x in cluster data\n", id);
  2330. /* fall-through */
  2331. case EBML_ID_VOID:
  2332. res = ebml_read_skip(matroska);
  2333. break;
  2334. }
  2335. if (matroska->level_up) {
  2336. matroska->level_up--;
  2337. break;
  2338. }
  2339. }
  2340. return res;
  2341. }
  2342. static int
  2343. matroska_read_packet (AVFormatContext *s,
  2344. AVPacket *pkt)
  2345. {
  2346. MatroskaDemuxContext *matroska = s->priv_data;
  2347. int res;
  2348. uint32_t id;
  2349. /* Read stream until we have a packet queued. */
  2350. while (matroska_deliver_packet(matroska, pkt)) {
  2351. /* Have we already reached the end? */
  2352. if (matroska->done)
  2353. return AVERROR(EIO);
  2354. res = 0;
  2355. while (res == 0) {
  2356. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2357. return AVERROR(EIO);
  2358. } else if (matroska->level_up) {
  2359. matroska->level_up--;
  2360. break;
  2361. }
  2362. switch (id) {
  2363. case MATROSKA_ID_CLUSTER:
  2364. if ((res = ebml_read_master(matroska, &id)) < 0)
  2365. break;
  2366. if ((res = matroska_parse_cluster(matroska)) == 0)
  2367. res = 1; /* Parsed one cluster, let's get out. */
  2368. break;
  2369. default:
  2370. case EBML_ID_VOID:
  2371. res = ebml_read_skip(matroska);
  2372. break;
  2373. }
  2374. if (matroska->level_up) {
  2375. matroska->level_up--;
  2376. break;
  2377. }
  2378. }
  2379. if (res == -1)
  2380. matroska->done = 1;
  2381. }
  2382. return 0;
  2383. }
  2384. static int
  2385. matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
  2386. int flags)
  2387. {
  2388. MatroskaDemuxContext *matroska = s->priv_data;
  2389. AVStream *st = s->streams[stream_index];
  2390. int index;
  2391. /* find index entry */
  2392. index = av_index_search_timestamp(st, timestamp, flags);
  2393. if (index < 0)
  2394. return 0;
  2395. matroska_clear_queue(matroska);
  2396. /* do the seek */
  2397. url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
  2398. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2399. matroska->skip_to_stream = st;
  2400. matroska->peek_id = 0;
  2401. return 0;
  2402. }
  2403. static int
  2404. matroska_read_close (AVFormatContext *s)
  2405. {
  2406. MatroskaDemuxContext *matroska = s->priv_data;
  2407. int n = 0;
  2408. av_free(matroska->writing_app);
  2409. av_free(matroska->muxing_app);
  2410. av_free(matroska->index);
  2411. matroska_clear_queue(matroska);
  2412. for (n = 0; n < matroska->num_tracks; n++) {
  2413. MatroskaTrack *track = matroska->tracks[n];
  2414. av_free(track->codec_id);
  2415. av_free(track->codec_name);
  2416. av_free(track->codec_priv);
  2417. av_free(track->name);
  2418. if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  2419. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  2420. av_free(audiotrack->buf);
  2421. }
  2422. av_free(track);
  2423. }
  2424. return 0;
  2425. }
  2426. AVInputFormat matroska_demuxer = {
  2427. "matroska",
  2428. "Matroska file format",
  2429. sizeof(MatroskaDemuxContext),
  2430. matroska_probe,
  2431. matroska_read_header,
  2432. matroska_read_packet,
  2433. matroska_read_close,
  2434. matroska_read_seek,
  2435. };