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