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.

2786 lines
87KB

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