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.

2718 lines
86KB

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