You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2749 lines
88KB

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