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.

2728 lines
87KB

  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;
  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_IO; /* 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. assert(level_up != NULL);
  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_NOMEM;
  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_IO;
  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_NOTSUPP;
  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_NOMEM;
  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_IO;
  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_IO;
  577. /* end-of-header */
  578. if (level_up)
  579. break;
  580. switch (id) {
  581. /* is our read version uptodate? */
  582. case EBML_ID_EBMLREADVERSION: {
  583. uint64_t num;
  584. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  585. return res;
  586. if (num > EBML_VERSION) {
  587. av_log(matroska->ctx, AV_LOG_ERROR,
  588. "EBML version %"PRIu64" (> %d) is not supported\n",
  589. num, EBML_VERSION);
  590. return AVERROR_INVALIDDATA;
  591. }
  592. break;
  593. }
  594. /* we only handle 8 byte lengths at max */
  595. case EBML_ID_EBMLMAXSIZELENGTH: {
  596. uint64_t num;
  597. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  598. return res;
  599. if (num > sizeof(uint64_t)) {
  600. av_log(matroska->ctx, AV_LOG_ERROR,
  601. "Integers of size %"PRIu64" (> %zd) not supported\n",
  602. num, sizeof(uint64_t));
  603. return AVERROR_INVALIDDATA;
  604. }
  605. break;
  606. }
  607. /* we handle 4 byte IDs at max */
  608. case EBML_ID_EBMLMAXIDLENGTH: {
  609. uint64_t num;
  610. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  611. return res;
  612. if (num > sizeof(uint32_t)) {
  613. av_log(matroska->ctx, AV_LOG_ERROR,
  614. "IDs of size %"PRIu64" (> %zu) not supported\n",
  615. num, sizeof(uint32_t));
  616. return AVERROR_INVALIDDATA;
  617. }
  618. break;
  619. }
  620. case EBML_ID_DOCTYPE: {
  621. char *text;
  622. if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
  623. return res;
  624. if (doctype) {
  625. if (*doctype)
  626. av_free(*doctype);
  627. *doctype = text;
  628. } else
  629. av_free(text);
  630. break;
  631. }
  632. case EBML_ID_DOCTYPEREADVERSION: {
  633. uint64_t num;
  634. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  635. return res;
  636. if (version)
  637. *version = num;
  638. break;
  639. }
  640. default:
  641. av_log(matroska->ctx, AV_LOG_INFO,
  642. "Unknown data type 0x%x in EBML header", id);
  643. /* pass-through */
  644. case EBML_ID_VOID:
  645. /* we ignore these two, as they don't tell us anything we
  646. * care about */
  647. case EBML_ID_EBMLVERSION:
  648. case EBML_ID_DOCTYPEVERSION:
  649. res = ebml_read_skip (matroska);
  650. break;
  651. }
  652. }
  653. return 0;
  654. }
  655. static int
  656. matroska_find_track_by_num (MatroskaDemuxContext *matroska,
  657. int num)
  658. {
  659. int i;
  660. for (i = 0; i < matroska->num_tracks; i++)
  661. if (matroska->tracks[i]->num == num)
  662. return i;
  663. return -1;
  664. }
  665. /*
  666. * Put one packet in an application-supplied AVPacket struct.
  667. * Returns 0 on success or -1 on failure.
  668. */
  669. static int
  670. matroska_deliver_packet (MatroskaDemuxContext *matroska,
  671. AVPacket *pkt)
  672. {
  673. if (matroska->num_packets > 0) {
  674. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  675. av_free(matroska->packets[0]);
  676. if (matroska->num_packets > 1) {
  677. memmove(&matroska->packets[0], &matroska->packets[1],
  678. (matroska->num_packets - 1) * sizeof(AVPacket *));
  679. matroska->packets =
  680. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  681. sizeof(AVPacket *));
  682. } else {
  683. av_freep(&matroska->packets);
  684. }
  685. matroska->num_packets--;
  686. return 0;
  687. }
  688. return -1;
  689. }
  690. /*
  691. * Put a packet into our internal queue. Will be delivered to the
  692. * user/application during the next get_packet() call.
  693. */
  694. static void
  695. matroska_queue_packet (MatroskaDemuxContext *matroska,
  696. AVPacket *pkt)
  697. {
  698. matroska->packets =
  699. av_realloc(matroska->packets, (matroska->num_packets + 1) *
  700. sizeof(AVPacket *));
  701. matroska->packets[matroska->num_packets] = pkt;
  702. matroska->num_packets++;
  703. }
  704. /*
  705. * Autodetecting...
  706. */
  707. static int
  708. matroska_probe (AVProbeData *p)
  709. {
  710. uint64_t total = 0;
  711. int len_mask = 0x80, size = 1, n = 1;
  712. uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
  713. /* ebml header? */
  714. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  715. return 0;
  716. /* length of header */
  717. total = p->buf[4];
  718. while (size <= 8 && !(total & len_mask)) {
  719. size++;
  720. len_mask >>= 1;
  721. }
  722. if (size > 8)
  723. return 0;
  724. total &= (len_mask - 1);
  725. while (n < size)
  726. total = (total << 8) | p->buf[4 + n++];
  727. /* does the probe data contain the whole header? */
  728. if (p->buf_size < 4 + size + total)
  729. return 0;
  730. /* the header must contain the document type 'matroska'. For now,
  731. * we don't parse the whole header but simply check for the
  732. * availability of that array of characters inside the header.
  733. * Not fully fool-proof, but good enough. */
  734. for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
  735. if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
  736. return AVPROBE_SCORE_MAX;
  737. return 0;
  738. }
  739. /*
  740. * From here on, it's all XML-style DTD stuff... Needs no comments.
  741. */
  742. static int
  743. matroska_parse_info (MatroskaDemuxContext *matroska)
  744. {
  745. int res = 0;
  746. uint32_t id;
  747. av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
  748. while (res == 0) {
  749. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  750. res = AVERROR_IO;
  751. break;
  752. } else if (matroska->level_up) {
  753. matroska->level_up--;
  754. break;
  755. }
  756. switch (id) {
  757. /* cluster timecode */
  758. case MATROSKA_ID_TIMECODESCALE: {
  759. uint64_t num;
  760. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  761. break;
  762. matroska->time_scale = num;
  763. break;
  764. }
  765. case MATROSKA_ID_DURATION: {
  766. double num;
  767. if ((res = ebml_read_float(matroska, &id, &num)) < 0)
  768. break;
  769. matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
  770. break;
  771. }
  772. case MATROSKA_ID_TITLE: {
  773. char *text;
  774. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  775. break;
  776. strncpy(matroska->ctx->title, text,
  777. sizeof(matroska->ctx->title)-1);
  778. av_free(text);
  779. break;
  780. }
  781. case MATROSKA_ID_WRITINGAPP: {
  782. char *text;
  783. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  784. break;
  785. matroska->writing_app = text;
  786. break;
  787. }
  788. case MATROSKA_ID_MUXINGAPP: {
  789. char *text;
  790. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  791. break;
  792. matroska->muxing_app = text;
  793. break;
  794. }
  795. case MATROSKA_ID_DATEUTC: {
  796. int64_t time;
  797. if ((res = ebml_read_date(matroska, &id, &time)) < 0)
  798. break;
  799. matroska->created = time;
  800. break;
  801. }
  802. default:
  803. av_log(matroska->ctx, AV_LOG_INFO,
  804. "Unknown entry 0x%x in info header\n", id);
  805. /* fall-through */
  806. case EBML_ID_VOID:
  807. res = ebml_read_skip(matroska);
  808. break;
  809. }
  810. if (matroska->level_up) {
  811. matroska->level_up--;
  812. break;
  813. }
  814. }
  815. return res;
  816. }
  817. static int
  818. matroska_add_stream (MatroskaDemuxContext *matroska)
  819. {
  820. int res = 0;
  821. uint32_t id;
  822. MatroskaTrack *track;
  823. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
  824. /* Allocate a generic track. As soon as we know its type we'll realloc. */
  825. track = av_mallocz(MAX_TRACK_SIZE);
  826. matroska->num_tracks++;
  827. /* start with the master */
  828. if ((res = ebml_read_master(matroska, &id)) < 0)
  829. return res;
  830. /* try reading the trackentry headers */
  831. while (res == 0) {
  832. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  833. res = AVERROR_IO;
  834. break;
  835. } else if (matroska->level_up > 0) {
  836. matroska->level_up--;
  837. break;
  838. }
  839. switch (id) {
  840. /* track number (unique stream ID) */
  841. case MATROSKA_ID_TRACKNUMBER: {
  842. uint64_t num;
  843. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  844. break;
  845. track->num = num;
  846. break;
  847. }
  848. /* track UID (unique identifier) */
  849. case MATROSKA_ID_TRACKUID: {
  850. uint64_t num;
  851. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  852. break;
  853. track->uid = num;
  854. break;
  855. }
  856. /* track type (video, audio, combined, subtitle, etc.) */
  857. case MATROSKA_ID_TRACKTYPE: {
  858. uint64_t num;
  859. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  860. break;
  861. if (track->type && track->type != num) {
  862. av_log(matroska->ctx, AV_LOG_INFO,
  863. "More than one tracktype in an entry - skip\n");
  864. break;
  865. }
  866. track->type = num;
  867. switch (track->type) {
  868. case MATROSKA_TRACK_TYPE_VIDEO:
  869. case MATROSKA_TRACK_TYPE_AUDIO:
  870. case MATROSKA_TRACK_TYPE_SUBTITLE:
  871. break;
  872. case MATROSKA_TRACK_TYPE_COMPLEX:
  873. case MATROSKA_TRACK_TYPE_LOGO:
  874. case MATROSKA_TRACK_TYPE_CONTROL:
  875. default:
  876. av_log(matroska->ctx, AV_LOG_INFO,
  877. "Unknown or unsupported track type 0x%x\n",
  878. track->type);
  879. track->type = 0;
  880. break;
  881. }
  882. matroska->tracks[matroska->num_tracks - 1] = track;
  883. break;
  884. }
  885. /* tracktype specific stuff for video */
  886. case MATROSKA_ID_TRACKVIDEO: {
  887. MatroskaVideoTrack *videotrack;
  888. if (!track->type)
  889. track->type = MATROSKA_TRACK_TYPE_VIDEO;
  890. if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
  891. av_log(matroska->ctx, AV_LOG_INFO,
  892. "video data in non-video track - ignoring\n");
  893. res = AVERROR_INVALIDDATA;
  894. break;
  895. } else if ((res = ebml_read_master(matroska, &id)) < 0)
  896. break;
  897. videotrack = (MatroskaVideoTrack *)track;
  898. while (res == 0) {
  899. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  900. res = AVERROR_IO;
  901. break;
  902. } else if (matroska->level_up > 0) {
  903. matroska->level_up--;
  904. break;
  905. }
  906. switch (id) {
  907. /* fixme, this should be one-up, but I get it here */
  908. case MATROSKA_ID_TRACKDEFAULTDURATION: {
  909. uint64_t num;
  910. if ((res = ebml_read_uint (matroska, &id,
  911. &num)) < 0)
  912. break;
  913. track->default_duration = num/matroska->time_scale;
  914. break;
  915. }
  916. /* video framerate */
  917. case MATROSKA_ID_VIDEOFRAMERATE: {
  918. double num;
  919. if ((res = ebml_read_float(matroska, &id,
  920. &num)) < 0)
  921. break;
  922. track->default_duration = 1000000000/(matroska->time_scale*num);
  923. break;
  924. }
  925. /* width of the size to display the video at */
  926. case MATROSKA_ID_VIDEODISPLAYWIDTH: {
  927. uint64_t num;
  928. if ((res = ebml_read_uint(matroska, &id,
  929. &num)) < 0)
  930. break;
  931. videotrack->display_width = num;
  932. break;
  933. }
  934. /* height of the size to display the video at */
  935. case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
  936. uint64_t num;
  937. if ((res = ebml_read_uint(matroska, &id,
  938. &num)) < 0)
  939. break;
  940. videotrack->display_height = num;
  941. break;
  942. }
  943. /* width of the video in the file */
  944. case MATROSKA_ID_VIDEOPIXELWIDTH: {
  945. uint64_t num;
  946. if ((res = ebml_read_uint(matroska, &id,
  947. &num)) < 0)
  948. break;
  949. videotrack->pixel_width = num;
  950. break;
  951. }
  952. /* height of the video in the file */
  953. case MATROSKA_ID_VIDEOPIXELHEIGHT: {
  954. uint64_t num;
  955. if ((res = ebml_read_uint(matroska, &id,
  956. &num)) < 0)
  957. break;
  958. videotrack->pixel_height = num;
  959. break;
  960. }
  961. /* whether the video is interlaced */
  962. case MATROSKA_ID_VIDEOFLAGINTERLACED: {
  963. uint64_t num;
  964. if ((res = ebml_read_uint(matroska, &id,
  965. &num)) < 0)
  966. break;
  967. if (num)
  968. track->flags |=
  969. MATROSKA_VIDEOTRACK_INTERLACED;
  970. else
  971. track->flags &=
  972. ~MATROSKA_VIDEOTRACK_INTERLACED;
  973. break;
  974. }
  975. /* stereo mode (whether the video has two streams,
  976. * where one is for the left eye and the other for
  977. * the right eye, which creates a 3D-like
  978. * effect) */
  979. case MATROSKA_ID_VIDEOSTEREOMODE: {
  980. uint64_t num;
  981. if ((res = ebml_read_uint(matroska, &id,
  982. &num)) < 0)
  983. break;
  984. if (num != MATROSKA_EYE_MODE_MONO &&
  985. num != MATROSKA_EYE_MODE_LEFT &&
  986. num != MATROSKA_EYE_MODE_RIGHT &&
  987. num != MATROSKA_EYE_MODE_BOTH) {
  988. av_log(matroska->ctx, AV_LOG_INFO,
  989. "Ignoring unknown eye mode 0x%x\n",
  990. (uint32_t) num);
  991. break;
  992. }
  993. videotrack->eye_mode = num;
  994. break;
  995. }
  996. /* aspect ratio behaviour */
  997. case MATROSKA_ID_VIDEOASPECTRATIO: {
  998. uint64_t num;
  999. if ((res = ebml_read_uint(matroska, &id,
  1000. &num)) < 0)
  1001. break;
  1002. if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
  1003. num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
  1004. num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
  1005. av_log(matroska->ctx, AV_LOG_INFO,
  1006. "Ignoring unknown aspect ratio 0x%x\n",
  1007. (uint32_t) num);
  1008. break;
  1009. }
  1010. videotrack->ar_mode = num;
  1011. break;
  1012. }
  1013. /* colourspace (only matters for raw video)
  1014. * fourcc */
  1015. case MATROSKA_ID_VIDEOCOLOURSPACE: {
  1016. uint64_t num;
  1017. if ((res = ebml_read_uint(matroska, &id,
  1018. &num)) < 0)
  1019. break;
  1020. videotrack->fourcc = num;
  1021. break;
  1022. }
  1023. default:
  1024. av_log(matroska->ctx, AV_LOG_INFO,
  1025. "Unknown video track header entry "
  1026. "0x%x - ignoring\n", id);
  1027. /* pass-through */
  1028. case EBML_ID_VOID:
  1029. res = ebml_read_skip(matroska);
  1030. break;
  1031. }
  1032. if (matroska->level_up) {
  1033. matroska->level_up--;
  1034. break;
  1035. }
  1036. }
  1037. break;
  1038. }
  1039. /* tracktype specific stuff for audio */
  1040. case MATROSKA_ID_TRACKAUDIO: {
  1041. MatroskaAudioTrack *audiotrack;
  1042. if (!track->type)
  1043. track->type = MATROSKA_TRACK_TYPE_AUDIO;
  1044. if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
  1045. av_log(matroska->ctx, AV_LOG_INFO,
  1046. "audio data in non-audio track - ignoring\n");
  1047. res = AVERROR_INVALIDDATA;
  1048. break;
  1049. } else if ((res = ebml_read_master(matroska, &id)) < 0)
  1050. break;
  1051. audiotrack = (MatroskaAudioTrack *)track;
  1052. audiotrack->channels = 1;
  1053. audiotrack->samplerate = 8000;
  1054. while (res == 0) {
  1055. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1056. res = AVERROR_IO;
  1057. break;
  1058. } else if (matroska->level_up > 0) {
  1059. matroska->level_up--;
  1060. break;
  1061. }
  1062. switch (id) {
  1063. /* samplerate */
  1064. case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
  1065. double num;
  1066. if ((res = ebml_read_float(matroska, &id,
  1067. &num)) < 0)
  1068. break;
  1069. audiotrack->internal_samplerate =
  1070. audiotrack->samplerate = num;
  1071. break;
  1072. }
  1073. case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
  1074. double num;
  1075. if ((res = ebml_read_float(matroska, &id,
  1076. &num)) < 0)
  1077. break;
  1078. audiotrack->samplerate = num;
  1079. break;
  1080. }
  1081. /* bitdepth */
  1082. case MATROSKA_ID_AUDIOBITDEPTH: {
  1083. uint64_t num;
  1084. if ((res = ebml_read_uint(matroska, &id,
  1085. &num)) < 0)
  1086. break;
  1087. audiotrack->bitdepth = num;
  1088. break;
  1089. }
  1090. /* channels */
  1091. case MATROSKA_ID_AUDIOCHANNELS: {
  1092. uint64_t num;
  1093. if ((res = ebml_read_uint(matroska, &id,
  1094. &num)) < 0)
  1095. break;
  1096. audiotrack->channels = num;
  1097. break;
  1098. }
  1099. default:
  1100. av_log(matroska->ctx, AV_LOG_INFO,
  1101. "Unknown audio track header entry "
  1102. "0x%x - ignoring\n", id);
  1103. /* pass-through */
  1104. case EBML_ID_VOID:
  1105. res = ebml_read_skip(matroska);
  1106. break;
  1107. }
  1108. if (matroska->level_up) {
  1109. matroska->level_up--;
  1110. break;
  1111. }
  1112. }
  1113. break;
  1114. }
  1115. /* codec identifier */
  1116. case MATROSKA_ID_CODECID: {
  1117. char *text;
  1118. if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
  1119. break;
  1120. track->codec_id = text;
  1121. break;
  1122. }
  1123. /* codec private data */
  1124. case MATROSKA_ID_CODECPRIVATE: {
  1125. uint8_t *data;
  1126. int size;
  1127. if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
  1128. break;
  1129. track->codec_priv = data;
  1130. track->codec_priv_size = size;
  1131. break;
  1132. }
  1133. /* name of the codec */
  1134. case MATROSKA_ID_CODECNAME: {
  1135. char *text;
  1136. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  1137. break;
  1138. track->codec_name = text;
  1139. break;
  1140. }
  1141. /* name of this track */
  1142. case MATROSKA_ID_TRACKNAME: {
  1143. char *text;
  1144. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  1145. break;
  1146. track->name = text;
  1147. break;
  1148. }
  1149. /* language (matters for audio/subtitles, mostly) */
  1150. case MATROSKA_ID_TRACKLANGUAGE: {
  1151. char *text;
  1152. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  1153. break;
  1154. track->language = text;
  1155. break;
  1156. }
  1157. /* whether this is actually used */
  1158. case MATROSKA_ID_TRACKFLAGENABLED: {
  1159. uint64_t num;
  1160. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1161. break;
  1162. if (num)
  1163. track->flags |= MATROSKA_TRACK_ENABLED;
  1164. else
  1165. track->flags &= ~MATROSKA_TRACK_ENABLED;
  1166. break;
  1167. }
  1168. /* whether it's the default for this track type */
  1169. case MATROSKA_ID_TRACKFLAGDEFAULT: {
  1170. uint64_t num;
  1171. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1172. break;
  1173. if (num)
  1174. track->flags |= MATROSKA_TRACK_DEFAULT;
  1175. else
  1176. track->flags &= ~MATROSKA_TRACK_DEFAULT;
  1177. break;
  1178. }
  1179. /* lacing (like MPEG, where blocks don't end/start on frame
  1180. * boundaries) */
  1181. case MATROSKA_ID_TRACKFLAGLACING: {
  1182. uint64_t num;
  1183. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1184. break;
  1185. if (num)
  1186. track->flags |= MATROSKA_TRACK_LACING;
  1187. else
  1188. track->flags &= ~MATROSKA_TRACK_LACING;
  1189. break;
  1190. }
  1191. /* default length (in time) of one data block in this track */
  1192. case MATROSKA_ID_TRACKDEFAULTDURATION: {
  1193. uint64_t num;
  1194. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1195. break;
  1196. track->default_duration = num / matroska->time_scale;
  1197. break;
  1198. }
  1199. default:
  1200. av_log(matroska->ctx, AV_LOG_INFO,
  1201. "Unknown track header entry 0x%x - ignoring\n", id);
  1202. /* pass-through */
  1203. case EBML_ID_VOID:
  1204. /* we ignore these because they're nothing useful. */
  1205. case MATROSKA_ID_CODECINFOURL:
  1206. case MATROSKA_ID_CODECDOWNLOADURL:
  1207. case MATROSKA_ID_TRACKMINCACHE:
  1208. case MATROSKA_ID_TRACKMAXCACHE:
  1209. res = ebml_read_skip(matroska);
  1210. break;
  1211. }
  1212. if (matroska->level_up) {
  1213. matroska->level_up--;
  1214. break;
  1215. }
  1216. }
  1217. return res;
  1218. }
  1219. static int
  1220. matroska_parse_tracks (MatroskaDemuxContext *matroska)
  1221. {
  1222. int res = 0;
  1223. uint32_t id;
  1224. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
  1225. while (res == 0) {
  1226. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1227. res = AVERROR_IO;
  1228. break;
  1229. } else if (matroska->level_up) {
  1230. matroska->level_up--;
  1231. break;
  1232. }
  1233. switch (id) {
  1234. /* one track within the "all-tracks" header */
  1235. case MATROSKA_ID_TRACKENTRY:
  1236. res = matroska_add_stream(matroska);
  1237. break;
  1238. default:
  1239. av_log(matroska->ctx, AV_LOG_INFO,
  1240. "Unknown entry 0x%x in track header\n", id);
  1241. /* fall-through */
  1242. case EBML_ID_VOID:
  1243. res = ebml_read_skip(matroska);
  1244. break;
  1245. }
  1246. if (matroska->level_up) {
  1247. matroska->level_up--;
  1248. break;
  1249. }
  1250. }
  1251. return res;
  1252. }
  1253. static int
  1254. matroska_parse_index (MatroskaDemuxContext *matroska)
  1255. {
  1256. int res = 0;
  1257. uint32_t id;
  1258. MatroskaDemuxIndex idx;
  1259. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
  1260. while (res == 0) {
  1261. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1262. res = AVERROR_IO;
  1263. break;
  1264. } else if (matroska->level_up) {
  1265. matroska->level_up--;
  1266. break;
  1267. }
  1268. switch (id) {
  1269. /* one single index entry ('point') */
  1270. case MATROSKA_ID_POINTENTRY:
  1271. if ((res = ebml_read_master(matroska, &id)) < 0)
  1272. break;
  1273. /* in the end, we hope to fill one entry with a
  1274. * timestamp, a file position and a tracknum */
  1275. idx.pos = (uint64_t) -1;
  1276. idx.time = (uint64_t) -1;
  1277. idx.track = (uint16_t) -1;
  1278. while (res == 0) {
  1279. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1280. res = AVERROR_IO;
  1281. break;
  1282. } else if (matroska->level_up) {
  1283. matroska->level_up--;
  1284. break;
  1285. }
  1286. switch (id) {
  1287. /* one single index entry ('point') */
  1288. case MATROSKA_ID_CUETIME: {
  1289. uint64_t time;
  1290. if ((res = ebml_read_uint(matroska, &id,
  1291. &time)) < 0)
  1292. break;
  1293. idx.time = time * matroska->time_scale;
  1294. break;
  1295. }
  1296. /* position in the file + track to which it
  1297. * belongs */
  1298. case MATROSKA_ID_CUETRACKPOSITION:
  1299. if ((res = ebml_read_master(matroska, &id)) < 0)
  1300. break;
  1301. while (res == 0) {
  1302. if (!(id = ebml_peek_id (matroska,
  1303. &matroska->level_up))) {
  1304. res = AVERROR_IO;
  1305. break;
  1306. } else if (matroska->level_up) {
  1307. matroska->level_up--;
  1308. break;
  1309. }
  1310. switch (id) {
  1311. /* track number */
  1312. case MATROSKA_ID_CUETRACK: {
  1313. uint64_t num;
  1314. if ((res = ebml_read_uint(matroska,
  1315. &id, &num)) < 0)
  1316. break;
  1317. idx.track = num;
  1318. break;
  1319. }
  1320. /* position in file */
  1321. case MATROSKA_ID_CUECLUSTERPOSITION: {
  1322. uint64_t num;
  1323. if ((res = ebml_read_uint(matroska,
  1324. &id, &num)) < 0)
  1325. break;
  1326. idx.pos = num+matroska->segment_start;
  1327. break;
  1328. }
  1329. default:
  1330. av_log(matroska->ctx, AV_LOG_INFO,
  1331. "Unknown entry 0x%x in "
  1332. "CuesTrackPositions\n", id);
  1333. /* fall-through */
  1334. case EBML_ID_VOID:
  1335. res = ebml_read_skip(matroska);
  1336. break;
  1337. }
  1338. if (matroska->level_up) {
  1339. matroska->level_up--;
  1340. break;
  1341. }
  1342. }
  1343. break;
  1344. default:
  1345. av_log(matroska->ctx, AV_LOG_INFO,
  1346. "Unknown entry 0x%x in cuespoint "
  1347. "index\n", id);
  1348. /* fall-through */
  1349. case EBML_ID_VOID:
  1350. res = ebml_read_skip(matroska);
  1351. break;
  1352. }
  1353. if (matroska->level_up) {
  1354. matroska->level_up--;
  1355. break;
  1356. }
  1357. }
  1358. /* so let's see if we got what we wanted */
  1359. if (idx.pos != (uint64_t) -1 &&
  1360. idx.time != (uint64_t) -1 &&
  1361. idx.track != (uint16_t) -1) {
  1362. if (matroska->num_indexes % 32 == 0) {
  1363. /* re-allocate bigger index */
  1364. matroska->index =
  1365. av_realloc(matroska->index,
  1366. (matroska->num_indexes + 32) *
  1367. sizeof(MatroskaDemuxIndex));
  1368. }
  1369. matroska->index[matroska->num_indexes] = idx;
  1370. matroska->num_indexes++;
  1371. }
  1372. break;
  1373. default:
  1374. av_log(matroska->ctx, AV_LOG_INFO,
  1375. "Unknown entry 0x%x in cues header\n", id);
  1376. /* fall-through */
  1377. case EBML_ID_VOID:
  1378. res = ebml_read_skip(matroska);
  1379. break;
  1380. }
  1381. if (matroska->level_up) {
  1382. matroska->level_up--;
  1383. break;
  1384. }
  1385. }
  1386. return res;
  1387. }
  1388. static int
  1389. matroska_parse_metadata (MatroskaDemuxContext *matroska)
  1390. {
  1391. int res = 0;
  1392. uint32_t id;
  1393. while (res == 0) {
  1394. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1395. res = AVERROR_IO;
  1396. break;
  1397. } else if (matroska->level_up) {
  1398. matroska->level_up--;
  1399. break;
  1400. }
  1401. switch (id) {
  1402. /* Hm, this is unsupported... */
  1403. default:
  1404. av_log(matroska->ctx, AV_LOG_INFO,
  1405. "Unknown entry 0x%x in metadata header\n", id);
  1406. /* fall-through */
  1407. case EBML_ID_VOID:
  1408. res = ebml_read_skip(matroska);
  1409. break;
  1410. }
  1411. if (matroska->level_up) {
  1412. matroska->level_up--;
  1413. break;
  1414. }
  1415. }
  1416. return res;
  1417. }
  1418. static int
  1419. matroska_parse_seekhead (MatroskaDemuxContext *matroska)
  1420. {
  1421. int res = 0;
  1422. uint32_t id;
  1423. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
  1424. while (res == 0) {
  1425. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1426. res = AVERROR_IO;
  1427. break;
  1428. } else if (matroska->level_up) {
  1429. matroska->level_up--;
  1430. break;
  1431. }
  1432. switch (id) {
  1433. case MATROSKA_ID_SEEKENTRY: {
  1434. uint32_t seek_id = 0, peek_id_cache = 0;
  1435. uint64_t seek_pos = (uint64_t) -1, t;
  1436. if ((res = ebml_read_master(matroska, &id)) < 0)
  1437. break;
  1438. while (res == 0) {
  1439. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1440. res = AVERROR_IO;
  1441. break;
  1442. } else if (matroska->level_up) {
  1443. matroska->level_up--;
  1444. break;
  1445. }
  1446. switch (id) {
  1447. case MATROSKA_ID_SEEKID:
  1448. res = ebml_read_uint(matroska, &id, &t);
  1449. seek_id = t;
  1450. break;
  1451. case MATROSKA_ID_SEEKPOSITION:
  1452. res = ebml_read_uint(matroska, &id, &seek_pos);
  1453. break;
  1454. default:
  1455. av_log(matroska->ctx, AV_LOG_INFO,
  1456. "Unknown seekhead ID 0x%x\n", id);
  1457. /* fall-through */
  1458. case EBML_ID_VOID:
  1459. res = ebml_read_skip(matroska);
  1460. break;
  1461. }
  1462. if (matroska->level_up) {
  1463. matroska->level_up--;
  1464. break;
  1465. }
  1466. }
  1467. if (!seek_id || seek_pos == (uint64_t) -1) {
  1468. av_log(matroska->ctx, AV_LOG_INFO,
  1469. "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
  1470. seek_id, seek_pos);
  1471. break;
  1472. }
  1473. switch (seek_id) {
  1474. case MATROSKA_ID_CUES:
  1475. case MATROSKA_ID_TAGS: {
  1476. uint32_t level_up = matroska->level_up;
  1477. offset_t before_pos;
  1478. uint64_t length;
  1479. MatroskaLevel level;
  1480. /* remember the peeked ID and the current position */
  1481. peek_id_cache = matroska->peek_id;
  1482. before_pos = url_ftell(&matroska->ctx->pb);
  1483. /* seek */
  1484. if ((res = ebml_read_seek(matroska, seek_pos +
  1485. matroska->segment_start)) < 0)
  1486. return res;
  1487. /* we don't want to lose our seekhead level, so we add
  1488. * a dummy. This is a crude hack. */
  1489. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1490. av_log(matroska->ctx, AV_LOG_INFO,
  1491. "Max EBML element depth (%d) reached, "
  1492. "cannot parse further.\n", EBML_MAX_DEPTH);
  1493. return AVERROR_UNKNOWN;
  1494. }
  1495. level.start = 0;
  1496. level.length = (uint64_t)-1;
  1497. matroska->levels[matroska->num_levels] = level;
  1498. matroska->num_levels++;
  1499. /* check ID */
  1500. if (!(id = ebml_peek_id (matroska,
  1501. &matroska->level_up)))
  1502. goto finish;
  1503. if (id != seek_id) {
  1504. av_log(matroska->ctx, AV_LOG_INFO,
  1505. "We looked for ID=0x%x but got "
  1506. "ID=0x%x (pos=%"PRIu64")",
  1507. seek_id, id, seek_pos +
  1508. matroska->segment_start);
  1509. goto finish;
  1510. }
  1511. /* read master + parse */
  1512. if ((res = ebml_read_master(matroska, &id)) < 0)
  1513. goto finish;
  1514. switch (id) {
  1515. case MATROSKA_ID_CUES:
  1516. if (!(res = matroska_parse_index(matroska)) ||
  1517. url_feof(&matroska->ctx->pb)) {
  1518. matroska->index_parsed = 1;
  1519. res = 0;
  1520. }
  1521. break;
  1522. case MATROSKA_ID_TAGS:
  1523. if (!(res = matroska_parse_metadata(matroska)) ||
  1524. url_feof(&matroska->ctx->pb)) {
  1525. matroska->metadata_parsed = 1;
  1526. res = 0;
  1527. }
  1528. break;
  1529. }
  1530. finish:
  1531. /* remove dummy level */
  1532. while (matroska->num_levels) {
  1533. matroska->num_levels--;
  1534. length =
  1535. matroska->levels[matroska->num_levels].length;
  1536. if (length == (uint64_t)-1)
  1537. break;
  1538. }
  1539. /* seek back */
  1540. if ((res = ebml_read_seek(matroska, before_pos)) < 0)
  1541. return res;
  1542. matroska->peek_id = peek_id_cache;
  1543. matroska->level_up = level_up;
  1544. break;
  1545. }
  1546. default:
  1547. av_log(matroska->ctx, AV_LOG_INFO,
  1548. "Ignoring seekhead entry for ID=0x%x\n",
  1549. seek_id);
  1550. break;
  1551. }
  1552. break;
  1553. }
  1554. default:
  1555. av_log(matroska->ctx, AV_LOG_INFO,
  1556. "Unknown seekhead ID 0x%x\n", id);
  1557. /* fall-through */
  1558. case EBML_ID_VOID:
  1559. res = ebml_read_skip(matroska);
  1560. break;
  1561. }
  1562. if (matroska->level_up) {
  1563. matroska->level_up--;
  1564. break;
  1565. }
  1566. }
  1567. return res;
  1568. }
  1569. #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
  1570. static int
  1571. matroska_aac_profile (char *codec_id)
  1572. {
  1573. static const char *aac_profiles[] = {
  1574. "MAIN", "LC", "SSR"
  1575. };
  1576. int profile;
  1577. for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
  1578. if (strstr(codec_id, aac_profiles[profile]))
  1579. break;
  1580. return profile + 1;
  1581. }
  1582. static int
  1583. matroska_aac_sri (int samplerate)
  1584. {
  1585. static const int aac_sample_rates[] = {
  1586. 96000, 88200, 64000, 48000, 44100, 32000,
  1587. 24000, 22050, 16000, 12000, 11025, 8000,
  1588. };
  1589. int sri;
  1590. for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
  1591. if (aac_sample_rates[sri] == samplerate)
  1592. break;
  1593. return sri;
  1594. }
  1595. static int
  1596. matroska_read_header (AVFormatContext *s,
  1597. AVFormatParameters *ap)
  1598. {
  1599. MatroskaDemuxContext *matroska = s->priv_data;
  1600. char *doctype;
  1601. int version, last_level, res = 0;
  1602. uint32_t id;
  1603. matroska->ctx = s;
  1604. /* First read the EBML header. */
  1605. doctype = NULL;
  1606. if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
  1607. return res;
  1608. if ((doctype == NULL) || strcmp(doctype, "matroska")) {
  1609. av_log(matroska->ctx, AV_LOG_ERROR,
  1610. "Wrong EBML doctype ('%s' != 'matroska').\n",
  1611. doctype ? doctype : "(none)");
  1612. if (doctype)
  1613. av_free(doctype);
  1614. return AVERROR_NOFMT;
  1615. }
  1616. av_free(doctype);
  1617. if (version > 2) {
  1618. av_log(matroska->ctx, AV_LOG_ERROR,
  1619. "Matroska demuxer version 2 too old for file version %d\n",
  1620. version);
  1621. return AVERROR_NOFMT;
  1622. }
  1623. /* The next thing is a segment. */
  1624. while (1) {
  1625. if (!(id = ebml_peek_id(matroska, &last_level)))
  1626. return AVERROR_IO;
  1627. if (id == MATROSKA_ID_SEGMENT)
  1628. break;
  1629. /* oi! */
  1630. av_log(matroska->ctx, AV_LOG_INFO,
  1631. "Expected a Segment ID (0x%x), but received 0x%x!\n",
  1632. MATROSKA_ID_SEGMENT, id);
  1633. if ((res = ebml_read_skip(matroska)) < 0)
  1634. return res;
  1635. }
  1636. /* We now have a Matroska segment.
  1637. * Seeks are from the beginning of the segment,
  1638. * after the segment ID/length. */
  1639. if ((res = ebml_read_master(matroska, &id)) < 0)
  1640. return res;
  1641. matroska->segment_start = url_ftell(&s->pb);
  1642. matroska->time_scale = 1000000;
  1643. /* we've found our segment, start reading the different contents in here */
  1644. while (res == 0) {
  1645. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1646. res = AVERROR_IO;
  1647. break;
  1648. } else if (matroska->level_up) {
  1649. matroska->level_up--;
  1650. break;
  1651. }
  1652. switch (id) {
  1653. /* stream info */
  1654. case MATROSKA_ID_INFO: {
  1655. if ((res = ebml_read_master(matroska, &id)) < 0)
  1656. break;
  1657. res = matroska_parse_info(matroska);
  1658. break;
  1659. }
  1660. /* track info headers */
  1661. case MATROSKA_ID_TRACKS: {
  1662. if ((res = ebml_read_master(matroska, &id)) < 0)
  1663. break;
  1664. res = matroska_parse_tracks(matroska);
  1665. break;
  1666. }
  1667. /* stream index */
  1668. case MATROSKA_ID_CUES: {
  1669. if (!matroska->index_parsed) {
  1670. if ((res = ebml_read_master(matroska, &id)) < 0)
  1671. break;
  1672. res = matroska_parse_index(matroska);
  1673. } else
  1674. res = ebml_read_skip(matroska);
  1675. break;
  1676. }
  1677. /* metadata */
  1678. case MATROSKA_ID_TAGS: {
  1679. if (!matroska->metadata_parsed) {
  1680. if ((res = ebml_read_master(matroska, &id)) < 0)
  1681. break;
  1682. res = matroska_parse_metadata(matroska);
  1683. } else
  1684. res = ebml_read_skip(matroska);
  1685. break;
  1686. }
  1687. /* file index (if seekable, seek to Cues/Tags to parse it) */
  1688. case MATROSKA_ID_SEEKHEAD: {
  1689. if ((res = ebml_read_master(matroska, &id)) < 0)
  1690. break;
  1691. res = matroska_parse_seekhead(matroska);
  1692. break;
  1693. }
  1694. case MATROSKA_ID_CLUSTER: {
  1695. /* Do not read the master - this will be done in the next
  1696. * call to matroska_read_packet. */
  1697. res = 1;
  1698. break;
  1699. }
  1700. default:
  1701. av_log(matroska->ctx, AV_LOG_INFO,
  1702. "Unknown matroska file header ID 0x%x\n", id);
  1703. /* fall-through */
  1704. case EBML_ID_VOID:
  1705. res = ebml_read_skip(matroska);
  1706. break;
  1707. }
  1708. if (matroska->level_up) {
  1709. matroska->level_up--;
  1710. break;
  1711. }
  1712. }
  1713. /* Have we found a cluster? */
  1714. if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
  1715. int i, j;
  1716. MatroskaTrack *track;
  1717. AVStream *st;
  1718. for (i = 0; i < matroska->num_tracks; i++) {
  1719. enum CodecID codec_id = CODEC_ID_NONE;
  1720. uint8_t *extradata = NULL;
  1721. int extradata_size = 0;
  1722. int extradata_offset = 0;
  1723. track = matroska->tracks[i];
  1724. track->stream_index = -1;
  1725. /* libavformat does not really support subtitles.
  1726. * Also apply some sanity checks. */
  1727. if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
  1728. (track->codec_id == NULL))
  1729. continue;
  1730. for(j=0; ff_mkv_codec_tags[j].str; j++){
  1731. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1732. strlen(ff_mkv_codec_tags[j].str))){
  1733. codec_id= ff_mkv_codec_tags[j].id;
  1734. break;
  1735. }
  1736. }
  1737. /* Set the FourCC from the CodecID. */
  1738. /* This is the MS compatibility mode which stores a
  1739. * BITMAPINFOHEADER in the CodecPrivate. */
  1740. if (!strcmp(track->codec_id,
  1741. MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
  1742. (track->codec_priv_size >= 40) &&
  1743. (track->codec_priv != NULL)) {
  1744. MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
  1745. /* Offset of biCompression. Stored in LE. */
  1746. vtrack->fourcc = AV_RL32(track->codec_priv + 16);
  1747. codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
  1748. }
  1749. /* This is the MS compatibility mode which stores a
  1750. * WAVEFORMATEX in the CodecPrivate. */
  1751. else if (!strcmp(track->codec_id,
  1752. MATROSKA_CODEC_ID_AUDIO_ACM) &&
  1753. (track->codec_priv_size >= 18) &&
  1754. (track->codec_priv != NULL)) {
  1755. uint16_t tag;
  1756. /* Offset of wFormatTag. Stored in LE. */
  1757. tag = AV_RL16(track->codec_priv);
  1758. codec_id = codec_get_id(codec_wav_tags, tag);
  1759. }
  1760. else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
  1761. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
  1762. int profile = matroska_aac_profile(track->codec_id);
  1763. int sri = matroska_aac_sri(audiotrack->internal_samplerate);
  1764. extradata = av_malloc(5);
  1765. if (extradata == NULL)
  1766. return AVERROR_NOMEM;
  1767. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1768. extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
  1769. if (strstr(track->codec_id, "SBR")) {
  1770. sri = matroska_aac_sri(audiotrack->samplerate);
  1771. extradata[2] = 0x56;
  1772. extradata[3] = 0xE5;
  1773. extradata[4] = 0x80 | (sri<<3);
  1774. extradata_size = 5;
  1775. } else {
  1776. extradata_size = 2;
  1777. }
  1778. track->default_duration = 1024*1000 / audiotrack->internal_samplerate;
  1779. }
  1780. else if (codec_id == CODEC_ID_TTA) {
  1781. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
  1782. ByteIOContext b;
  1783. extradata_size = 30;
  1784. extradata = av_mallocz(extradata_size);
  1785. if (extradata == NULL)
  1786. return AVERROR_NOMEM;
  1787. init_put_byte(&b, extradata, extradata_size, 1,
  1788. NULL, NULL, NULL, NULL);
  1789. put_buffer(&b, (uint8_t *) "TTA1", 4);
  1790. put_le16(&b, 1);
  1791. put_le16(&b, audiotrack->channels);
  1792. put_le16(&b, audiotrack->bitdepth);
  1793. put_le32(&b, audiotrack->samplerate);
  1794. put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
  1795. }
  1796. else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1797. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1798. extradata_offset = 26;
  1799. track->codec_priv_size -= extradata_offset;
  1800. track->flags |= MATROSKA_TRACK_REAL_V;
  1801. }
  1802. else if (codec_id == CODEC_ID_RA_144) {
  1803. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1804. audiotrack->samplerate = 8000;
  1805. audiotrack->channels = 1;
  1806. }
  1807. else if (codec_id == CODEC_ID_RA_288 ||
  1808. codec_id == CODEC_ID_COOK ||
  1809. codec_id == CODEC_ID_ATRAC3) {
  1810. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1811. ByteIOContext b;
  1812. init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
  1813. NULL, NULL, NULL, NULL);
  1814. url_fskip(&b, 24);
  1815. audiotrack->coded_framesize = get_be32(&b);
  1816. url_fskip(&b, 12);
  1817. audiotrack->sub_packet_h = get_be16(&b);
  1818. audiotrack->frame_size = get_be16(&b);
  1819. audiotrack->sub_packet_size = get_be16(&b);
  1820. audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
  1821. if (codec_id == CODEC_ID_RA_288) {
  1822. audiotrack->block_align = audiotrack->coded_framesize;
  1823. track->codec_priv_size = 0;
  1824. } else {
  1825. audiotrack->block_align = audiotrack->sub_packet_size;
  1826. extradata_offset = 78;
  1827. track->codec_priv_size -= extradata_offset;
  1828. }
  1829. }
  1830. if (codec_id == CODEC_ID_NONE) {
  1831. av_log(matroska->ctx, AV_LOG_INFO,
  1832. "Unknown/unsupported CodecID %s.\n",
  1833. track->codec_id);
  1834. }
  1835. track->stream_index = matroska->num_streams;
  1836. matroska->num_streams++;
  1837. st = av_new_stream(s, track->stream_index);
  1838. if (st == NULL)
  1839. return AVERROR_NOMEM;
  1840. av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1841. st->codec->codec_id = codec_id;
  1842. st->start_time = 0;
  1843. if (track->default_duration)
  1844. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1845. track->default_duration, 1000, 30000);
  1846. if(extradata){
  1847. st->codec->extradata = extradata;
  1848. st->codec->extradata_size = extradata_size;
  1849. } else if(track->codec_priv && track->codec_priv_size > 0){
  1850. st->codec->extradata = av_malloc(track->codec_priv_size);
  1851. if(st->codec->extradata == NULL)
  1852. return AVERROR_NOMEM;
  1853. st->codec->extradata_size = track->codec_priv_size;
  1854. memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
  1855. track->codec_priv_size);
  1856. }
  1857. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1858. MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
  1859. st->codec->codec_type = CODEC_TYPE_VIDEO;
  1860. st->codec->codec_tag = videotrack->fourcc;
  1861. st->codec->width = videotrack->pixel_width;
  1862. st->codec->height = videotrack->pixel_height;
  1863. if (videotrack->display_width == 0)
  1864. videotrack->display_width= videotrack->pixel_width;
  1865. if (videotrack->display_height == 0)
  1866. videotrack->display_height= videotrack->pixel_height;
  1867. av_reduce(&st->codec->sample_aspect_ratio.num,
  1868. &st->codec->sample_aspect_ratio.den,
  1869. st->codec->height * videotrack->display_width,
  1870. st->codec-> width * videotrack->display_height,
  1871. 255);
  1872. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1873. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1874. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1875. st->codec->codec_type = CODEC_TYPE_AUDIO;
  1876. st->codec->sample_rate = audiotrack->samplerate;
  1877. st->codec->channels = audiotrack->channels;
  1878. st->codec->block_align = audiotrack->block_align;
  1879. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1880. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  1881. }
  1882. /* What do we do with private data? E.g. for Vorbis. */
  1883. }
  1884. res = 0;
  1885. }
  1886. if (matroska->index_parsed) {
  1887. int i, track, stream;
  1888. for (i=0; i<matroska->num_indexes; i++) {
  1889. MatroskaDemuxIndex *idx = &matroska->index[i];
  1890. track = matroska_find_track_by_num(matroska, idx->track);
  1891. stream = matroska->tracks[track]->stream_index;
  1892. if (stream >= 0)
  1893. av_add_index_entry(matroska->ctx->streams[stream],
  1894. idx->pos, idx->time/matroska->time_scale,
  1895. 0, 0, AVINDEX_KEYFRAME);
  1896. }
  1897. }
  1898. return res;
  1899. }
  1900. static inline int
  1901. rv_offset(uint8_t *data, int slice, int slices)
  1902. {
  1903. return AV_RL32(data+8*slice+4) + 8*slices;
  1904. }
  1905. static int
  1906. matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
  1907. int64_t pos, uint64_t cluster_time, uint64_t duration,
  1908. int is_keyframe, int is_bframe)
  1909. {
  1910. int res = 0;
  1911. int track;
  1912. AVStream *st;
  1913. AVPacket *pkt;
  1914. uint8_t *origdata = data;
  1915. int16_t block_time;
  1916. uint32_t *lace_size = NULL;
  1917. int n, flags, laces = 0;
  1918. uint64_t num;
  1919. /* first byte(s): tracknum */
  1920. if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
  1921. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1922. av_free(origdata);
  1923. return res;
  1924. }
  1925. data += n;
  1926. size -= n;
  1927. /* fetch track from num */
  1928. track = matroska_find_track_by_num(matroska, num);
  1929. if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
  1930. av_log(matroska->ctx, AV_LOG_INFO,
  1931. "Invalid stream %d or size %u\n", track, size);
  1932. av_free(origdata);
  1933. return res;
  1934. }
  1935. if (matroska->tracks[track]->stream_index < 0)
  1936. return res;
  1937. st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
  1938. if (st->discard >= AVDISCARD_ALL) {
  1939. av_free(origdata);
  1940. return res;
  1941. }
  1942. if (duration == AV_NOPTS_VALUE)
  1943. duration = matroska->tracks[track]->default_duration;
  1944. /* block_time (relative to cluster time) */
  1945. block_time = AV_RB16(data);
  1946. data += 2;
  1947. flags = *data++;
  1948. size -= 3;
  1949. if (is_keyframe == -1)
  1950. is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
  1951. if (matroska->skip_to_keyframe) {
  1952. if (!is_keyframe || st != matroska->skip_to_stream)
  1953. return res;
  1954. matroska->skip_to_keyframe = 0;
  1955. }
  1956. switch ((flags & 0x06) >> 1) {
  1957. case 0x0: /* no lacing */
  1958. laces = 1;
  1959. lace_size = av_mallocz(sizeof(int));
  1960. lace_size[0] = size;
  1961. break;
  1962. case 0x1: /* xiph lacing */
  1963. case 0x2: /* fixed-size lacing */
  1964. case 0x3: /* EBML lacing */
  1965. if (size == 0) {
  1966. res = -1;
  1967. break;
  1968. }
  1969. laces = (*data) + 1;
  1970. data += 1;
  1971. size -= 1;
  1972. lace_size = av_mallocz(laces * sizeof(int));
  1973. switch ((flags & 0x06) >> 1) {
  1974. case 0x1: /* xiph lacing */ {
  1975. uint8_t temp;
  1976. uint32_t total = 0;
  1977. for (n = 0; res == 0 && n < laces - 1; n++) {
  1978. while (1) {
  1979. if (size == 0) {
  1980. res = -1;
  1981. break;
  1982. }
  1983. temp = *data;
  1984. lace_size[n] += temp;
  1985. data += 1;
  1986. size -= 1;
  1987. if (temp != 0xff)
  1988. break;
  1989. }
  1990. total += lace_size[n];
  1991. }
  1992. lace_size[n] = size - total;
  1993. break;
  1994. }
  1995. case 0x2: /* fixed-size lacing */
  1996. for (n = 0; n < laces; n++)
  1997. lace_size[n] = size / laces;
  1998. break;
  1999. case 0x3: /* EBML lacing */ {
  2000. uint32_t total;
  2001. n = matroska_ebmlnum_uint(data, size, &num);
  2002. if (n < 0) {
  2003. av_log(matroska->ctx, AV_LOG_INFO,
  2004. "EBML block data error\n");
  2005. break;
  2006. }
  2007. data += n;
  2008. size -= n;
  2009. total = lace_size[0] = num;
  2010. for (n = 1; res == 0 && n < laces - 1; n++) {
  2011. int64_t snum;
  2012. int r;
  2013. r = matroska_ebmlnum_sint (data, size, &snum);
  2014. if (r < 0) {
  2015. av_log(matroska->ctx, AV_LOG_INFO,
  2016. "EBML block data error\n");
  2017. break;
  2018. }
  2019. data += r;
  2020. size -= r;
  2021. lace_size[n] = lace_size[n - 1] + snum;
  2022. total += lace_size[n];
  2023. }
  2024. lace_size[n] = size - total;
  2025. break;
  2026. }
  2027. }
  2028. break;
  2029. }
  2030. if (res == 0) {
  2031. int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
  2032. uint64_t timecode = AV_NOPTS_VALUE;
  2033. if (cluster_time != (uint64_t)-1 && cluster_time + block_time >= 0)
  2034. timecode = cluster_time + block_time;
  2035. for (n = 0; n < laces; n++) {
  2036. int slice, slices = 1;
  2037. if (real_v) {
  2038. slices = *data++ + 1;
  2039. lace_size[n]--;
  2040. }
  2041. for (slice=0; slice<slices; slice++) {
  2042. int slice_size, slice_offset = 0;
  2043. if (real_v)
  2044. slice_offset = rv_offset(data, slice, slices);
  2045. if (slice+1 == slices)
  2046. slice_size = lace_size[n] - slice_offset;
  2047. else
  2048. slice_size = rv_offset(data, slice+1, slices) - slice_offset;
  2049. if (st->codec->codec_id == CODEC_ID_RA_288 ||
  2050. st->codec->codec_id == CODEC_ID_COOK ||
  2051. st->codec->codec_id == CODEC_ID_ATRAC3) {
  2052. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
  2053. int a = st->codec->block_align;
  2054. int sps = audiotrack->sub_packet_size;
  2055. int cfs = audiotrack->coded_framesize;
  2056. int h = audiotrack->sub_packet_h;
  2057. int y = audiotrack->sub_packet_cnt;
  2058. int w = audiotrack->frame_size;
  2059. int x;
  2060. if (!audiotrack->pkt_cnt) {
  2061. if (st->codec->codec_id == CODEC_ID_RA_288)
  2062. for (x=0; x<h/2; x++)
  2063. memcpy(audiotrack->buf+x*2*w+y*cfs,
  2064. data+x*cfs, cfs);
  2065. else
  2066. for (x=0; x<w/sps; x++)
  2067. memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  2068. if (++audiotrack->sub_packet_cnt >= h) {
  2069. audiotrack->sub_packet_cnt = 0;
  2070. audiotrack->pkt_cnt = h*w / a;
  2071. }
  2072. }
  2073. while (audiotrack->pkt_cnt) {
  2074. pkt = av_mallocz(sizeof(AVPacket));
  2075. av_new_packet(pkt, a);
  2076. memcpy(pkt->data, audiotrack->buf
  2077. + a * (h*w / a - audiotrack->pkt_cnt--), a);
  2078. pkt->pos = pos;
  2079. pkt->stream_index = matroska->tracks[track]->stream_index;
  2080. matroska_queue_packet(matroska, pkt);
  2081. }
  2082. } else {
  2083. pkt = av_mallocz(sizeof(AVPacket));
  2084. /* XXX: prevent data copy... */
  2085. if (av_new_packet(pkt, slice_size) < 0) {
  2086. res = AVERROR_NOMEM;
  2087. n = laces-1;
  2088. break;
  2089. }
  2090. memcpy (pkt->data, data+slice_offset, slice_size);
  2091. if (n == 0)
  2092. pkt->flags = is_keyframe;
  2093. pkt->stream_index = matroska->tracks[track]->stream_index;
  2094. pkt->pts = timecode;
  2095. pkt->pos = pos;
  2096. pkt->duration = duration;
  2097. matroska_queue_packet(matroska, pkt);
  2098. }
  2099. if (timecode != AV_NOPTS_VALUE)
  2100. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  2101. }
  2102. data += lace_size[n];
  2103. }
  2104. }
  2105. av_free(lace_size);
  2106. av_free(origdata);
  2107. return res;
  2108. }
  2109. static int
  2110. matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
  2111. uint64_t cluster_time)
  2112. {
  2113. int res = 0;
  2114. uint32_t id;
  2115. int is_bframe = 0;
  2116. int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
  2117. uint64_t duration = AV_NOPTS_VALUE;
  2118. uint8_t *data;
  2119. int size = 0;
  2120. int64_t pos = 0;
  2121. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
  2122. while (res == 0) {
  2123. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2124. res = AVERROR_IO;
  2125. break;
  2126. } else if (matroska->level_up) {
  2127. matroska->level_up--;
  2128. break;
  2129. }
  2130. switch (id) {
  2131. /* one block inside the group. Note, block parsing is one
  2132. * of the harder things, so this code is a bit complicated.
  2133. * See http://www.matroska.org/ for documentation. */
  2134. case MATROSKA_ID_BLOCK: {
  2135. pos = url_ftell(&matroska->ctx->pb);
  2136. res = ebml_read_binary(matroska, &id, &data, &size);
  2137. break;
  2138. }
  2139. case MATROSKA_ID_BLOCKDURATION: {
  2140. if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
  2141. break;
  2142. duration /= matroska->time_scale;
  2143. break;
  2144. }
  2145. case MATROSKA_ID_BLOCKREFERENCE: {
  2146. int64_t num;
  2147. /* We've found a reference, so not even the first frame in
  2148. * the lace is a key frame. */
  2149. is_keyframe = 0;
  2150. if (last_num_packets != matroska->num_packets)
  2151. matroska->packets[last_num_packets]->flags = 0;
  2152. if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
  2153. break;
  2154. if (num > 0)
  2155. is_bframe = 1;
  2156. break;
  2157. }
  2158. default:
  2159. av_log(matroska->ctx, AV_LOG_INFO,
  2160. "Unknown entry 0x%x in blockgroup data\n", id);
  2161. /* fall-through */
  2162. case EBML_ID_VOID:
  2163. res = ebml_read_skip(matroska);
  2164. break;
  2165. }
  2166. if (matroska->level_up) {
  2167. matroska->level_up--;
  2168. break;
  2169. }
  2170. }
  2171. if (res)
  2172. return res;
  2173. if (size > 0)
  2174. res = matroska_parse_block(matroska, data, size, pos, cluster_time,
  2175. duration, is_keyframe, is_bframe);
  2176. return res;
  2177. }
  2178. static int
  2179. matroska_parse_cluster (MatroskaDemuxContext *matroska)
  2180. {
  2181. int res = 0;
  2182. uint32_t id;
  2183. uint64_t cluster_time = 0;
  2184. uint8_t *data;
  2185. int64_t pos;
  2186. int size;
  2187. av_log(matroska->ctx, AV_LOG_DEBUG,
  2188. "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
  2189. while (res == 0) {
  2190. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2191. res = AVERROR_IO;
  2192. break;
  2193. } else if (matroska->level_up) {
  2194. matroska->level_up--;
  2195. break;
  2196. }
  2197. switch (id) {
  2198. /* cluster timecode */
  2199. case MATROSKA_ID_CLUSTERTIMECODE: {
  2200. uint64_t num;
  2201. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  2202. break;
  2203. cluster_time = num;
  2204. break;
  2205. }
  2206. /* a group of blocks inside a cluster */
  2207. case MATROSKA_ID_BLOCKGROUP:
  2208. if ((res = ebml_read_master(matroska, &id)) < 0)
  2209. break;
  2210. res = matroska_parse_blockgroup(matroska, cluster_time);
  2211. break;
  2212. case MATROSKA_ID_SIMPLEBLOCK:
  2213. pos = url_ftell(&matroska->ctx->pb);
  2214. res = ebml_read_binary(matroska, &id, &data, &size);
  2215. if (res == 0)
  2216. res = matroska_parse_block(matroska, data, size, pos,
  2217. cluster_time, AV_NOPTS_VALUE,
  2218. -1, 0);
  2219. break;
  2220. default:
  2221. av_log(matroska->ctx, AV_LOG_INFO,
  2222. "Unknown entry 0x%x in cluster data\n", id);
  2223. /* fall-through */
  2224. case EBML_ID_VOID:
  2225. res = ebml_read_skip(matroska);
  2226. break;
  2227. }
  2228. if (matroska->level_up) {
  2229. matroska->level_up--;
  2230. break;
  2231. }
  2232. }
  2233. return res;
  2234. }
  2235. static int
  2236. matroska_read_packet (AVFormatContext *s,
  2237. AVPacket *pkt)
  2238. {
  2239. MatroskaDemuxContext *matroska = s->priv_data;
  2240. int res;
  2241. uint32_t id;
  2242. /* Read stream until we have a packet queued. */
  2243. while (matroska_deliver_packet(matroska, pkt)) {
  2244. /* Have we already reached the end? */
  2245. if (matroska->done)
  2246. return AVERROR_IO;
  2247. res = 0;
  2248. while (res == 0) {
  2249. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2250. return AVERROR_IO;
  2251. } else if (matroska->level_up) {
  2252. matroska->level_up--;
  2253. break;
  2254. }
  2255. switch (id) {
  2256. case MATROSKA_ID_CLUSTER:
  2257. if ((res = ebml_read_master(matroska, &id)) < 0)
  2258. break;
  2259. if ((res = matroska_parse_cluster(matroska)) == 0)
  2260. res = 1; /* Parsed one cluster, let's get out. */
  2261. break;
  2262. default:
  2263. case EBML_ID_VOID:
  2264. res = ebml_read_skip(matroska);
  2265. break;
  2266. }
  2267. if (matroska->level_up) {
  2268. matroska->level_up--;
  2269. break;
  2270. }
  2271. }
  2272. if (res == -1)
  2273. matroska->done = 1;
  2274. }
  2275. return 0;
  2276. }
  2277. static int
  2278. matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
  2279. int flags)
  2280. {
  2281. MatroskaDemuxContext *matroska = s->priv_data;
  2282. AVStream *st = s->streams[stream_index];
  2283. int index;
  2284. /* find index entry */
  2285. index = av_index_search_timestamp(st, timestamp, flags);
  2286. if (index < 0)
  2287. return 0;
  2288. /* do the seek */
  2289. url_fseek(&s->pb, st->index_entries[index].pos, SEEK_SET);
  2290. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2291. matroska->skip_to_stream = st;
  2292. matroska->num_packets = 0;
  2293. matroska->peek_id = 0;
  2294. return 0;
  2295. }
  2296. static int
  2297. matroska_read_close (AVFormatContext *s)
  2298. {
  2299. MatroskaDemuxContext *matroska = s->priv_data;
  2300. int n = 0;
  2301. av_free(matroska->writing_app);
  2302. av_free(matroska->muxing_app);
  2303. av_free(matroska->index);
  2304. if (matroska->packets != NULL) {
  2305. for (n = 0; n < matroska->num_packets; n++) {
  2306. av_free_packet(matroska->packets[n]);
  2307. av_free(matroska->packets[n]);
  2308. }
  2309. av_free(matroska->packets);
  2310. }
  2311. for (n = 0; n < matroska->num_tracks; n++) {
  2312. MatroskaTrack *track = matroska->tracks[n];
  2313. av_free(track->codec_id);
  2314. av_free(track->codec_name);
  2315. av_free(track->codec_priv);
  2316. av_free(track->name);
  2317. av_free(track->language);
  2318. if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  2319. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  2320. av_free(audiotrack->buf);
  2321. }
  2322. av_free(track);
  2323. }
  2324. return 0;
  2325. }
  2326. AVInputFormat matroska_demuxer = {
  2327. "matroska",
  2328. "Matroska file format",
  2329. sizeof(MatroskaDemuxContext),
  2330. matroska_probe,
  2331. matroska_read_header,
  2332. matroska_read_packet,
  2333. matroska_read_close,
  2334. matroska_read_seek,
  2335. };