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.

2659 lines
84KB

  1. /*
  2. * Matroska file demuxer (no muxer yet)
  3. * Copyright (c) 2003-2004 The ffmpeg Project
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. */
  19. /**
  20. * @file matroska.c
  21. * Matroska file demuxer
  22. * by Ronald Bultje <rbultje@ronald.bitfreak.net>
  23. * with a little help from Moritz Bunkus <moritz@bunkus.org>
  24. * Specs available on the matroska project page:
  25. * http://www.matroska.org/.
  26. */
  27. #include "avformat.h"
  28. /* For codec_get_bmp_id and codec_get_wav_id. */
  29. #include "avi.h"
  30. #include "intfloat_readwrite.h"
  31. /* EBML version supported */
  32. #define EBML_VERSION 1
  33. /* top-level master-IDs */
  34. #define EBML_ID_HEADER 0x1A45DFA3
  35. /* IDs in the HEADER master */
  36. #define EBML_ID_EBMLVERSION 0x4286
  37. #define EBML_ID_EBMLREADVERSION 0x42F7
  38. #define EBML_ID_EBMLMAXIDLENGTH 0x42F2
  39. #define EBML_ID_EBMLMAXSIZELENGTH 0x42F3
  40. #define EBML_ID_DOCTYPE 0x4282
  41. #define EBML_ID_DOCTYPEVERSION 0x4287
  42. #define EBML_ID_DOCTYPEREADVERSION 0x4285
  43. /* general EBML types */
  44. #define EBML_ID_VOID 0xEC
  45. /*
  46. * Matroska element IDs. max. 32-bit.
  47. */
  48. /* toplevel segment */
  49. #define MATROSKA_ID_SEGMENT 0x18538067
  50. /* matroska top-level master IDs */
  51. #define MATROSKA_ID_INFO 0x1549A966
  52. #define MATROSKA_ID_TRACKS 0x1654AE6B
  53. #define MATROSKA_ID_CUES 0x1C53BB6B
  54. #define MATROSKA_ID_TAGS 0x1254C367
  55. #define MATROSKA_ID_SEEKHEAD 0x114D9B74
  56. #define MATROSKA_ID_CLUSTER 0x1F43B675
  57. /* IDs in the info master */
  58. #define MATROSKA_ID_TIMECODESCALE 0x2AD7B1
  59. #define MATROSKA_ID_DURATION 0x4489
  60. #define MATROSKA_ID_WRITINGAPP 0x5741
  61. #define MATROSKA_ID_MUXINGAPP 0x4D80
  62. #define MATROSKA_ID_DATEUTC 0x4461
  63. /* ID in the tracks master */
  64. #define MATROSKA_ID_TRACKENTRY 0xAE
  65. /* IDs in the trackentry master */
  66. #define MATROSKA_ID_TRACKNUMBER 0xD7
  67. #define MATROSKA_ID_TRACKUID 0x73C5
  68. #define MATROSKA_ID_TRACKTYPE 0x83
  69. #define MATROSKA_ID_TRACKAUDIO 0xE1
  70. #define MATROSKA_ID_TRACKVIDEO 0xE0
  71. #define MATROSKA_ID_CODECID 0x86
  72. #define MATROSKA_ID_CODECPRIVATE 0x63A2
  73. #define MATROSKA_ID_CODECNAME 0x258688
  74. #define MATROSKA_ID_CODECINFOURL 0x3B4040
  75. #define MATROSKA_ID_CODECDOWNLOADURL 0x26B240
  76. #define MATROSKA_ID_TRACKNAME 0x536E
  77. #define MATROSKA_ID_TRACKLANGUAGE 0x22B59C
  78. #define MATROSKA_ID_TRACKFLAGENABLED 0xB9
  79. #define MATROSKA_ID_TRACKFLAGDEFAULT 0x88
  80. #define MATROSKA_ID_TRACKFLAGLACING 0x9C
  81. #define MATROSKA_ID_TRACKMINCACHE 0x6DE7
  82. #define MATROSKA_ID_TRACKMAXCACHE 0x6DF8
  83. #define MATROSKA_ID_TRACKDEFAULTDURATION 0x23E383
  84. /* IDs in the trackvideo master */
  85. #define MATROSKA_ID_VIDEOFRAMERATE 0x2383E3
  86. #define MATROSKA_ID_VIDEODISPLAYWIDTH 0x54B0
  87. #define MATROSKA_ID_VIDEODISPLAYHEIGHT 0x54BA
  88. #define MATROSKA_ID_VIDEOPIXELWIDTH 0xB0
  89. #define MATROSKA_ID_VIDEOPIXELHEIGHT 0xBA
  90. #define MATROSKA_ID_VIDEOFLAGINTERLACED 0x9A
  91. #define MATROSKA_ID_VIDEOSTEREOMODE 0x53B9
  92. #define MATROSKA_ID_VIDEOASPECTRATIO 0x54B3
  93. #define MATROSKA_ID_VIDEOCOLOURSPACE 0x2EB524
  94. /* IDs in the trackaudio master */
  95. #define MATROSKA_ID_AUDIOSAMPLINGFREQ 0xB5
  96. #define MATROSKA_ID_AUDIOBITDEPTH 0x6264
  97. #define MATROSKA_ID_AUDIOCHANNELS 0x9F
  98. /* ID in the cues master */
  99. #define MATROSKA_ID_POINTENTRY 0xBB
  100. /* IDs in the pointentry master */
  101. #define MATROSKA_ID_CUETIME 0xB3
  102. #define MATROSKA_ID_CUETRACKPOSITION 0xB7
  103. /* IDs in the cuetrackposition master */
  104. #define MATROSKA_ID_CUETRACK 0xF7
  105. #define MATROSKA_ID_CUECLUSTERPOSITION 0xF1
  106. /* IDs in the tags master */
  107. /* TODO */
  108. /* IDs in the seekhead master */
  109. #define MATROSKA_ID_SEEKENTRY 0x4DBB
  110. /* IDs in the seekpoint master */
  111. #define MATROSKA_ID_SEEKID 0x53AB
  112. #define MATROSKA_ID_SEEKPOSITION 0x53AC
  113. /* IDs in the cluster master */
  114. #define MATROSKA_ID_CLUSTERTIMECODE 0xE7
  115. #define MATROSKA_ID_BLOCKGROUP 0xA0
  116. /* IDs in the blockgroup master */
  117. #define MATROSKA_ID_BLOCK 0xA1
  118. #define MATROSKA_ID_BLOCKDURATION 0x9B
  119. #define MATROSKA_ID_BLOCKREFERENCE 0xFB
  120. typedef enum {
  121. MATROSKA_TRACK_TYPE_VIDEO = 0x1,
  122. MATROSKA_TRACK_TYPE_AUDIO = 0x2,
  123. MATROSKA_TRACK_TYPE_COMPLEX = 0x3,
  124. MATROSKA_TRACK_TYPE_LOGO = 0x10,
  125. MATROSKA_TRACK_TYPE_SUBTITLE = 0x11,
  126. MATROSKA_TRACK_TYPE_CONTROL = 0x20,
  127. } MatroskaTrackType;
  128. typedef enum {
  129. MATROSKA_EYE_MODE_MONO = 0x0,
  130. MATROSKA_EYE_MODE_RIGHT = 0x1,
  131. MATROSKA_EYE_MODE_LEFT = 0x2,
  132. MATROSKA_EYE_MODE_BOTH = 0x3,
  133. } MatroskaEyeMode;
  134. typedef enum {
  135. MATROSKA_ASPECT_RATIO_MODE_FREE = 0x0,
  136. MATROSKA_ASPECT_RATIO_MODE_KEEP = 0x1,
  137. MATROSKA_ASPECT_RATIO_MODE_FIXED = 0x2,
  138. } MatroskaAspectRatioMode;
  139. /*
  140. * These aren't in any way "matroska-form" things,
  141. * it's just something I use in the muxer/demuxer.
  142. */
  143. typedef enum {
  144. MATROSKA_TRACK_ENABLED = (1<<0),
  145. MATROSKA_TRACK_DEFAULT = (1<<1),
  146. MATROSKA_TRACK_LACING = (1<<2),
  147. MATROSKA_TRACK_SHIFT = (1<<16)
  148. } MatroskaTrackFlags;
  149. typedef enum {
  150. MATROSKA_VIDEOTRACK_INTERLACED = (MATROSKA_TRACK_SHIFT<<0)
  151. } MatroskaVideoTrackFlags;
  152. /*
  153. * Matroska Codec IDs. Strings.
  154. */
  155. typedef struct CodecTags{
  156. char *str;
  157. enum CodecID id;
  158. }CodecTags;
  159. #define MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC "V_MS/VFW/FOURCC"
  160. #define MATROSKA_CODEC_ID_AUDIO_ACM "A_MS/ACM"
  161. CodecTags codec_tags[]={
  162. // {"V_MS/VFW/FOURCC" , CODEC_ID_NONE},
  163. {"V_UNCOMPRESSED" , CODEC_ID_RAWVIDEO},
  164. {"V_MPEG4/ISO/SP" , CODEC_ID_MPEG4},
  165. {"V_MPEG4/ISO/ASP" , CODEC_ID_MPEG4},
  166. {"V_MPEG4/ISO/AP" , CODEC_ID_MPEG4},
  167. {"V_MPEG4/ISO/AVC" , CODEC_ID_H264},
  168. {"V_MPEG4/MS/V3" , CODEC_ID_MSMPEG4V3},
  169. {"V_MPEG1" , CODEC_ID_MPEG1VIDEO},
  170. {"V_MPEG2" , CODEC_ID_MPEG2VIDEO},
  171. {"V_MJPEG" , CODEC_ID_MJPEG},
  172. {"V_REAL/RV10" , CODEC_ID_RV10},
  173. {"V_REAL/RV20" , CODEC_ID_RV20},
  174. {"V_REAL/RV30" , CODEC_ID_RV30},
  175. {"V_REAL/RV40" , CODEC_ID_RV40},
  176. /* TODO: Real/Quicktime */
  177. // {"A_MS/ACM" , CODEC_ID_NONE},
  178. {"A_MPEG/L1" , CODEC_ID_MP3},
  179. {"A_MPEG/L2" , CODEC_ID_MP3},
  180. {"A_MPEG/L3" , CODEC_ID_MP3},
  181. {"A_PCM/INT/BIG" , CODEC_ID_PCM_U16BE},
  182. {"A_PCM/INT/LIT" , CODEC_ID_PCM_U16LE},
  183. // {"A_PCM/FLOAT/IEEE" , CODEC_ID_NONE},
  184. {"A_AC3" , CODEC_ID_AC3},
  185. {"A_DTS" , CODEC_ID_DTS},
  186. {"A_VORBIS" , CODEC_ID_VORBIS},
  187. {"A_AAC/MPEG2/" , CODEC_ID_AAC},
  188. {"A_AAC/MPEG4/" , CODEC_ID_AAC},
  189. {NULL , CODEC_ID_NONE}
  190. /* TODO: AC3-9/10 (?), Real, Musepack, Quicktime */
  191. };
  192. /* max. depth in the EBML tree structure */
  193. #define EBML_MAX_DEPTH 16
  194. typedef struct Track {
  195. MatroskaTrackType type;
  196. /* Unique track number and track ID. stream_index is the index that
  197. * the calling app uses for this track. */
  198. uint32_t num,
  199. uid,
  200. stream_index;
  201. char *name,
  202. *language;
  203. char *codec_id,
  204. *codec_name;
  205. unsigned char *codec_priv;
  206. int codec_priv_size;
  207. int64_t default_duration;
  208. MatroskaTrackFlags flags;
  209. } MatroskaTrack;
  210. typedef struct MatroskaVideoTrack {
  211. MatroskaTrack track;
  212. int pixel_width,
  213. pixel_height,
  214. display_width,
  215. display_height;
  216. uint32_t fourcc;
  217. MatroskaAspectRatioMode ar_mode;
  218. MatroskaEyeMode eye_mode;
  219. //..
  220. } MatroskaVideoTrack;
  221. typedef struct MatroskaAudioTrack {
  222. MatroskaTrack track;
  223. int channels,
  224. bitdepth,
  225. samplerate;
  226. //..
  227. } MatroskaAudioTrack;
  228. typedef struct MatroskaSubtitleTrack {
  229. MatroskaTrack track;
  230. //..
  231. } MatroskaSubtitleTrack;
  232. typedef struct MatroskaLevel {
  233. uint64_t start, length;
  234. } MatroskaLevel;
  235. typedef struct MatroskaDemuxIndex {
  236. uint64_t pos; /* of the corresponding *cluster*! */
  237. uint16_t track; /* reference to 'num' */
  238. uint64_t time; /* in nanoseconds */
  239. } MatroskaDemuxIndex;
  240. typedef struct MatroskaDemuxContext {
  241. AVFormatContext *ctx;
  242. /* ebml stuff */
  243. int num_levels;
  244. MatroskaLevel levels[EBML_MAX_DEPTH];
  245. int level_up;
  246. /* matroska stuff */
  247. char *writing_app,
  248. *muxing_app;
  249. int64_t created;
  250. /* timescale in the file */
  251. int64_t time_scale;
  252. /* length, position (time, ns) */
  253. int64_t duration,
  254. pos;
  255. /* num_streams is the number of streams that av_new_stream() was called
  256. * for ( = that are available to the calling program). */
  257. int num_tracks, num_streams;
  258. MatroskaTrack *tracks[MAX_STREAMS];
  259. /* cache for ID peeking */
  260. uint32_t peek_id;
  261. /* byte position of the segment inside the stream */
  262. offset_t segment_start;
  263. /* The packet queue. */
  264. AVPacket **packets;
  265. int num_packets;
  266. /* have we already parse metadata/cues/clusters? */
  267. int metadata_parsed,
  268. index_parsed,
  269. done;
  270. /* The index for seeking. */
  271. int num_indexes;
  272. MatroskaDemuxIndex *index;
  273. } MatroskaDemuxContext;
  274. /*
  275. * The first few functions handle EBML file parsing. The rest
  276. * is the document interpretation. Matroska really just is a
  277. * EBML file.
  278. */
  279. /*
  280. * Return: the amount of levels in the hierarchy that the
  281. * current element lies higher than the previous one.
  282. * The opposite isn't done - that's auto-done using master
  283. * element reading.
  284. */
  285. static int
  286. ebml_read_element_level_up (MatroskaDemuxContext *matroska)
  287. {
  288. ByteIOContext *pb = &matroska->ctx->pb;
  289. offset_t pos = url_ftell(pb);
  290. int num = 0;
  291. while (matroska->num_levels > 0) {
  292. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  293. if (pos >= level->start + level->length) {
  294. matroska->num_levels--;
  295. num++;
  296. } else {
  297. break;
  298. }
  299. }
  300. return num;
  301. }
  302. /*
  303. * Read: an "EBML number", which is defined as a variable-length
  304. * array of bytes. The first byte indicates the length by giving a
  305. * number of 0-bits followed by a one. The position of the first
  306. * "one" bit inside the first byte indicates the length of this
  307. * number.
  308. * Returns: num. of bytes read. < 0 on error.
  309. */
  310. static int
  311. ebml_read_num (MatroskaDemuxContext *matroska,
  312. int max_size,
  313. uint64_t *number)
  314. {
  315. ByteIOContext *pb = &matroska->ctx->pb;
  316. int len_mask = 0x80, read = 1, n = 1;
  317. int64_t total = 0;
  318. /* the first byte tells us the length in bytes - get_byte() can normally
  319. * return 0, but since that's not a valid first ebmlID byte, we can
  320. * use it safely here to catch EOS. */
  321. if (!(total = get_byte(pb))) {
  322. /* we might encounter EOS here */
  323. if (!url_feof(pb)) {
  324. offset_t pos = url_ftell(pb);
  325. av_log(matroska->ctx, AV_LOG_ERROR,
  326. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  327. pos, pos);
  328. }
  329. return AVERROR_IO; /* EOS or actual I/O error */
  330. }
  331. /* get the length of the EBML number */
  332. while (read <= max_size && !(total & len_mask)) {
  333. read++;
  334. len_mask >>= 1;
  335. }
  336. if (read > max_size) {
  337. offset_t pos = url_ftell(pb) - 1;
  338. av_log(matroska->ctx, AV_LOG_ERROR,
  339. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  340. (uint8_t) total, pos, pos);
  341. return AVERROR_INVALIDDATA;
  342. }
  343. /* read out length */
  344. total &= ~len_mask;
  345. while (n++ < read)
  346. total = (total << 8) | get_byte(pb);
  347. *number = total;
  348. return read;
  349. }
  350. /*
  351. * Read: the element content data ID.
  352. * Return: the number of bytes read or < 0 on error.
  353. */
  354. static int
  355. ebml_read_element_id (MatroskaDemuxContext *matroska,
  356. uint32_t *id,
  357. int *level_up)
  358. {
  359. int read;
  360. uint64_t total;
  361. /* if we re-call this, use our cached ID */
  362. if (matroska->peek_id != 0) {
  363. if (level_up)
  364. *level_up = 0;
  365. *id = matroska->peek_id;
  366. return 0;
  367. }
  368. /* read out the "EBML number", include tag in ID */
  369. if ((read = ebml_read_num(matroska, 4, &total)) < 0)
  370. return read;
  371. *id = matroska->peek_id = total | (1 << (read * 7));
  372. /* level tracking */
  373. if (level_up)
  374. *level_up = ebml_read_element_level_up(matroska);
  375. return read;
  376. }
  377. /*
  378. * Read: element content length.
  379. * Return: the number of bytes read or < 0 on error.
  380. */
  381. static int
  382. ebml_read_element_length (MatroskaDemuxContext *matroska,
  383. uint64_t *length)
  384. {
  385. /* clear cache since we're now beyond that data point */
  386. matroska->peek_id = 0;
  387. /* read out the "EBML number", include tag in ID */
  388. return ebml_read_num(matroska, 8, length);
  389. }
  390. /*
  391. * Return: the ID of the next element, or 0 on error.
  392. * Level_up contains the amount of levels that this
  393. * next element lies higher than the previous one.
  394. */
  395. static uint32_t
  396. ebml_peek_id (MatroskaDemuxContext *matroska,
  397. int *level_up)
  398. {
  399. uint32_t id;
  400. assert(level_up != NULL);
  401. if (ebml_read_element_id(matroska, &id, level_up) < 0)
  402. return 0;
  403. return id;
  404. }
  405. /*
  406. * Seek to a given offset.
  407. * 0 is success, -1 is failure.
  408. */
  409. static int
  410. ebml_read_seek (MatroskaDemuxContext *matroska,
  411. offset_t offset)
  412. {
  413. ByteIOContext *pb = &matroska->ctx->pb;
  414. /* clear ID cache, if any */
  415. matroska->peek_id = 0;
  416. return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
  417. }
  418. /*
  419. * Skip the next element.
  420. * 0 is success, -1 is failure.
  421. */
  422. static int
  423. ebml_read_skip (MatroskaDemuxContext *matroska)
  424. {
  425. ByteIOContext *pb = &matroska->ctx->pb;
  426. uint32_t id;
  427. uint64_t length;
  428. int res;
  429. if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
  430. (res = ebml_read_element_length(matroska, &length)) < 0)
  431. return res;
  432. url_fskip(pb, length);
  433. return 0;
  434. }
  435. /*
  436. * Read the next element as an unsigned int.
  437. * 0 is success, < 0 is failure.
  438. */
  439. static int
  440. ebml_read_uint (MatroskaDemuxContext *matroska,
  441. uint32_t *id,
  442. uint64_t *num)
  443. {
  444. ByteIOContext *pb = &matroska->ctx->pb;
  445. int n = 0, size, res;
  446. uint64_t rlength;
  447. if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
  448. (res = ebml_read_element_length(matroska, &rlength)) < 0)
  449. return res;
  450. size = rlength;
  451. if (size < 1 || size > 8) {
  452. offset_t pos = url_ftell(pb);
  453. av_log(matroska->ctx, AV_LOG_ERROR,
  454. "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
  455. size, pos, pos);
  456. return AVERROR_INVALIDDATA;
  457. }
  458. /* big-endian ordening; build up number */
  459. *num = 0;
  460. while (n++ < size)
  461. *num = (*num << 8) | get_byte(pb);
  462. return 0;
  463. }
  464. /*
  465. * Read the next element as a signed int.
  466. * 0 is success, < 0 is failure.
  467. */
  468. static int
  469. ebml_read_sint (MatroskaDemuxContext *matroska,
  470. uint32_t *id,
  471. int64_t *num)
  472. {
  473. ByteIOContext *pb = &matroska->ctx->pb;
  474. int size, n = 1, negative = 0, res;
  475. uint64_t rlength;
  476. if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
  477. (res = ebml_read_element_length(matroska, &rlength)) < 0)
  478. return res;
  479. size = rlength;
  480. if (size < 1 || size > 8) {
  481. offset_t pos = url_ftell(pb);
  482. av_log(matroska->ctx, AV_LOG_ERROR,
  483. "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
  484. size, pos, pos);
  485. return AVERROR_INVALIDDATA;
  486. }
  487. if ((*num = get_byte(pb)) & 0x80) {
  488. negative = 1;
  489. *num &= ~0x80;
  490. }
  491. *num = 0;
  492. while (n++ < size)
  493. *num = (*num << 8) | get_byte(pb);
  494. /* make signed */
  495. if (negative)
  496. *num = *num - (1LL << ((8 * size) - 1));
  497. return 0;
  498. }
  499. /*
  500. * Read the next element as a float.
  501. * 0 is success, < 0 is failure.
  502. */
  503. static int
  504. ebml_read_float (MatroskaDemuxContext *matroska,
  505. uint32_t *id,
  506. double *num)
  507. {
  508. ByteIOContext *pb = &matroska->ctx->pb;
  509. int size, res;
  510. uint64_t rlength;
  511. if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
  512. (res = ebml_read_element_length(matroska, &rlength)) < 0)
  513. return res;
  514. size = rlength;
  515. if (size == 4) {
  516. *num= av_int2flt(get_be32(pb));
  517. } else if(size==8){
  518. *num= av_int2dbl(get_be64(pb));
  519. } else if(size==10){
  520. av_log(matroska->ctx, AV_LOG_ERROR,
  521. "FIXME! 10-byte floats unimplemented\n");
  522. return AVERROR_UNKNOWN;
  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->duration = num * matroska->time_scale;
  914. break;
  915. }
  916. case MATROSKA_ID_WRITINGAPP: {
  917. char *text;
  918. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  919. break;
  920. matroska->writing_app = text;
  921. break;
  922. }
  923. case MATROSKA_ID_MUXINGAPP: {
  924. char *text;
  925. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  926. break;
  927. matroska->muxing_app = text;
  928. break;
  929. }
  930. case MATROSKA_ID_DATEUTC: {
  931. int64_t time;
  932. if ((res = ebml_read_date(matroska, &id, &time)) < 0)
  933. break;
  934. matroska->created = time;
  935. break;
  936. }
  937. default:
  938. av_log(matroska->ctx, AV_LOG_INFO,
  939. "Unknown entry 0x%x in info header\n", id);
  940. /* fall-through */
  941. case EBML_ID_VOID:
  942. res = ebml_read_skip(matroska);
  943. break;
  944. }
  945. if (matroska->level_up) {
  946. matroska->level_up--;
  947. break;
  948. }
  949. }
  950. return res;
  951. }
  952. static int
  953. matroska_add_stream (MatroskaDemuxContext *matroska)
  954. {
  955. int res = 0;
  956. uint32_t id;
  957. MatroskaTrack *track;
  958. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
  959. /* Allocate a generic track. As soon as we know its type we'll realloc. */
  960. track = av_mallocz(sizeof(MatroskaTrack));
  961. matroska->num_tracks++;
  962. /* start with the master */
  963. if ((res = ebml_read_master(matroska, &id)) < 0)
  964. return res;
  965. /* try reading the trackentry headers */
  966. while (res == 0) {
  967. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  968. res = AVERROR_IO;
  969. break;
  970. } else if (matroska->level_up > 0) {
  971. matroska->level_up--;
  972. break;
  973. }
  974. switch (id) {
  975. /* track number (unique stream ID) */
  976. case MATROSKA_ID_TRACKNUMBER: {
  977. uint64_t num;
  978. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  979. break;
  980. track->num = num;
  981. break;
  982. }
  983. /* track UID (unique identifier) */
  984. case MATROSKA_ID_TRACKUID: {
  985. uint64_t num;
  986. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  987. break;
  988. track->uid = num;
  989. break;
  990. }
  991. /* track type (video, audio, combined, subtitle, etc.) */
  992. case MATROSKA_ID_TRACKTYPE: {
  993. uint64_t num;
  994. if (track->type != 0) {
  995. av_log(matroska->ctx, AV_LOG_INFO,
  996. "More than one tracktype in an entry - skip\n");
  997. break;
  998. }
  999. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1000. break;
  1001. track->type = num;
  1002. /* ok, so we're actually going to reallocate this thing */
  1003. switch (track->type) {
  1004. case MATROSKA_TRACK_TYPE_VIDEO:
  1005. track = (MatroskaTrack *)
  1006. av_realloc(track, sizeof(MatroskaVideoTrack));
  1007. break;
  1008. case MATROSKA_TRACK_TYPE_AUDIO:
  1009. track = (MatroskaTrack *)
  1010. av_realloc(track, sizeof(MatroskaAudioTrack));
  1011. ((MatroskaAudioTrack *)track)->channels = 1;
  1012. ((MatroskaAudioTrack *)track)->samplerate = 8000;
  1013. break;
  1014. case MATROSKA_TRACK_TYPE_SUBTITLE:
  1015. track = (MatroskaTrack *)
  1016. av_realloc(track, sizeof(MatroskaSubtitleTrack));
  1017. break;
  1018. case MATROSKA_TRACK_TYPE_COMPLEX:
  1019. case MATROSKA_TRACK_TYPE_LOGO:
  1020. case MATROSKA_TRACK_TYPE_CONTROL:
  1021. default:
  1022. av_log(matroska->ctx, AV_LOG_INFO,
  1023. "Unknown or unsupported track type 0x%x\n",
  1024. track->type);
  1025. track->type = 0;
  1026. break;
  1027. }
  1028. matroska->tracks[matroska->num_tracks - 1] = track;
  1029. break;
  1030. }
  1031. /* tracktype specific stuff for video */
  1032. case MATROSKA_ID_TRACKVIDEO: {
  1033. MatroskaVideoTrack *videotrack;
  1034. if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
  1035. av_log(matroska->ctx, AV_LOG_INFO,
  1036. "video data in non-video track - ignoring\n");
  1037. res = AVERROR_INVALIDDATA;
  1038. break;
  1039. } else if ((res = ebml_read_master(matroska, &id)) < 0)
  1040. break;
  1041. videotrack = (MatroskaVideoTrack *)track;
  1042. while (res == 0) {
  1043. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1044. res = AVERROR_IO;
  1045. break;
  1046. } else if (matroska->level_up > 0) {
  1047. matroska->level_up--;
  1048. break;
  1049. }
  1050. switch (id) {
  1051. /* fixme, this should be one-up, but I get it here */
  1052. case MATROSKA_ID_TRACKDEFAULTDURATION: {
  1053. uint64_t num;
  1054. if ((res = ebml_read_uint (matroska, &id,
  1055. &num)) < 0)
  1056. break;
  1057. track->default_duration = num;
  1058. break;
  1059. }
  1060. /* video framerate */
  1061. case MATROSKA_ID_VIDEOFRAMERATE: {
  1062. double num;
  1063. if ((res = ebml_read_float(matroska, &id,
  1064. &num)) < 0)
  1065. break;
  1066. track->default_duration = 1000000000 * (1. / num);
  1067. break;
  1068. }
  1069. /* width of the size to display the video at */
  1070. case MATROSKA_ID_VIDEODISPLAYWIDTH: {
  1071. uint64_t num;
  1072. if ((res = ebml_read_uint(matroska, &id,
  1073. &num)) < 0)
  1074. break;
  1075. videotrack->display_width = num;
  1076. break;
  1077. }
  1078. /* height of the size to display the video at */
  1079. case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
  1080. uint64_t num;
  1081. if ((res = ebml_read_uint(matroska, &id,
  1082. &num)) < 0)
  1083. break;
  1084. videotrack->display_height = num;
  1085. break;
  1086. }
  1087. /* width of the video in the file */
  1088. case MATROSKA_ID_VIDEOPIXELWIDTH: {
  1089. uint64_t num;
  1090. if ((res = ebml_read_uint(matroska, &id,
  1091. &num)) < 0)
  1092. break;
  1093. videotrack->pixel_width = num;
  1094. break;
  1095. }
  1096. /* height of the video in the file */
  1097. case MATROSKA_ID_VIDEOPIXELHEIGHT: {
  1098. uint64_t num;
  1099. if ((res = ebml_read_uint(matroska, &id,
  1100. &num)) < 0)
  1101. break;
  1102. videotrack->pixel_height = num;
  1103. break;
  1104. }
  1105. /* whether the video is interlaced */
  1106. case MATROSKA_ID_VIDEOFLAGINTERLACED: {
  1107. uint64_t num;
  1108. if ((res = ebml_read_uint(matroska, &id,
  1109. &num)) < 0)
  1110. break;
  1111. if (num)
  1112. track->flags |=
  1113. MATROSKA_VIDEOTRACK_INTERLACED;
  1114. else
  1115. track->flags &=
  1116. ~MATROSKA_VIDEOTRACK_INTERLACED;
  1117. break;
  1118. }
  1119. /* stereo mode (whether the video has two streams,
  1120. * where one is for the left eye and the other for
  1121. * the right eye, which creates a 3D-like
  1122. * effect) */
  1123. case MATROSKA_ID_VIDEOSTEREOMODE: {
  1124. uint64_t num;
  1125. if ((res = ebml_read_uint(matroska, &id,
  1126. &num)) < 0)
  1127. break;
  1128. if (num != MATROSKA_EYE_MODE_MONO &&
  1129. num != MATROSKA_EYE_MODE_LEFT &&
  1130. num != MATROSKA_EYE_MODE_RIGHT &&
  1131. num != MATROSKA_EYE_MODE_BOTH) {
  1132. av_log(matroska->ctx, AV_LOG_INFO,
  1133. "Ignoring unknown eye mode 0x%x\n",
  1134. (uint32_t) num);
  1135. break;
  1136. }
  1137. videotrack->eye_mode = num;
  1138. break;
  1139. }
  1140. /* aspect ratio behaviour */
  1141. case MATROSKA_ID_VIDEOASPECTRATIO: {
  1142. uint64_t num;
  1143. if ((res = ebml_read_uint(matroska, &id,
  1144. &num)) < 0)
  1145. break;
  1146. if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
  1147. num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
  1148. num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
  1149. av_log(matroska->ctx, AV_LOG_INFO,
  1150. "Ignoring unknown aspect ratio 0x%x\n",
  1151. (uint32_t) num);
  1152. break;
  1153. }
  1154. videotrack->ar_mode = num;
  1155. break;
  1156. }
  1157. /* colourspace (only matters for raw video)
  1158. * fourcc */
  1159. case MATROSKA_ID_VIDEOCOLOURSPACE: {
  1160. uint64_t num;
  1161. if ((res = ebml_read_uint(matroska, &id,
  1162. &num)) < 0)
  1163. break;
  1164. videotrack->fourcc = num;
  1165. break;
  1166. }
  1167. default:
  1168. av_log(matroska->ctx, AV_LOG_INFO,
  1169. "Unknown video track header entry "
  1170. "0x%x - ignoring\n", id);
  1171. /* pass-through */
  1172. case EBML_ID_VOID:
  1173. res = ebml_read_skip(matroska);
  1174. break;
  1175. }
  1176. if (matroska->level_up) {
  1177. matroska->level_up--;
  1178. break;
  1179. }
  1180. }
  1181. break;
  1182. }
  1183. /* tracktype specific stuff for audio */
  1184. case MATROSKA_ID_TRACKAUDIO: {
  1185. MatroskaAudioTrack *audiotrack;
  1186. if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
  1187. av_log(matroska->ctx, AV_LOG_INFO,
  1188. "audio data in non-audio track - ignoring\n");
  1189. res = AVERROR_INVALIDDATA;
  1190. break;
  1191. } else if ((res = ebml_read_master(matroska, &id)) < 0)
  1192. break;
  1193. audiotrack = (MatroskaAudioTrack *)track;
  1194. while (res == 0) {
  1195. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1196. res = AVERROR_IO;
  1197. break;
  1198. } else if (matroska->level_up > 0) {
  1199. matroska->level_up--;
  1200. break;
  1201. }
  1202. switch (id) {
  1203. /* samplerate */
  1204. case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
  1205. double num;
  1206. if ((res = ebml_read_float(matroska, &id,
  1207. &num)) < 0)
  1208. break;
  1209. audiotrack->samplerate = num;
  1210. break;
  1211. }
  1212. /* bitdepth */
  1213. case MATROSKA_ID_AUDIOBITDEPTH: {
  1214. uint64_t num;
  1215. if ((res = ebml_read_uint(matroska, &id,
  1216. &num)) < 0)
  1217. break;
  1218. audiotrack->bitdepth = num;
  1219. break;
  1220. }
  1221. /* channels */
  1222. case MATROSKA_ID_AUDIOCHANNELS: {
  1223. uint64_t num;
  1224. if ((res = ebml_read_uint(matroska, &id,
  1225. &num)) < 0)
  1226. break;
  1227. audiotrack->channels = num;
  1228. break;
  1229. }
  1230. default:
  1231. av_log(matroska->ctx, AV_LOG_INFO,
  1232. "Unknown audio track header entry "
  1233. "0x%x - ignoring\n", id);
  1234. /* pass-through */
  1235. case EBML_ID_VOID:
  1236. res = ebml_read_skip(matroska);
  1237. break;
  1238. }
  1239. if (matroska->level_up) {
  1240. matroska->level_up--;
  1241. break;
  1242. }
  1243. }
  1244. break;
  1245. }
  1246. /* codec identifier */
  1247. case MATROSKA_ID_CODECID: {
  1248. char *text;
  1249. if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
  1250. break;
  1251. track->codec_id = text;
  1252. break;
  1253. }
  1254. /* codec private data */
  1255. case MATROSKA_ID_CODECPRIVATE: {
  1256. uint8_t *data;
  1257. int size;
  1258. if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
  1259. break;
  1260. track->codec_priv = data;
  1261. track->codec_priv_size = size;
  1262. break;
  1263. }
  1264. /* name of the codec */
  1265. case MATROSKA_ID_CODECNAME: {
  1266. char *text;
  1267. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  1268. break;
  1269. track->codec_name = text;
  1270. break;
  1271. }
  1272. /* name of this track */
  1273. case MATROSKA_ID_TRACKNAME: {
  1274. char *text;
  1275. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  1276. break;
  1277. track->name = text;
  1278. break;
  1279. }
  1280. /* language (matters for audio/subtitles, mostly) */
  1281. case MATROSKA_ID_TRACKLANGUAGE: {
  1282. char *text;
  1283. if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
  1284. break;
  1285. track->language = text;
  1286. break;
  1287. }
  1288. /* whether this is actually used */
  1289. case MATROSKA_ID_TRACKFLAGENABLED: {
  1290. uint64_t num;
  1291. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1292. break;
  1293. if (num)
  1294. track->flags |= MATROSKA_TRACK_ENABLED;
  1295. else
  1296. track->flags &= ~MATROSKA_TRACK_ENABLED;
  1297. break;
  1298. }
  1299. /* whether it's the default for this track type */
  1300. case MATROSKA_ID_TRACKFLAGDEFAULT: {
  1301. uint64_t num;
  1302. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1303. break;
  1304. if (num)
  1305. track->flags |= MATROSKA_TRACK_DEFAULT;
  1306. else
  1307. track->flags &= ~MATROSKA_TRACK_DEFAULT;
  1308. break;
  1309. }
  1310. /* lacing (like MPEG, where blocks don't end/start on frame
  1311. * boundaries) */
  1312. case MATROSKA_ID_TRACKFLAGLACING: {
  1313. uint64_t num;
  1314. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1315. break;
  1316. if (num)
  1317. track->flags |= MATROSKA_TRACK_LACING;
  1318. else
  1319. track->flags &= ~MATROSKA_TRACK_LACING;
  1320. break;
  1321. }
  1322. /* default length (in time) of one data block in this track */
  1323. case MATROSKA_ID_TRACKDEFAULTDURATION: {
  1324. uint64_t num;
  1325. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  1326. break;
  1327. track->default_duration = num;
  1328. break;
  1329. }
  1330. default:
  1331. av_log(matroska->ctx, AV_LOG_INFO,
  1332. "Unknown track header entry 0x%x - ignoring\n", id);
  1333. /* pass-through */
  1334. case EBML_ID_VOID:
  1335. /* we ignore these because they're nothing useful. */
  1336. case MATROSKA_ID_CODECINFOURL:
  1337. case MATROSKA_ID_CODECDOWNLOADURL:
  1338. case MATROSKA_ID_TRACKMINCACHE:
  1339. case MATROSKA_ID_TRACKMAXCACHE:
  1340. res = ebml_read_skip(matroska);
  1341. break;
  1342. }
  1343. if (matroska->level_up) {
  1344. matroska->level_up--;
  1345. break;
  1346. }
  1347. }
  1348. return res;
  1349. }
  1350. static int
  1351. matroska_parse_tracks (MatroskaDemuxContext *matroska)
  1352. {
  1353. int res = 0;
  1354. uint32_t id;
  1355. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
  1356. while (res == 0) {
  1357. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1358. res = AVERROR_IO;
  1359. break;
  1360. } else if (matroska->level_up) {
  1361. matroska->level_up--;
  1362. break;
  1363. }
  1364. switch (id) {
  1365. /* one track within the "all-tracks" header */
  1366. case MATROSKA_ID_TRACKENTRY:
  1367. res = matroska_add_stream(matroska);
  1368. break;
  1369. default:
  1370. av_log(matroska->ctx, AV_LOG_INFO,
  1371. "Unknown entry 0x%x in track header\n", id);
  1372. /* fall-through */
  1373. case EBML_ID_VOID:
  1374. res = ebml_read_skip(matroska);
  1375. break;
  1376. }
  1377. if (matroska->level_up) {
  1378. matroska->level_up--;
  1379. break;
  1380. }
  1381. }
  1382. return res;
  1383. }
  1384. static int
  1385. matroska_parse_index (MatroskaDemuxContext *matroska)
  1386. {
  1387. int res = 0;
  1388. uint32_t id;
  1389. MatroskaDemuxIndex idx;
  1390. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
  1391. while (res == 0) {
  1392. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1393. res = AVERROR_IO;
  1394. break;
  1395. } else if (matroska->level_up) {
  1396. matroska->level_up--;
  1397. break;
  1398. }
  1399. switch (id) {
  1400. /* one single index entry ('point') */
  1401. case MATROSKA_ID_POINTENTRY:
  1402. if ((res = ebml_read_master(matroska, &id)) < 0)
  1403. break;
  1404. /* in the end, we hope to fill one entry with a
  1405. * timestamp, a file position and a tracknum */
  1406. idx.pos = (uint64_t) -1;
  1407. idx.time = (uint64_t) -1;
  1408. idx.track = (uint16_t) -1;
  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_CUETIME: {
  1420. int64_t time;
  1421. if ((res = ebml_read_uint(matroska, &id,
  1422. &time)) < 0)
  1423. break;
  1424. idx.time = time * matroska->time_scale;
  1425. break;
  1426. }
  1427. /* position in the file + track to which it
  1428. * belongs */
  1429. case MATROSKA_ID_CUETRACKPOSITION:
  1430. if ((res = ebml_read_master(matroska, &id)) < 0)
  1431. break;
  1432. while (res == 0) {
  1433. if (!(id = ebml_peek_id (matroska,
  1434. &matroska->level_up))) {
  1435. res = AVERROR_IO;
  1436. break;
  1437. } else if (matroska->level_up) {
  1438. matroska->level_up--;
  1439. break;
  1440. }
  1441. switch (id) {
  1442. /* track number */
  1443. case MATROSKA_ID_CUETRACK: {
  1444. uint64_t num;
  1445. if ((res = ebml_read_uint(matroska,
  1446. &id, &num)) < 0)
  1447. break;
  1448. idx.track = num;
  1449. break;
  1450. }
  1451. /* position in file */
  1452. case MATROSKA_ID_CUECLUSTERPOSITION: {
  1453. uint64_t num;
  1454. if ((res = ebml_read_uint(matroska,
  1455. &id, &num)) < 0)
  1456. break;
  1457. idx.pos = num;
  1458. break;
  1459. }
  1460. default:
  1461. av_log(matroska->ctx, AV_LOG_INFO,
  1462. "Unknown entry 0x%x in "
  1463. "CuesTrackPositions\n", id);
  1464. /* fall-through */
  1465. case EBML_ID_VOID:
  1466. res = ebml_read_skip(matroska);
  1467. break;
  1468. }
  1469. if (matroska->level_up) {
  1470. matroska->level_up--;
  1471. break;
  1472. }
  1473. }
  1474. break;
  1475. default:
  1476. av_log(matroska->ctx, AV_LOG_INFO,
  1477. "Unknown entry 0x%x in cuespoint "
  1478. "index\n", id);
  1479. /* fall-through */
  1480. case EBML_ID_VOID:
  1481. res = ebml_read_skip(matroska);
  1482. break;
  1483. }
  1484. if (matroska->level_up) {
  1485. matroska->level_up--;
  1486. break;
  1487. }
  1488. }
  1489. /* so let's see if we got what we wanted */
  1490. if (idx.pos != (uint64_t) -1 &&
  1491. idx.time != (uint64_t) -1 &&
  1492. idx.track != (uint16_t) -1) {
  1493. if (matroska->num_indexes % 32 == 0) {
  1494. /* re-allocate bigger index */
  1495. matroska->index =
  1496. av_realloc(matroska->index,
  1497. (matroska->num_indexes + 32) *
  1498. sizeof(MatroskaDemuxIndex));
  1499. }
  1500. matroska->index[matroska->num_indexes] = idx;
  1501. matroska->num_indexes++;
  1502. }
  1503. break;
  1504. default:
  1505. av_log(matroska->ctx, AV_LOG_INFO,
  1506. "Unknown entry 0x%x in cues header\n", id);
  1507. /* fall-through */
  1508. case EBML_ID_VOID:
  1509. res = ebml_read_skip(matroska);
  1510. break;
  1511. }
  1512. if (matroska->level_up) {
  1513. matroska->level_up--;
  1514. break;
  1515. }
  1516. }
  1517. return res;
  1518. }
  1519. static int
  1520. matroska_parse_metadata (MatroskaDemuxContext *matroska)
  1521. {
  1522. int res = 0;
  1523. uint32_t id;
  1524. while (res == 0) {
  1525. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1526. res = AVERROR_IO;
  1527. break;
  1528. } else if (matroska->level_up) {
  1529. matroska->level_up--;
  1530. break;
  1531. }
  1532. switch (id) {
  1533. /* Hm, this is unsupported... */
  1534. default:
  1535. av_log(matroska->ctx, AV_LOG_INFO,
  1536. "Unknown entry 0x%x in metadata header\n", id);
  1537. /* fall-through */
  1538. case EBML_ID_VOID:
  1539. res = ebml_read_skip(matroska);
  1540. break;
  1541. }
  1542. if (matroska->level_up) {
  1543. matroska->level_up--;
  1544. break;
  1545. }
  1546. }
  1547. return res;
  1548. }
  1549. static int
  1550. matroska_parse_seekhead (MatroskaDemuxContext *matroska)
  1551. {
  1552. int res = 0;
  1553. uint32_t id;
  1554. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
  1555. while (res == 0) {
  1556. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1557. res = AVERROR_IO;
  1558. break;
  1559. } else if (matroska->level_up) {
  1560. matroska->level_up--;
  1561. break;
  1562. }
  1563. switch (id) {
  1564. case MATROSKA_ID_SEEKENTRY: {
  1565. uint32_t seek_id = 0, peek_id_cache = 0;
  1566. uint64_t seek_pos = (uint64_t) -1, t;
  1567. if ((res = ebml_read_master(matroska, &id)) < 0)
  1568. break;
  1569. while (res == 0) {
  1570. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1571. res = AVERROR_IO;
  1572. break;
  1573. } else if (matroska->level_up) {
  1574. matroska->level_up--;
  1575. break;
  1576. }
  1577. switch (id) {
  1578. case MATROSKA_ID_SEEKID:
  1579. res = ebml_read_uint(matroska, &id, &t);
  1580. seek_id = t;
  1581. break;
  1582. case MATROSKA_ID_SEEKPOSITION:
  1583. res = ebml_read_uint(matroska, &id, &seek_pos);
  1584. break;
  1585. default:
  1586. av_log(matroska->ctx, AV_LOG_INFO,
  1587. "Unknown seekhead ID 0x%x\n", id);
  1588. /* fall-through */
  1589. case EBML_ID_VOID:
  1590. res = ebml_read_skip(matroska);
  1591. break;
  1592. }
  1593. if (matroska->level_up) {
  1594. matroska->level_up--;
  1595. break;
  1596. }
  1597. }
  1598. if (!seek_id || seek_pos == (uint64_t) -1) {
  1599. av_log(matroska->ctx, AV_LOG_INFO,
  1600. "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
  1601. seek_id, seek_pos);
  1602. break;
  1603. }
  1604. switch (seek_id) {
  1605. case MATROSKA_ID_CUES:
  1606. case MATROSKA_ID_TAGS: {
  1607. uint32_t level_up = matroska->level_up;
  1608. offset_t before_pos;
  1609. uint64_t length;
  1610. MatroskaLevel level;
  1611. /* remember the peeked ID and the current position */
  1612. peek_id_cache = matroska->peek_id;
  1613. before_pos = url_ftell(&matroska->ctx->pb);
  1614. /* seek */
  1615. if ((res = ebml_read_seek(matroska, seek_pos +
  1616. matroska->segment_start)) < 0)
  1617. return res;
  1618. /* we don't want to lose our seekhead level, so we add
  1619. * a dummy. This is a crude hack. */
  1620. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1621. av_log(matroska->ctx, AV_LOG_INFO,
  1622. "Max EBML element depth (%d) reached, "
  1623. "cannot parse further.\n", EBML_MAX_DEPTH);
  1624. return AVERROR_UNKNOWN;
  1625. }
  1626. level.start = 0;
  1627. level.length = (uint64_t)-1;
  1628. matroska->levels[matroska->num_levels] = level;
  1629. matroska->num_levels++;
  1630. /* check ID */
  1631. if (!(id = ebml_peek_id (matroska,
  1632. &matroska->level_up)))
  1633. break;
  1634. if (id != seek_id) {
  1635. av_log(matroska->ctx, AV_LOG_INFO,
  1636. "We looked for ID=0x%x but got "
  1637. "ID=0x%x (pos=%"PRIu64")",
  1638. seek_id, id, seek_pos +
  1639. matroska->segment_start);
  1640. goto finish;
  1641. }
  1642. /* read master + parse */
  1643. if ((res = ebml_read_master(matroska, &id)) < 0)
  1644. break;
  1645. switch (id) {
  1646. case MATROSKA_ID_CUES:
  1647. if (!(res = matroska_parse_index(matroska)) ||
  1648. url_feof(&matroska->ctx->pb)) {
  1649. matroska->index_parsed = 1;
  1650. res = 0;
  1651. }
  1652. break;
  1653. case MATROSKA_ID_TAGS:
  1654. if (!(res = matroska_parse_metadata(matroska)) ||
  1655. url_feof(&matroska->ctx->pb)) {
  1656. matroska->metadata_parsed = 1;
  1657. res = 0;
  1658. }
  1659. break;
  1660. }
  1661. if (res < 0)
  1662. break;
  1663. finish:
  1664. /* remove dummy level */
  1665. while (matroska->num_levels) {
  1666. matroska->num_levels--;
  1667. length =
  1668. matroska->levels[matroska->num_levels].length;
  1669. if (length == (uint64_t)-1)
  1670. break;
  1671. }
  1672. /* seek back */
  1673. if ((res = ebml_read_seek(matroska, before_pos)) < 0)
  1674. return res;
  1675. matroska->peek_id = peek_id_cache;
  1676. matroska->level_up = level_up;
  1677. break;
  1678. }
  1679. default:
  1680. av_log(matroska->ctx, AV_LOG_INFO,
  1681. "Ignoring seekhead entry for ID=0x%x\n",
  1682. seek_id);
  1683. break;
  1684. }
  1685. break;
  1686. }
  1687. default:
  1688. av_log(matroska->ctx, AV_LOG_INFO,
  1689. "Unknown seekhead ID 0x%x\n", id);
  1690. /* fall-through */
  1691. case EBML_ID_VOID:
  1692. res = ebml_read_skip(matroska);
  1693. break;
  1694. }
  1695. if (matroska->level_up) {
  1696. matroska->level_up--;
  1697. break;
  1698. }
  1699. }
  1700. return res;
  1701. }
  1702. static int
  1703. matroska_read_header (AVFormatContext *s,
  1704. AVFormatParameters *ap)
  1705. {
  1706. MatroskaDemuxContext *matroska = s->priv_data;
  1707. char *doctype;
  1708. int version, last_level, res = 0;
  1709. uint32_t id;
  1710. matroska->ctx = s;
  1711. /* First read the EBML header. */
  1712. doctype = NULL;
  1713. if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
  1714. return res;
  1715. if ((doctype == NULL) || strcmp(doctype, "matroska")) {
  1716. av_log(matroska->ctx, AV_LOG_ERROR,
  1717. "Wrong EBML doctype ('%s' != 'matroska').\n",
  1718. doctype ? doctype : "(none)");
  1719. if (doctype)
  1720. av_free(doctype);
  1721. return AVERROR_NOFMT;
  1722. }
  1723. av_free(doctype);
  1724. if (version != 1) {
  1725. av_log(matroska->ctx, AV_LOG_ERROR,
  1726. "Matroska demuxer version 1 too old for file version %d\n",
  1727. version);
  1728. return AVERROR_NOFMT;
  1729. }
  1730. /* The next thing is a segment. */
  1731. while (1) {
  1732. if (!(id = ebml_peek_id(matroska, &last_level)))
  1733. return AVERROR_IO;
  1734. if (id == MATROSKA_ID_SEGMENT)
  1735. break;
  1736. /* oi! */
  1737. av_log(matroska->ctx, AV_LOG_INFO,
  1738. "Expected a Segment ID (0x%x), but received 0x%x!\n",
  1739. MATROSKA_ID_SEGMENT, id);
  1740. if ((res = ebml_read_skip(matroska)) < 0)
  1741. return res;
  1742. }
  1743. /* We now have a Matroska segment.
  1744. * Seeks are from the beginning of the segment,
  1745. * after the segment ID/length. */
  1746. if ((res = ebml_read_master(matroska, &id)) < 0)
  1747. return res;
  1748. matroska->segment_start = url_ftell(&s->pb);
  1749. matroska->time_scale = 1000000;
  1750. /* we've found our segment, start reading the different contents in here */
  1751. while (res == 0) {
  1752. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1753. res = AVERROR_IO;
  1754. break;
  1755. } else if (matroska->level_up) {
  1756. matroska->level_up--;
  1757. break;
  1758. }
  1759. switch (id) {
  1760. /* stream info */
  1761. case MATROSKA_ID_INFO: {
  1762. if ((res = ebml_read_master(matroska, &id)) < 0)
  1763. break;
  1764. res = matroska_parse_info(matroska);
  1765. break;
  1766. }
  1767. /* track info headers */
  1768. case MATROSKA_ID_TRACKS: {
  1769. if ((res = ebml_read_master(matroska, &id)) < 0)
  1770. break;
  1771. res = matroska_parse_tracks(matroska);
  1772. break;
  1773. }
  1774. /* stream index */
  1775. case MATROSKA_ID_CUES: {
  1776. if (!matroska->index_parsed) {
  1777. if ((res = ebml_read_master(matroska, &id)) < 0)
  1778. break;
  1779. res = matroska_parse_index(matroska);
  1780. } else
  1781. res = ebml_read_skip(matroska);
  1782. break;
  1783. }
  1784. /* metadata */
  1785. case MATROSKA_ID_TAGS: {
  1786. if (!matroska->metadata_parsed) {
  1787. if ((res = ebml_read_master(matroska, &id)) < 0)
  1788. break;
  1789. res = matroska_parse_metadata(matroska);
  1790. } else
  1791. res = ebml_read_skip(matroska);
  1792. break;
  1793. }
  1794. /* file index (if seekable, seek to Cues/Tags to parse it) */
  1795. case MATROSKA_ID_SEEKHEAD: {
  1796. if ((res = ebml_read_master(matroska, &id)) < 0)
  1797. break;
  1798. res = matroska_parse_seekhead(matroska);
  1799. break;
  1800. }
  1801. case MATROSKA_ID_CLUSTER: {
  1802. /* Do not read the master - this will be done in the next
  1803. * call to matroska_read_packet. */
  1804. res = 1;
  1805. break;
  1806. }
  1807. default:
  1808. av_log(matroska->ctx, AV_LOG_INFO,
  1809. "Unknown matroska file header ID 0x%x\n", id);
  1810. /* fall-through */
  1811. case EBML_ID_VOID:
  1812. res = ebml_read_skip(matroska);
  1813. break;
  1814. }
  1815. if (matroska->level_up) {
  1816. matroska->level_up--;
  1817. break;
  1818. }
  1819. }
  1820. if (res < 0)
  1821. return res;
  1822. /* Have we found a cluster? */
  1823. if (res == 1) {
  1824. int i, j;
  1825. enum CodecID codec_id= CODEC_ID_NONE;
  1826. MatroskaTrack *track;
  1827. AVStream *st;
  1828. for (i = 0; i < matroska->num_tracks; i++) {
  1829. void *extradata = NULL;
  1830. int extradata_size = 0;
  1831. track = matroska->tracks[i];
  1832. /* libavformat does not really support subtitles.
  1833. * Also apply some sanity checks. */
  1834. if ((track->type == MATROSKA_TRACK_TYPE_SUBTITLE) ||
  1835. (track->codec_id == NULL))
  1836. continue;
  1837. for(j=0; codec_tags[j].str; j++){
  1838. if(!strcmp(codec_tags[j].str, track->codec_id)){
  1839. codec_id= codec_tags[j].id;
  1840. break;
  1841. }
  1842. }
  1843. /* Set the FourCC from the CodecID. */
  1844. /* This is the MS compatibility mode which stores a
  1845. * BITMAPINFOHEADER in the CodecPrivate. */
  1846. if (!strcmp(track->codec_id,
  1847. MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
  1848. (track->codec_priv_size >= 40) &&
  1849. (track->codec_priv != NULL)) {
  1850. unsigned char *p;
  1851. /* Offset of biCompression. Stored in LE. */
  1852. p = (unsigned char *)track->codec_priv + 16;
  1853. ((MatroskaVideoTrack *)track)->fourcc = (p[3] << 24) |
  1854. (p[2] << 16) | (p[1] << 8) | p[0];
  1855. codec_id = codec_get_bmp_id(((MatroskaVideoTrack *)track)->fourcc);
  1856. }
  1857. /* This is the MS compatibility mode which stores a
  1858. * WAVEFORMATEX in the CodecPrivate. */
  1859. else if (!strcmp(track->codec_id,
  1860. MATROSKA_CODEC_ID_AUDIO_ACM) &&
  1861. (track->codec_priv_size >= 18) &&
  1862. (track->codec_priv != NULL)) {
  1863. unsigned char *p;
  1864. uint16_t tag;
  1865. /* Offset of wFormatTag. Stored in LE. */
  1866. p = (unsigned char *)track->codec_priv;
  1867. tag = (p[1] << 8) | p[0];
  1868. codec_id = codec_get_wav_id(tag);
  1869. }
  1870. if (codec_id == CODEC_ID_NONE) {
  1871. av_log(matroska->ctx, AV_LOG_INFO,
  1872. "Unknown/unsupported CodecID %s.\n",
  1873. track->codec_id);
  1874. }
  1875. track->stream_index = matroska->num_streams;
  1876. matroska->num_streams++;
  1877. st = av_new_stream(s, track->stream_index);
  1878. if (st == NULL)
  1879. return AVERROR_NOMEM;
  1880. av_set_pts_info(st, 24, 1, 1000); /* 24 bit pts in ms */
  1881. st->codec->codec_id = codec_id;
  1882. if(extradata){
  1883. st->codec->extradata = extradata;
  1884. st->codec->extradata_size = extradata_size;
  1885. } else if(track->codec_priv && track->codec_priv_size > 0){
  1886. st->codec->extradata = av_malloc(track->codec_priv_size);
  1887. if(st->codec->extradata == NULL)
  1888. return AVERROR_NOMEM;
  1889. st->codec->extradata_size = track->codec_priv_size;
  1890. memcpy(st->codec->extradata, track->codec_priv,
  1891. track->codec_priv_size);
  1892. }
  1893. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1894. MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
  1895. st->codec->codec_type = CODEC_TYPE_VIDEO;
  1896. st->codec->codec_tag = videotrack->fourcc;
  1897. st->codec->width = videotrack->pixel_width;
  1898. st->codec->height = videotrack->pixel_height;
  1899. if (videotrack->display_width == 0)
  1900. videotrack->display_width= videotrack->pixel_width;
  1901. if (videotrack->display_height == 0)
  1902. videotrack->display_height= videotrack->pixel_height;
  1903. av_reduce(&st->codec->sample_aspect_ratio.num,
  1904. &st->codec->sample_aspect_ratio.den,
  1905. st->codec->height * videotrack->display_width,
  1906. st->codec-> width * videotrack->display_height,
  1907. 255);
  1908. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1909. MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
  1910. st->codec->codec_type = CODEC_TYPE_AUDIO;
  1911. st->codec->sample_rate = audiotrack->samplerate;
  1912. st->codec->channels = audiotrack->channels;
  1913. }
  1914. /* What do we do with private data? E.g. for Vorbis. */
  1915. }
  1916. }
  1917. return 0;
  1918. }
  1919. static int
  1920. matroska_find_track_by_num (MatroskaDemuxContext *matroska,
  1921. int num)
  1922. {
  1923. int i;
  1924. for (i = 0; i < matroska->num_tracks; i++)
  1925. if (matroska->tracks[i]->num == num)
  1926. return i;
  1927. return -1;
  1928. }
  1929. static int
  1930. matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
  1931. uint64_t cluster_time)
  1932. {
  1933. int res = 0;
  1934. uint32_t id;
  1935. AVPacket *pkt;
  1936. int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
  1937. av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
  1938. while (res == 0) {
  1939. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  1940. res = AVERROR_IO;
  1941. break;
  1942. } else if (matroska->level_up) {
  1943. matroska->level_up--;
  1944. break;
  1945. }
  1946. switch (id) {
  1947. /* one block inside the group. Note, block parsing is one
  1948. * of the harder things, so this code is a bit complicated.
  1949. * See http://www.matroska.org/ for documentation. */
  1950. case MATROSKA_ID_BLOCK: {
  1951. uint8_t *data, *origdata;
  1952. int size;
  1953. uint64_t time;
  1954. uint32_t *lace_size = NULL;
  1955. int n, track, flags, laces = 0;
  1956. uint64_t num;
  1957. int64_t pos= url_ftell(&matroska->ctx->pb);
  1958. if ((res = ebml_read_binary(matroska, &id, &data, &size)) < 0)
  1959. break;
  1960. origdata = data;
  1961. /* first byte(s): blocknum */
  1962. if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
  1963. av_log(matroska->ctx, AV_LOG_ERROR,
  1964. "EBML block data error\n");
  1965. av_free(origdata);
  1966. break;
  1967. }
  1968. data += n;
  1969. size -= n;
  1970. /* fetch track from num */
  1971. track = matroska_find_track_by_num(matroska, num);
  1972. if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
  1973. av_log(matroska->ctx, AV_LOG_INFO,
  1974. "Invalid stream %d or size %u\n", track, size);
  1975. av_free(origdata);
  1976. break;
  1977. }
  1978. if(matroska->ctx->streams[ matroska->tracks[track]->stream_index ]->discard >= AVDISCARD_ALL){
  1979. av_free(origdata);
  1980. break;
  1981. }
  1982. /* time (relative to cluster time) */
  1983. time = ((data[0] << 8) | data[1]) * matroska->time_scale;
  1984. data += 2;
  1985. size -= 2;
  1986. flags = *data;
  1987. data += 1;
  1988. size -= 1;
  1989. switch ((flags & 0x06) >> 1) {
  1990. case 0x0: /* no lacing */
  1991. laces = 1;
  1992. lace_size = av_mallocz(sizeof(int));
  1993. lace_size[0] = size;
  1994. break;
  1995. case 0x1: /* xiph lacing */
  1996. case 0x2: /* fixed-size lacing */
  1997. case 0x3: /* EBML lacing */
  1998. if (size == 0) {
  1999. res = -1;
  2000. break;
  2001. }
  2002. laces = (*data) + 1;
  2003. data += 1;
  2004. size -= 1;
  2005. lace_size = av_mallocz(laces * sizeof(int));
  2006. switch ((flags & 0x06) >> 1) {
  2007. case 0x1: /* xiph lacing */ {
  2008. uint8_t temp;
  2009. uint32_t total = 0;
  2010. for (n = 0; res == 0 && n < laces - 1; n++) {
  2011. while (1) {
  2012. if (size == 0) {
  2013. res = -1;
  2014. break;
  2015. }
  2016. temp = *data;
  2017. lace_size[n] += temp;
  2018. data += 1;
  2019. size -= 1;
  2020. if (temp != 0xff)
  2021. break;
  2022. }
  2023. total += lace_size[n];
  2024. }
  2025. lace_size[n] = size - total;
  2026. break;
  2027. }
  2028. case 0x2: /* fixed-size lacing */
  2029. for (n = 0; n < laces; n++)
  2030. lace_size[n] = size / laces;
  2031. break;
  2032. case 0x3: /* EBML lacing */ {
  2033. uint32_t total;
  2034. n = matroska_ebmlnum_uint(data, size, &num);
  2035. if (n < 0) {
  2036. av_log(matroska->ctx, AV_LOG_INFO,
  2037. "EBML block data error\n");
  2038. break;
  2039. }
  2040. data += n;
  2041. size -= n;
  2042. total = lace_size[0] = num;
  2043. for (n = 1; res == 0 && n < laces - 1; n++) {
  2044. int64_t snum;
  2045. int r;
  2046. r = matroska_ebmlnum_sint (data, size,
  2047. &snum);
  2048. if (r < 0) {
  2049. av_log(matroska->ctx, AV_LOG_INFO,
  2050. "EBML block data error\n");
  2051. break;
  2052. }
  2053. data += r;
  2054. size -= r;
  2055. lace_size[n] = lace_size[n - 1] + snum;
  2056. total += lace_size[n];
  2057. }
  2058. lace_size[n] = size - total;
  2059. break;
  2060. }
  2061. }
  2062. break;
  2063. }
  2064. if (res == 0) {
  2065. for (n = 0; n < laces; n++) {
  2066. uint64_t timecode = 0;
  2067. pkt = av_mallocz(sizeof(AVPacket));
  2068. /* XXX: prevent data copy... */
  2069. if (av_new_packet(pkt,lace_size[n]) < 0) {
  2070. res = AVERROR_NOMEM;
  2071. break;
  2072. }
  2073. if (cluster_time != (uint64_t)-1) {
  2074. if (time < 0 && (-time) > cluster_time)
  2075. timecode = cluster_time;
  2076. else
  2077. timecode = cluster_time + time;
  2078. }
  2079. /* FIXME: duration */
  2080. memcpy(pkt->data, data, lace_size[n]);
  2081. data += lace_size[n];
  2082. if (n == 0)
  2083. pkt->flags = is_keyframe;
  2084. pkt->stream_index =
  2085. matroska->tracks[track]->stream_index;
  2086. pkt->pts = timecode / 1000000; /* ns to ms */
  2087. pkt->pos= pos;
  2088. matroska_queue_packet(matroska, pkt);
  2089. }
  2090. }
  2091. av_free(lace_size);
  2092. av_free(origdata);
  2093. break;
  2094. }
  2095. case MATROSKA_ID_BLOCKDURATION: {
  2096. uint64_t num;
  2097. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  2098. break;
  2099. av_log(matroska->ctx, AV_LOG_INFO,
  2100. "FIXME: implement support for BlockDuration\n");
  2101. break;
  2102. }
  2103. case MATROSKA_ID_BLOCKREFERENCE:
  2104. /* We've found a reference, so not even the first frame in
  2105. * the lace is a key frame. */
  2106. is_keyframe = 0;
  2107. if (last_num_packets != matroska->num_packets)
  2108. matroska->packets[last_num_packets]->flags = 0;
  2109. res = ebml_read_skip(matroska);
  2110. break;
  2111. default:
  2112. av_log(matroska->ctx, AV_LOG_INFO,
  2113. "Unknown entry 0x%x in blockgroup data\n", id);
  2114. /* fall-through */
  2115. case EBML_ID_VOID:
  2116. res = ebml_read_skip(matroska);
  2117. break;
  2118. }
  2119. if (matroska->level_up) {
  2120. matroska->level_up--;
  2121. break;
  2122. }
  2123. }
  2124. return res;
  2125. }
  2126. static int
  2127. matroska_parse_cluster (MatroskaDemuxContext *matroska)
  2128. {
  2129. int res = 0;
  2130. uint32_t id;
  2131. uint64_t cluster_time = 0;
  2132. av_log(matroska->ctx, AV_LOG_DEBUG,
  2133. "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
  2134. while (res == 0) {
  2135. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2136. res = AVERROR_IO;
  2137. break;
  2138. } else if (matroska->level_up) {
  2139. matroska->level_up--;
  2140. break;
  2141. }
  2142. switch (id) {
  2143. /* cluster timecode */
  2144. case MATROSKA_ID_CLUSTERTIMECODE: {
  2145. uint64_t num;
  2146. if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
  2147. break;
  2148. cluster_time = num * matroska->time_scale;
  2149. break;
  2150. }
  2151. /* a group of blocks inside a cluster */
  2152. case MATROSKA_ID_BLOCKGROUP:
  2153. if ((res = ebml_read_master(matroska, &id)) < 0)
  2154. break;
  2155. res = matroska_parse_blockgroup(matroska, cluster_time);
  2156. break;
  2157. default:
  2158. av_log(matroska->ctx, AV_LOG_INFO,
  2159. "Unknown entry 0x%x in cluster data\n", id);
  2160. /* fall-through */
  2161. case EBML_ID_VOID:
  2162. res = ebml_read_skip(matroska);
  2163. break;
  2164. }
  2165. if (matroska->level_up) {
  2166. matroska->level_up--;
  2167. break;
  2168. }
  2169. }
  2170. return res;
  2171. }
  2172. static int
  2173. matroska_read_packet (AVFormatContext *s,
  2174. AVPacket *pkt)
  2175. {
  2176. MatroskaDemuxContext *matroska = s->priv_data;
  2177. int res = 0;
  2178. uint32_t id;
  2179. /* Do we still have a packet queued? */
  2180. if (matroska_deliver_packet(matroska, pkt) == 0)
  2181. return 0;
  2182. /* Have we already reached the end? */
  2183. if (matroska->done)
  2184. return AVERROR_IO;
  2185. while (res == 0) {
  2186. if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
  2187. res = AVERROR_IO;
  2188. break;
  2189. } else if (matroska->level_up) {
  2190. matroska->level_up--;
  2191. break;
  2192. }
  2193. switch (id) {
  2194. case MATROSKA_ID_CLUSTER:
  2195. if ((res = ebml_read_master(matroska, &id)) < 0)
  2196. break;
  2197. if ((res = matroska_parse_cluster(matroska)) == 0)
  2198. res = 1; /* Parsed one cluster, let's get out. */
  2199. break;
  2200. default:
  2201. case EBML_ID_VOID:
  2202. res = ebml_read_skip(matroska);
  2203. break;
  2204. }
  2205. if (matroska->level_up) {
  2206. matroska->level_up--;
  2207. break;
  2208. }
  2209. }
  2210. if (res == -1)
  2211. matroska->done = 1;
  2212. return matroska_deliver_packet(matroska, pkt);
  2213. }
  2214. static int
  2215. matroska_read_close (AVFormatContext *s)
  2216. {
  2217. MatroskaDemuxContext *matroska = s->priv_data;
  2218. int n = 0;
  2219. if (matroska->writing_app)
  2220. av_free(matroska->writing_app);
  2221. if (matroska->muxing_app)
  2222. av_free(matroska->muxing_app);
  2223. if (matroska->index)
  2224. av_free(matroska->index);
  2225. if (matroska->packets != NULL) {
  2226. for (n = 0; n < matroska->num_packets; n++) {
  2227. av_free_packet(matroska->packets[n]);
  2228. av_free(matroska->packets[n]);
  2229. }
  2230. av_free(matroska->packets);
  2231. }
  2232. for (n = 0; n < matroska->num_tracks; n++) {
  2233. MatroskaTrack *track = matroska->tracks[n];
  2234. if (track->codec_id)
  2235. av_free(track->codec_id);
  2236. if (track->codec_name)
  2237. av_free(track->codec_name);
  2238. if (track->codec_priv)
  2239. av_free(track->codec_priv);
  2240. if (track->name)
  2241. av_free(track->name);
  2242. if (track->language)
  2243. av_free(track->language);
  2244. av_free(track);
  2245. }
  2246. for (n = 0; n < s->nb_streams; n++) {
  2247. av_free(s->streams[n]->codec->extradata);
  2248. }
  2249. memset(matroska, 0, sizeof(MatroskaDemuxContext));
  2250. return 0;
  2251. }
  2252. static AVInputFormat matroska_iformat = {
  2253. "matroska",
  2254. "Matroska file format",
  2255. sizeof(MatroskaDemuxContext),
  2256. matroska_probe,
  2257. matroska_read_header,
  2258. matroska_read_packet,
  2259. matroska_read_close,
  2260. };
  2261. int
  2262. matroska_init(void)
  2263. {
  2264. av_register_input_format(&matroska_iformat);
  2265. return 0;
  2266. }