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.

2643 lines
83KB

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