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.

2768 lines
89KB

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