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.

2845 lines
89KB

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