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.

1608 lines
56KB

  1. /*
  2. * Matroska file demuxer
  3. * Copyright (c) 2003-2008 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 matroskadec.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. * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
  27. * Specs available on the Matroska project page: http://www.matroska.org/.
  28. */
  29. #include "avformat.h"
  30. /* For codec_get_id(). */
  31. #include "riff.h"
  32. #include "isom.h"
  33. #include "matroska.h"
  34. #include "libavcodec/mpeg4audio.h"
  35. #include "libavutil/intfloat_readwrite.h"
  36. #include "libavutil/avstring.h"
  37. #include "libavutil/lzo.h"
  38. #ifdef CONFIG_ZLIB
  39. #include <zlib.h>
  40. #endif
  41. #ifdef CONFIG_BZLIB
  42. #include <bzlib.h>
  43. #endif
  44. typedef enum {
  45. EBML_NONE,
  46. EBML_UINT,
  47. EBML_FLOAT,
  48. EBML_STR,
  49. EBML_UTF8,
  50. EBML_BIN,
  51. EBML_NEST,
  52. EBML_PASS,
  53. EBML_STOP,
  54. } EbmlType;
  55. typedef const struct EbmlSyntax {
  56. uint32_t id;
  57. EbmlType type;
  58. int list_elem_size;
  59. int data_offset;
  60. union {
  61. uint64_t u;
  62. double f;
  63. const char *s;
  64. const struct EbmlSyntax *n;
  65. } def;
  66. } EbmlSyntax;
  67. typedef struct {
  68. int nb_elem;
  69. void *elem;
  70. } EbmlList;
  71. typedef struct {
  72. int size;
  73. uint8_t *data;
  74. int64_t pos;
  75. } EbmlBin;
  76. typedef struct {
  77. uint64_t version;
  78. uint64_t max_size;
  79. uint64_t id_length;
  80. char *doctype;
  81. uint64_t doctype_version;
  82. } Ebml;
  83. typedef struct {
  84. uint64_t algo;
  85. EbmlBin settings;
  86. } MatroskaTrackCompression;
  87. typedef struct {
  88. uint64_t scope;
  89. uint64_t type;
  90. MatroskaTrackCompression compression;
  91. } MatroskaTrackEncoding;
  92. typedef struct {
  93. double frame_rate;
  94. uint64_t display_width;
  95. uint64_t display_height;
  96. uint64_t pixel_width;
  97. uint64_t pixel_height;
  98. uint64_t fourcc;
  99. } MatroskaTrackVideo;
  100. typedef struct {
  101. double samplerate;
  102. double out_samplerate;
  103. uint64_t bitdepth;
  104. uint64_t channels;
  105. /* real audio header (extracted from extradata) */
  106. int coded_framesize;
  107. int sub_packet_h;
  108. int frame_size;
  109. int sub_packet_size;
  110. int sub_packet_cnt;
  111. int pkt_cnt;
  112. uint8_t *buf;
  113. } MatroskaTrackAudio;
  114. typedef struct {
  115. uint64_t num;
  116. uint64_t type;
  117. char *codec_id;
  118. EbmlBin codec_priv;
  119. char *language;
  120. double time_scale;
  121. uint64_t default_duration;
  122. uint64_t flag_default;
  123. MatroskaTrackVideo video;
  124. MatroskaTrackAudio audio;
  125. EbmlList encodings;
  126. AVStream *stream;
  127. } MatroskaTrack;
  128. typedef struct {
  129. char *filename;
  130. char *mime;
  131. EbmlBin bin;
  132. } MatroskaAttachement;
  133. typedef struct {
  134. uint64_t start;
  135. uint64_t end;
  136. uint64_t uid;
  137. char *title;
  138. } MatroskaChapter;
  139. typedef struct {
  140. uint64_t track;
  141. uint64_t pos;
  142. } MatroskaIndexPos;
  143. typedef struct {
  144. uint64_t time;
  145. EbmlList pos;
  146. } MatroskaIndex;
  147. typedef struct {
  148. uint64_t id;
  149. uint64_t pos;
  150. } MatroskaSeekhead;
  151. typedef struct {
  152. uint64_t start;
  153. uint64_t length;
  154. } MatroskaLevel;
  155. typedef struct {
  156. AVFormatContext *ctx;
  157. /* EBML stuff */
  158. int num_levels;
  159. MatroskaLevel levels[EBML_MAX_DEPTH];
  160. int level_up;
  161. uint64_t time_scale;
  162. double duration;
  163. char *title;
  164. EbmlList tracks;
  165. EbmlList attachments;
  166. EbmlList chapters;
  167. EbmlList index;
  168. EbmlList seekhead;
  169. /* byte position of the segment inside the stream */
  170. offset_t segment_start;
  171. /* the packet queue */
  172. AVPacket **packets;
  173. int num_packets;
  174. int done;
  175. int has_cluster_id;
  176. /* What to skip before effectively reading a packet. */
  177. int skip_to_keyframe;
  178. AVStream *skip_to_stream;
  179. } MatroskaDemuxContext;
  180. typedef struct {
  181. uint64_t duration;
  182. int64_t reference;
  183. EbmlBin bin;
  184. } MatroskaBlock;
  185. typedef struct {
  186. uint64_t timecode;
  187. EbmlList blocks;
  188. } MatroskaCluster;
  189. #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
  190. static EbmlSyntax ebml_header[] = {
  191. { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
  192. { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
  193. { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
  194. { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
  195. { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
  196. { EBML_ID_EBMLVERSION, EBML_NONE },
  197. { EBML_ID_DOCTYPEVERSION, EBML_NONE },
  198. { EBML_ID_VOID, EBML_NONE },
  199. { 0 }
  200. };
  201. static EbmlSyntax ebml_syntax[] = {
  202. { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
  203. { 0 }
  204. };
  205. static EbmlSyntax matroska_info[] = {
  206. { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
  207. { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
  208. { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
  209. { MATROSKA_ID_WRITINGAPP, EBML_NONE },
  210. { MATROSKA_ID_MUXINGAPP, EBML_NONE },
  211. { MATROSKA_ID_DATEUTC, EBML_NONE },
  212. { MATROSKA_ID_SEGMENTUID, EBML_NONE },
  213. { EBML_ID_VOID, EBML_NONE },
  214. { 0 }
  215. };
  216. static EbmlSyntax matroska_track_video[] = {
  217. { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
  218. { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
  219. { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
  220. { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
  221. { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
  222. { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
  223. { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
  224. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
  225. { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
  226. { EBML_ID_VOID, EBML_NONE },
  227. { 0 }
  228. };
  229. static EbmlSyntax matroska_track_audio[] = {
  230. { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
  231. { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
  232. { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
  233. { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
  234. { EBML_ID_VOID, EBML_NONE },
  235. { 0 }
  236. };
  237. static EbmlSyntax matroska_track_encoding_compression[] = {
  238. { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
  239. { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
  240. { EBML_ID_VOID, EBML_NONE },
  241. { 0 }
  242. };
  243. static EbmlSyntax matroska_track_encoding[] = {
  244. { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
  245. { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
  246. { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
  247. { EBML_ID_VOID, EBML_NONE },
  248. { 0 }
  249. };
  250. static EbmlSyntax matroska_track_encodings[] = {
  251. { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
  252. { EBML_ID_VOID, EBML_NONE },
  253. { 0 }
  254. };
  255. static EbmlSyntax matroska_track[] = {
  256. { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
  257. { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
  258. { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
  259. { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
  260. { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
  261. { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
  262. { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
  263. { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
  264. { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
  265. { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
  266. { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
  267. { MATROSKA_ID_TRACKUID, EBML_NONE },
  268. { MATROSKA_ID_TRACKNAME, EBML_NONE },
  269. { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
  270. { MATROSKA_ID_TRACKFLAGFORCED, EBML_NONE },
  271. { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
  272. { MATROSKA_ID_CODECNAME, EBML_NONE },
  273. { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
  274. { MATROSKA_ID_CODECINFOURL, EBML_NONE },
  275. { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
  276. { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
  277. { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
  278. { EBML_ID_VOID, EBML_NONE },
  279. { 0 }
  280. };
  281. static EbmlSyntax matroska_tracks[] = {
  282. { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
  283. { EBML_ID_VOID, EBML_NONE },
  284. { 0 }
  285. };
  286. static EbmlSyntax matroska_attachment[] = {
  287. { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
  288. { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
  289. { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
  290. { MATROSKA_ID_FILEUID, EBML_NONE },
  291. { EBML_ID_VOID, EBML_NONE },
  292. { 0 }
  293. };
  294. static EbmlSyntax matroska_attachments[] = {
  295. { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
  296. { EBML_ID_VOID, EBML_NONE },
  297. { 0 }
  298. };
  299. static EbmlSyntax matroska_chapter_display[] = {
  300. { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
  301. { EBML_ID_VOID, EBML_NONE },
  302. { 0 }
  303. };
  304. static EbmlSyntax matroska_chapter_entry[] = {
  305. { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
  306. { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
  307. { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
  308. { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
  309. { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
  310. { EBML_ID_VOID, EBML_NONE },
  311. { 0 }
  312. };
  313. static EbmlSyntax matroska_chapter[] = {
  314. { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
  315. { MATROSKA_ID_EDITIONUID, EBML_NONE },
  316. { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
  317. { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  318. { EBML_ID_VOID, EBML_NONE },
  319. { 0 }
  320. };
  321. static EbmlSyntax matroska_chapters[] = {
  322. { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
  323. { EBML_ID_VOID, EBML_NONE },
  324. { 0 }
  325. };
  326. static EbmlSyntax matroska_index_pos[] = {
  327. { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
  328. { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
  329. { EBML_ID_VOID, EBML_NONE },
  330. { 0 }
  331. };
  332. static EbmlSyntax matroska_index_entry[] = {
  333. { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
  334. { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
  335. { EBML_ID_VOID, EBML_NONE },
  336. { 0 }
  337. };
  338. static EbmlSyntax matroska_index[] = {
  339. { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
  340. { EBML_ID_VOID, EBML_NONE },
  341. { 0 }
  342. };
  343. static EbmlSyntax matroska_tags[] = {
  344. { EBML_ID_VOID, EBML_NONE },
  345. { 0 }
  346. };
  347. static EbmlSyntax matroska_seekhead_entry[] = {
  348. { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
  349. { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
  350. { EBML_ID_VOID, EBML_NONE },
  351. { 0 }
  352. };
  353. static EbmlSyntax matroska_seekhead[] = {
  354. { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
  355. { EBML_ID_VOID, EBML_NONE },
  356. { 0 }
  357. };
  358. static EbmlSyntax matroska_segment[] = {
  359. { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
  360. { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
  361. { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
  362. { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
  363. { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
  364. { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
  365. { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
  366. { MATROSKA_ID_CLUSTER, EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
  367. { EBML_ID_VOID, EBML_NONE },
  368. { 0 }
  369. };
  370. static EbmlSyntax matroska_segments[] = {
  371. { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
  372. { 0 }
  373. };
  374. static EbmlSyntax matroska_blockgroup[] = {
  375. { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  376. { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  377. { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
  378. { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
  379. { EBML_ID_VOID, EBML_NONE },
  380. { 0 }
  381. };
  382. static EbmlSyntax matroska_cluster[] = {
  383. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  384. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  385. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  386. { EBML_ID_VOID, EBML_NONE },
  387. { 0 }
  388. };
  389. static EbmlSyntax matroska_clusters[] = {
  390. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
  391. { 0 }
  392. };
  393. /*
  394. * Return: Whether we reached the end of a level in the hierarchy or not.
  395. */
  396. static int ebml_level_end(MatroskaDemuxContext *matroska)
  397. {
  398. ByteIOContext *pb = matroska->ctx->pb;
  399. offset_t pos = url_ftell(pb);
  400. if (matroska->num_levels > 0) {
  401. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  402. if (pos - level->start >= level->length) {
  403. matroska->num_levels--;
  404. return 1;
  405. }
  406. }
  407. return 0;
  408. }
  409. /*
  410. * Read: an "EBML number", which is defined as a variable-length
  411. * array of bytes. The first byte indicates the length by giving a
  412. * number of 0-bits followed by a one. The position of the first
  413. * "one" bit inside the first byte indicates the length of this
  414. * number.
  415. * Returns: number of bytes read, < 0 on error
  416. */
  417. static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
  418. int max_size, uint64_t *number)
  419. {
  420. int len_mask = 0x80, read = 1, n = 1;
  421. int64_t total = 0;
  422. /* The first byte tells us the length in bytes - get_byte() can normally
  423. * return 0, but since that's not a valid first ebmlID byte, we can
  424. * use it safely here to catch EOS. */
  425. if (!(total = get_byte(pb))) {
  426. /* we might encounter EOS here */
  427. if (!url_feof(pb)) {
  428. offset_t pos = url_ftell(pb);
  429. av_log(matroska->ctx, AV_LOG_ERROR,
  430. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  431. pos, pos);
  432. }
  433. return AVERROR(EIO); /* EOS or actual I/O error */
  434. }
  435. /* get the length of the EBML number */
  436. while (read <= max_size && !(total & len_mask)) {
  437. read++;
  438. len_mask >>= 1;
  439. }
  440. if (read > max_size) {
  441. offset_t pos = url_ftell(pb) - 1;
  442. av_log(matroska->ctx, AV_LOG_ERROR,
  443. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  444. (uint8_t) total, pos, pos);
  445. return AVERROR_INVALIDDATA;
  446. }
  447. /* read out length */
  448. total &= ~len_mask;
  449. while (n++ < read)
  450. total = (total << 8) | get_byte(pb);
  451. *number = total;
  452. return read;
  453. }
  454. /*
  455. * Read the next element as an unsigned int.
  456. * 0 is success, < 0 is failure.
  457. */
  458. static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
  459. {
  460. int n = 0;
  461. if (size < 1 || size > 8)
  462. return AVERROR_INVALIDDATA;
  463. /* big-endian ordering; build up number */
  464. *num = 0;
  465. while (n++ < size)
  466. *num = (*num << 8) | get_byte(pb);
  467. return 0;
  468. }
  469. /*
  470. * Read the next element as a float.
  471. * 0 is success, < 0 is failure.
  472. */
  473. static int ebml_read_float(ByteIOContext *pb, int size, double *num)
  474. {
  475. if (size == 4) {
  476. *num= av_int2flt(get_be32(pb));
  477. } else if(size==8){
  478. *num= av_int2dbl(get_be64(pb));
  479. } else
  480. return AVERROR_INVALIDDATA;
  481. return 0;
  482. }
  483. /*
  484. * Read the next element as an ASCII string.
  485. * 0 is success, < 0 is failure.
  486. */
  487. static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
  488. {
  489. av_free(*str);
  490. /* EBML strings are usually not 0-terminated, so we allocate one
  491. * byte more, read the string and NULL-terminate it ourselves. */
  492. if (!(*str = av_malloc(size + 1)))
  493. return AVERROR(ENOMEM);
  494. if (get_buffer(pb, (uint8_t *) *str, size) != size) {
  495. av_free(*str);
  496. return AVERROR(EIO);
  497. }
  498. (*str)[size] = '\0';
  499. return 0;
  500. }
  501. /*
  502. * Read the next element as binary data.
  503. * 0 is success, < 0 is failure.
  504. */
  505. static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
  506. {
  507. av_free(bin->data);
  508. if (!(bin->data = av_malloc(length)))
  509. return AVERROR(ENOMEM);
  510. bin->size = length;
  511. bin->pos = url_ftell(pb);
  512. if (get_buffer(pb, bin->data, length) != length)
  513. return AVERROR(EIO);
  514. return 0;
  515. }
  516. /*
  517. * Read the next element, but only the header. The contents
  518. * are supposed to be sub-elements which can be read separately.
  519. * 0 is success, < 0 is failure.
  520. */
  521. static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
  522. {
  523. ByteIOContext *pb = matroska->ctx->pb;
  524. MatroskaLevel *level;
  525. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  526. av_log(matroska->ctx, AV_LOG_ERROR,
  527. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  528. return AVERROR(ENOSYS);
  529. }
  530. level = &matroska->levels[matroska->num_levels++];
  531. level->start = url_ftell(pb);
  532. level->length = length;
  533. return 0;
  534. }
  535. /*
  536. * Read signed/unsigned "EBML" numbers.
  537. * Return: number of bytes processed, < 0 on error
  538. */
  539. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  540. uint8_t *data, uint32_t size, uint64_t *num)
  541. {
  542. ByteIOContext pb;
  543. init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  544. return ebml_read_num(matroska, &pb, 8, num);
  545. }
  546. /*
  547. * Same as above, but signed.
  548. */
  549. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  550. uint8_t *data, uint32_t size, int64_t *num)
  551. {
  552. uint64_t unum;
  553. int res;
  554. /* read as unsigned number first */
  555. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  556. return res;
  557. /* make signed (weird way) */
  558. *num = unum - ((1LL << (7*res - 1)) - 1);
  559. return res;
  560. }
  561. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  562. EbmlSyntax *syntax, void *data);
  563. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  564. uint32_t id, void *data)
  565. {
  566. int i;
  567. for (i=0; syntax[i].id; i++)
  568. if (id == syntax[i].id)
  569. break;
  570. if (!syntax[i].id)
  571. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  572. return ebml_parse_elem(matroska, &syntax[i], data);
  573. }
  574. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  575. void *data)
  576. {
  577. uint64_t id;
  578. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  579. id |= 1 << 7*res;
  580. return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
  581. }
  582. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  583. void *data)
  584. {
  585. int i, res = 0;
  586. for (i=0; syntax[i].id; i++)
  587. switch (syntax[i].type) {
  588. case EBML_UINT:
  589. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  590. break;
  591. case EBML_FLOAT:
  592. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  593. break;
  594. case EBML_STR:
  595. case EBML_UTF8:
  596. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  597. break;
  598. }
  599. while (!res && !ebml_level_end(matroska))
  600. res = ebml_parse(matroska, syntax, data);
  601. return res;
  602. }
  603. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  604. EbmlSyntax *syntax, void *data)
  605. {
  606. ByteIOContext *pb = matroska->ctx->pb;
  607. uint32_t id = syntax->id;
  608. uint64_t length;
  609. int res;
  610. data = (char *)data + syntax->data_offset;
  611. if (syntax->list_elem_size) {
  612. EbmlList *list = data;
  613. list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  614. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  615. memset(data, 0, syntax->list_elem_size);
  616. list->nb_elem++;
  617. }
  618. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
  619. if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
  620. return res;
  621. switch (syntax->type) {
  622. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  623. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  624. case EBML_STR:
  625. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  626. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  627. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  628. return res;
  629. if (id == MATROSKA_ID_SEGMENT)
  630. matroska->segment_start = url_ftell(matroska->ctx->pb);
  631. return ebml_parse_nest(matroska, syntax->def.n, data);
  632. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  633. case EBML_STOP: *(int *)data = 1; return 1;
  634. default: url_fskip(pb, length); return 0;
  635. }
  636. if (res == AVERROR_INVALIDDATA)
  637. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  638. else if (res == AVERROR(EIO))
  639. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  640. return res;
  641. }
  642. static void ebml_free(EbmlSyntax *syntax, void *data)
  643. {
  644. int i, j;
  645. for (i=0; syntax[i].id; i++) {
  646. void *data_off = (char *)data + syntax[i].data_offset;
  647. switch (syntax[i].type) {
  648. case EBML_STR:
  649. case EBML_UTF8: av_freep(data_off); break;
  650. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  651. case EBML_NEST:
  652. if (syntax[i].list_elem_size) {
  653. EbmlList *list = data_off;
  654. char *ptr = list->elem;
  655. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  656. ebml_free(syntax[i].def.n, ptr);
  657. av_free(list->elem);
  658. } else
  659. ebml_free(syntax[i].def.n, data_off);
  660. default: break;
  661. }
  662. }
  663. }
  664. /*
  665. * Autodetecting...
  666. */
  667. static int matroska_probe(AVProbeData *p)
  668. {
  669. uint64_t total = 0;
  670. int len_mask = 0x80, size = 1, n = 1;
  671. char probe_data[] = "matroska";
  672. /* EBML header? */
  673. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  674. return 0;
  675. /* length of header */
  676. total = p->buf[4];
  677. while (size <= 8 && !(total & len_mask)) {
  678. size++;
  679. len_mask >>= 1;
  680. }
  681. if (size > 8)
  682. return 0;
  683. total &= (len_mask - 1);
  684. while (n < size)
  685. total = (total << 8) | p->buf[4 + n++];
  686. /* Does the probe data contain the whole header? */
  687. if (p->buf_size < 4 + size + total)
  688. return 0;
  689. /* The header must contain the document type 'matroska'. For now,
  690. * we don't parse the whole header but simply check for the
  691. * availability of that array of characters inside the header.
  692. * Not fully fool-proof, but good enough. */
  693. for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
  694. if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
  695. return AVPROBE_SCORE_MAX;
  696. return 0;
  697. }
  698. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  699. int num)
  700. {
  701. MatroskaTrack *tracks = matroska->tracks.elem;
  702. int i;
  703. for (i=0; i < matroska->tracks.nb_elem; i++)
  704. if (tracks[i].num == num)
  705. return &tracks[i];
  706. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  707. return NULL;
  708. }
  709. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  710. MatroskaTrack *track)
  711. {
  712. MatroskaTrackEncoding *encodings = track->encodings.elem;
  713. uint8_t* data = *buf;
  714. int isize = *buf_size;
  715. uint8_t* pkt_data = NULL;
  716. int pkt_size = isize;
  717. int result = 0;
  718. int olen;
  719. switch (encodings[0].compression.algo) {
  720. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  721. return encodings[0].compression.settings.size;
  722. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  723. do {
  724. olen = pkt_size *= 3;
  725. pkt_data = av_realloc(pkt_data,
  726. pkt_size+LZO_OUTPUT_PADDING);
  727. result = lzo1x_decode(pkt_data, &olen, data, &isize);
  728. } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
  729. if (result)
  730. goto failed;
  731. pkt_size -= olen;
  732. break;
  733. #ifdef CONFIG_ZLIB
  734. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  735. z_stream zstream = {0};
  736. if (inflateInit(&zstream) != Z_OK)
  737. return -1;
  738. zstream.next_in = data;
  739. zstream.avail_in = isize;
  740. do {
  741. pkt_size *= 3;
  742. pkt_data = av_realloc(pkt_data, pkt_size);
  743. zstream.avail_out = pkt_size - zstream.total_out;
  744. zstream.next_out = pkt_data + zstream.total_out;
  745. result = inflate(&zstream, Z_NO_FLUSH);
  746. } while (result==Z_OK && pkt_size<10000000);
  747. pkt_size = zstream.total_out;
  748. inflateEnd(&zstream);
  749. if (result != Z_STREAM_END)
  750. goto failed;
  751. break;
  752. }
  753. #endif
  754. #ifdef CONFIG_BZLIB
  755. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  756. bz_stream bzstream = {0};
  757. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  758. return -1;
  759. bzstream.next_in = data;
  760. bzstream.avail_in = isize;
  761. do {
  762. pkt_size *= 3;
  763. pkt_data = av_realloc(pkt_data, pkt_size);
  764. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  765. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  766. result = BZ2_bzDecompress(&bzstream);
  767. } while (result==BZ_OK && pkt_size<10000000);
  768. pkt_size = bzstream.total_out_lo32;
  769. BZ2_bzDecompressEnd(&bzstream);
  770. if (result != BZ_STREAM_END)
  771. goto failed;
  772. break;
  773. }
  774. #endif
  775. }
  776. *buf = pkt_data;
  777. *buf_size = pkt_size;
  778. return 0;
  779. failed:
  780. av_free(pkt_data);
  781. return -1;
  782. }
  783. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  784. {
  785. EbmlList *seekhead_list = &matroska->seekhead;
  786. MatroskaSeekhead *seekhead = seekhead_list->elem;
  787. uint32_t level_up = matroska->level_up;
  788. offset_t before_pos = url_ftell(matroska->ctx->pb);
  789. MatroskaLevel level;
  790. int i;
  791. for (i=0; i<seekhead_list->nb_elem; i++) {
  792. offset_t offset = seekhead[i].pos + matroska->segment_start;
  793. if (seekhead[i].pos <= before_pos
  794. || seekhead[i].id == MATROSKA_ID_SEEKHEAD
  795. || seekhead[i].id == MATROSKA_ID_CLUSTER)
  796. continue;
  797. /* seek */
  798. if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
  799. continue;
  800. /* We don't want to lose our seekhead level, so we add
  801. * a dummy. This is a crude hack. */
  802. if (matroska->num_levels == EBML_MAX_DEPTH) {
  803. av_log(matroska->ctx, AV_LOG_INFO,
  804. "Max EBML element depth (%d) reached, "
  805. "cannot parse further.\n", EBML_MAX_DEPTH);
  806. break;
  807. }
  808. level.start = 0;
  809. level.length = (uint64_t)-1;
  810. matroska->levels[matroska->num_levels] = level;
  811. matroska->num_levels++;
  812. ebml_parse(matroska, matroska_segment, matroska);
  813. /* remove dummy level */
  814. while (matroska->num_levels) {
  815. uint64_t length = matroska->levels[--matroska->num_levels].length;
  816. if (length == (uint64_t)-1)
  817. break;
  818. }
  819. }
  820. /* seek back */
  821. url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
  822. matroska->level_up = level_up;
  823. }
  824. static int matroska_aac_profile(char *codec_id)
  825. {
  826. static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
  827. int profile;
  828. for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
  829. if (strstr(codec_id, aac_profiles[profile]))
  830. break;
  831. return profile + 1;
  832. }
  833. static int matroska_aac_sri(int samplerate)
  834. {
  835. int sri;
  836. for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
  837. if (ff_mpeg4audio_sample_rates[sri] == samplerate)
  838. break;
  839. return sri;
  840. }
  841. static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
  842. {
  843. MatroskaDemuxContext *matroska = s->priv_data;
  844. EbmlList *attachements_list = &matroska->attachments;
  845. MatroskaAttachement *attachements;
  846. EbmlList *chapters_list = &matroska->chapters;
  847. MatroskaChapter *chapters;
  848. MatroskaTrack *tracks;
  849. EbmlList *index_list;
  850. MatroskaIndex *index;
  851. Ebml ebml = { 0 };
  852. AVStream *st;
  853. int i, j;
  854. matroska->ctx = s;
  855. /* First read the EBML header. */
  856. if (ebml_parse(matroska, ebml_syntax, &ebml)
  857. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  858. || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
  859. || ebml.doctype_version > 2) {
  860. av_log(matroska->ctx, AV_LOG_ERROR,
  861. "EBML header using unsupported features\n"
  862. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  863. ebml.version, ebml.doctype, ebml.doctype_version);
  864. return AVERROR_NOFMT;
  865. }
  866. ebml_free(ebml_syntax, &ebml);
  867. /* The next thing is a segment. */
  868. if (ebml_parse(matroska, matroska_segments, matroska) < 0)
  869. return -1;
  870. matroska_execute_seekhead(matroska);
  871. if (matroska->duration)
  872. matroska->ctx->duration = matroska->duration * matroska->time_scale
  873. * 1000 / AV_TIME_BASE;
  874. if (matroska->title)
  875. strncpy(matroska->ctx->title, matroska->title,
  876. sizeof(matroska->ctx->title)-1);
  877. tracks = matroska->tracks.elem;
  878. for (i=0; i < matroska->tracks.nb_elem; i++) {
  879. MatroskaTrack *track = &tracks[i];
  880. enum CodecID codec_id = CODEC_ID_NONE;
  881. EbmlList *encodings_list = &tracks->encodings;
  882. MatroskaTrackEncoding *encodings = encodings_list->elem;
  883. uint8_t *extradata = NULL;
  884. int extradata_size = 0;
  885. int extradata_offset = 0;
  886. /* Apply some sanity checks. */
  887. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  888. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  889. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  890. av_log(matroska->ctx, AV_LOG_INFO,
  891. "Unknown or unsupported track type %"PRIu64"\n",
  892. track->type);
  893. continue;
  894. }
  895. if (track->codec_id == NULL)
  896. continue;
  897. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  898. if (!track->default_duration)
  899. track->default_duration = 1000000000/track->video.frame_rate;
  900. if (!track->video.display_width)
  901. track->video.display_width = track->video.pixel_width;
  902. if (!track->video.display_height)
  903. track->video.display_height = track->video.pixel_height;
  904. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  905. if (!track->audio.out_samplerate)
  906. track->audio.out_samplerate = track->audio.samplerate;
  907. }
  908. if (encodings_list->nb_elem > 1) {
  909. av_log(matroska->ctx, AV_LOG_ERROR,
  910. "Multiple combined encodings no supported");
  911. } else if (encodings_list->nb_elem == 1) {
  912. if (encodings[0].type ||
  913. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  914. #ifdef CONFIG_ZLIB
  915. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  916. #endif
  917. #ifdef CONFIG_BZLIB
  918. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  919. #endif
  920. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  921. encodings[0].scope = 0;
  922. av_log(matroska->ctx, AV_LOG_ERROR,
  923. "Unsupported encoding type");
  924. } else if (track->codec_priv.size && encodings[0].scope&2) {
  925. uint8_t *codec_priv = track->codec_priv.data;
  926. int offset = matroska_decode_buffer(&track->codec_priv.data,
  927. &track->codec_priv.size,
  928. track);
  929. if (offset < 0) {
  930. track->codec_priv.data = NULL;
  931. track->codec_priv.size = 0;
  932. av_log(matroska->ctx, AV_LOG_ERROR,
  933. "Failed to decode codec private data\n");
  934. } else if (offset > 0) {
  935. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  936. memcpy(track->codec_priv.data,
  937. encodings[0].compression.settings.data, offset);
  938. memcpy(track->codec_priv.data+offset, codec_priv,
  939. track->codec_priv.size);
  940. track->codec_priv.size += offset;
  941. }
  942. if (codec_priv != track->codec_priv.data)
  943. av_free(codec_priv);
  944. }
  945. }
  946. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  947. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  948. strlen(ff_mkv_codec_tags[j].str))){
  949. codec_id= ff_mkv_codec_tags[j].id;
  950. break;
  951. }
  952. }
  953. st = track->stream = av_new_stream(s, 0);
  954. if (st == NULL)
  955. return AVERROR(ENOMEM);
  956. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  957. && track->codec_priv.size >= 40
  958. && track->codec_priv.data != NULL) {
  959. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  960. codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
  961. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  962. && track->codec_priv.size >= 18
  963. && track->codec_priv.data != NULL) {
  964. uint16_t tag = AV_RL16(track->codec_priv.data);
  965. codec_id = codec_get_id(codec_wav_tags, tag);
  966. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  967. && (track->codec_priv.size >= 86)
  968. && (track->codec_priv.data != NULL)) {
  969. track->video.fourcc = AV_RL32(track->codec_priv.data);
  970. codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
  971. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  972. int profile = matroska_aac_profile(track->codec_id);
  973. int sri = matroska_aac_sri(track->audio.samplerate);
  974. extradata = av_malloc(5);
  975. if (extradata == NULL)
  976. return AVERROR(ENOMEM);
  977. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  978. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  979. if (strstr(track->codec_id, "SBR")) {
  980. sri = matroska_aac_sri(track->audio.out_samplerate);
  981. extradata[2] = 0x56;
  982. extradata[3] = 0xE5;
  983. extradata[4] = 0x80 | (sri<<3);
  984. extradata_size = 5;
  985. } else
  986. extradata_size = 2;
  987. } else if (codec_id == CODEC_ID_TTA) {
  988. ByteIOContext b;
  989. extradata_size = 30;
  990. extradata = av_mallocz(extradata_size);
  991. if (extradata == NULL)
  992. return AVERROR(ENOMEM);
  993. init_put_byte(&b, extradata, extradata_size, 1,
  994. NULL, NULL, NULL, NULL);
  995. put_buffer(&b, "TTA1", 4);
  996. put_le16(&b, 1);
  997. put_le16(&b, track->audio.channels);
  998. put_le16(&b, track->audio.bitdepth);
  999. put_le32(&b, track->audio.out_samplerate);
  1000. put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1001. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1002. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1003. extradata_offset = 26;
  1004. track->codec_priv.size -= extradata_offset;
  1005. } else if (codec_id == CODEC_ID_RA_144) {
  1006. track->audio.out_samplerate = 8000;
  1007. track->audio.channels = 1;
  1008. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1009. codec_id == CODEC_ID_ATRAC3) {
  1010. ByteIOContext b;
  1011. init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
  1012. 0, NULL, NULL, NULL, NULL);
  1013. url_fskip(&b, 24);
  1014. track->audio.coded_framesize = get_be32(&b);
  1015. url_fskip(&b, 12);
  1016. track->audio.sub_packet_h = get_be16(&b);
  1017. track->audio.frame_size = get_be16(&b);
  1018. track->audio.sub_packet_size = get_be16(&b);
  1019. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1020. if (codec_id == CODEC_ID_RA_288) {
  1021. st->codec->block_align = track->audio.coded_framesize;
  1022. track->codec_priv.size = 0;
  1023. } else {
  1024. st->codec->block_align = track->audio.sub_packet_size;
  1025. extradata_offset = 78;
  1026. track->codec_priv.size -= extradata_offset;
  1027. }
  1028. }
  1029. if (codec_id == CODEC_ID_NONE)
  1030. av_log(matroska->ctx, AV_LOG_INFO,
  1031. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1032. av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1033. st->codec->codec_id = codec_id;
  1034. st->start_time = 0;
  1035. if (strcmp(track->language, "und"))
  1036. av_strlcpy(st->language, track->language, 4);
  1037. if (track->flag_default)
  1038. st->disposition |= AV_DISPOSITION_DEFAULT;
  1039. if (track->default_duration)
  1040. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1041. track->default_duration, 1000000000, 30000);
  1042. if(extradata){
  1043. st->codec->extradata = extradata;
  1044. st->codec->extradata_size = extradata_size;
  1045. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1046. st->codec->extradata = av_malloc(track->codec_priv.size);
  1047. if(st->codec->extradata == NULL)
  1048. return AVERROR(ENOMEM);
  1049. st->codec->extradata_size = track->codec_priv.size;
  1050. memcpy(st->codec->extradata,
  1051. track->codec_priv.data + extradata_offset,
  1052. track->codec_priv.size);
  1053. }
  1054. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1055. st->codec->codec_type = CODEC_TYPE_VIDEO;
  1056. st->codec->codec_tag = track->video.fourcc;
  1057. st->codec->width = track->video.pixel_width;
  1058. st->codec->height = track->video.pixel_height;
  1059. av_reduce(&st->codec->sample_aspect_ratio.num,
  1060. &st->codec->sample_aspect_ratio.den,
  1061. st->codec->height * track->video.display_width,
  1062. st->codec-> width * track->video.display_height,
  1063. 255);
  1064. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1065. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1066. st->codec->codec_type = CODEC_TYPE_AUDIO;
  1067. st->codec->sample_rate = track->audio.out_samplerate;
  1068. st->codec->channels = track->audio.channels;
  1069. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1070. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  1071. }
  1072. }
  1073. attachements = attachements_list->elem;
  1074. for (j=0; j<attachements_list->nb_elem; j++) {
  1075. if (!(attachements[j].filename && attachements[j].mime &&
  1076. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1077. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1078. } else {
  1079. AVStream *st = av_new_stream(s, 0);
  1080. if (st == NULL)
  1081. break;
  1082. st->filename = av_strdup(attachements[j].filename);
  1083. st->codec->codec_id = CODEC_ID_NONE;
  1084. st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
  1085. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1086. if(st->codec->extradata == NULL)
  1087. break;
  1088. st->codec->extradata_size = attachements[j].bin.size;
  1089. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1090. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1091. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1092. strlen(ff_mkv_mime_tags[i].str))) {
  1093. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1094. break;
  1095. }
  1096. }
  1097. }
  1098. }
  1099. chapters = chapters_list->elem;
  1100. for (i=0; i<chapters_list->nb_elem; i++)
  1101. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
  1102. ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1103. chapters[i].start, chapters[i].end,
  1104. chapters[i].title);
  1105. index_list = &matroska->index;
  1106. index = index_list->elem;
  1107. for (i=0; i<index_list->nb_elem; i++) {
  1108. EbmlList *pos_list = &index[i].pos;
  1109. MatroskaIndexPos *pos = pos_list->elem;
  1110. for (j=0; j<pos_list->nb_elem; j++) {
  1111. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1112. pos[j].track);
  1113. if (track && track->stream)
  1114. av_add_index_entry(track->stream,
  1115. pos[j].pos + matroska->segment_start,
  1116. index[i].time*matroska->time_scale/AV_TIME_BASE,
  1117. 0, 0, AVINDEX_KEYFRAME);
  1118. }
  1119. }
  1120. return 0;
  1121. }
  1122. /*
  1123. * Put one packet in an application-supplied AVPacket struct.
  1124. * Returns 0 on success or -1 on failure.
  1125. */
  1126. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1127. AVPacket *pkt)
  1128. {
  1129. if (matroska->num_packets > 0) {
  1130. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1131. av_free(matroska->packets[0]);
  1132. if (matroska->num_packets > 1) {
  1133. memmove(&matroska->packets[0], &matroska->packets[1],
  1134. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1135. matroska->packets =
  1136. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  1137. sizeof(AVPacket *));
  1138. } else {
  1139. av_freep(&matroska->packets);
  1140. }
  1141. matroska->num_packets--;
  1142. return 0;
  1143. }
  1144. return -1;
  1145. }
  1146. /*
  1147. * Free all packets in our internal queue.
  1148. */
  1149. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1150. {
  1151. if (matroska->packets) {
  1152. int n;
  1153. for (n = 0; n < matroska->num_packets; n++) {
  1154. av_free_packet(matroska->packets[n]);
  1155. av_free(matroska->packets[n]);
  1156. }
  1157. av_freep(&matroska->packets);
  1158. matroska->num_packets = 0;
  1159. }
  1160. }
  1161. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1162. int size, int64_t pos, uint64_t cluster_time,
  1163. uint64_t duration, int is_keyframe)
  1164. {
  1165. MatroskaTrack *track;
  1166. int res = 0;
  1167. AVStream *st;
  1168. AVPacket *pkt;
  1169. int16_t block_time;
  1170. uint32_t *lace_size = NULL;
  1171. int n, flags, laces = 0;
  1172. uint64_t num;
  1173. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1174. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1175. return res;
  1176. }
  1177. data += n;
  1178. size -= n;
  1179. track = matroska_find_track_by_num(matroska, num);
  1180. if (size <= 3 || !track || !track->stream) {
  1181. av_log(matroska->ctx, AV_LOG_INFO,
  1182. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1183. return res;
  1184. }
  1185. st = track->stream;
  1186. if (st->discard >= AVDISCARD_ALL)
  1187. return res;
  1188. if (duration == AV_NOPTS_VALUE)
  1189. duration = track->default_duration / matroska->time_scale;
  1190. block_time = AV_RB16(data);
  1191. data += 2;
  1192. flags = *data++;
  1193. size -= 3;
  1194. if (is_keyframe == -1)
  1195. is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
  1196. if (matroska->skip_to_keyframe) {
  1197. if (!is_keyframe || st != matroska->skip_to_stream)
  1198. return res;
  1199. matroska->skip_to_keyframe = 0;
  1200. }
  1201. switch ((flags & 0x06) >> 1) {
  1202. case 0x0: /* no lacing */
  1203. laces = 1;
  1204. lace_size = av_mallocz(sizeof(int));
  1205. lace_size[0] = size;
  1206. break;
  1207. case 0x1: /* Xiph lacing */
  1208. case 0x2: /* fixed-size lacing */
  1209. case 0x3: /* EBML lacing */
  1210. assert(size>0); // size <=3 is checked before size-=3 above
  1211. laces = (*data) + 1;
  1212. data += 1;
  1213. size -= 1;
  1214. lace_size = av_mallocz(laces * sizeof(int));
  1215. switch ((flags & 0x06) >> 1) {
  1216. case 0x1: /* Xiph lacing */ {
  1217. uint8_t temp;
  1218. uint32_t total = 0;
  1219. for (n = 0; res == 0 && n < laces - 1; n++) {
  1220. while (1) {
  1221. if (size == 0) {
  1222. res = -1;
  1223. break;
  1224. }
  1225. temp = *data;
  1226. lace_size[n] += temp;
  1227. data += 1;
  1228. size -= 1;
  1229. if (temp != 0xff)
  1230. break;
  1231. }
  1232. total += lace_size[n];
  1233. }
  1234. lace_size[n] = size - total;
  1235. break;
  1236. }
  1237. case 0x2: /* fixed-size lacing */
  1238. for (n = 0; n < laces; n++)
  1239. lace_size[n] = size / laces;
  1240. break;
  1241. case 0x3: /* EBML lacing */ {
  1242. uint32_t total;
  1243. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1244. if (n < 0) {
  1245. av_log(matroska->ctx, AV_LOG_INFO,
  1246. "EBML block data error\n");
  1247. break;
  1248. }
  1249. data += n;
  1250. size -= n;
  1251. total = lace_size[0] = num;
  1252. for (n = 1; res == 0 && n < laces - 1; n++) {
  1253. int64_t snum;
  1254. int r;
  1255. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1256. if (r < 0) {
  1257. av_log(matroska->ctx, AV_LOG_INFO,
  1258. "EBML block data error\n");
  1259. break;
  1260. }
  1261. data += r;
  1262. size -= r;
  1263. lace_size[n] = lace_size[n - 1] + snum;
  1264. total += lace_size[n];
  1265. }
  1266. lace_size[n] = size - total;
  1267. break;
  1268. }
  1269. }
  1270. break;
  1271. }
  1272. if (res == 0) {
  1273. uint64_t timecode = AV_NOPTS_VALUE;
  1274. if (cluster_time != (uint64_t)-1
  1275. && (block_time >= 0 || cluster_time >= -block_time))
  1276. timecode = cluster_time + block_time;
  1277. for (n = 0; n < laces; n++) {
  1278. if (st->codec->codec_id == CODEC_ID_RA_288 ||
  1279. st->codec->codec_id == CODEC_ID_COOK ||
  1280. st->codec->codec_id == CODEC_ID_ATRAC3) {
  1281. int a = st->codec->block_align;
  1282. int sps = track->audio.sub_packet_size;
  1283. int cfs = track->audio.coded_framesize;
  1284. int h = track->audio.sub_packet_h;
  1285. int y = track->audio.sub_packet_cnt;
  1286. int w = track->audio.frame_size;
  1287. int x;
  1288. if (!track->audio.pkt_cnt) {
  1289. if (st->codec->codec_id == CODEC_ID_RA_288)
  1290. for (x=0; x<h/2; x++)
  1291. memcpy(track->audio.buf+x*2*w+y*cfs,
  1292. data+x*cfs, cfs);
  1293. else
  1294. for (x=0; x<w/sps; x++)
  1295. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1296. if (++track->audio.sub_packet_cnt >= h) {
  1297. track->audio.sub_packet_cnt = 0;
  1298. track->audio.pkt_cnt = h*w / a;
  1299. }
  1300. }
  1301. while (track->audio.pkt_cnt) {
  1302. pkt = av_mallocz(sizeof(AVPacket));
  1303. av_new_packet(pkt, a);
  1304. memcpy(pkt->data, track->audio.buf
  1305. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1306. pkt->pos = pos;
  1307. pkt->stream_index = st->index;
  1308. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1309. }
  1310. } else {
  1311. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1312. int offset = 0, pkt_size = lace_size[n];
  1313. uint8_t *pkt_data = data;
  1314. if (encodings && encodings->scope & 1) {
  1315. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1316. if (offset < 0)
  1317. continue;
  1318. }
  1319. pkt = av_mallocz(sizeof(AVPacket));
  1320. /* XXX: prevent data copy... */
  1321. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1322. av_free(pkt);
  1323. res = AVERROR(ENOMEM);
  1324. n = laces-1;
  1325. break;
  1326. }
  1327. if (offset)
  1328. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1329. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1330. if (pkt_data != data)
  1331. av_free(pkt_data);
  1332. if (n == 0)
  1333. pkt->flags = is_keyframe;
  1334. pkt->stream_index = st->index;
  1335. pkt->pts = timecode;
  1336. pkt->pos = pos;
  1337. pkt->duration = duration;
  1338. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  1339. }
  1340. if (timecode != AV_NOPTS_VALUE)
  1341. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1342. data += lace_size[n];
  1343. }
  1344. }
  1345. av_free(lace_size);
  1346. return res;
  1347. }
  1348. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1349. {
  1350. MatroskaCluster cluster = { 0 };
  1351. EbmlList *blocks_list;
  1352. MatroskaBlock *blocks;
  1353. int i, res;
  1354. if (matroska->has_cluster_id){
  1355. /* For the first cluster we parse, its ID was already read as
  1356. part of matroska_read_header(), so don't read it again */
  1357. res = ebml_parse_id(matroska, matroska_clusters,
  1358. MATROSKA_ID_CLUSTER, &cluster);
  1359. matroska->has_cluster_id = 0;
  1360. } else
  1361. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1362. blocks_list = &cluster.blocks;
  1363. blocks = blocks_list->elem;
  1364. for (i=0; !res && i<blocks_list->nb_elem; i++)
  1365. if (blocks[i].bin.size > 0)
  1366. res=matroska_parse_block(matroska,
  1367. blocks[i].bin.data, blocks[i].bin.size,
  1368. blocks[i].bin.pos, cluster.timecode,
  1369. blocks[i].duration, !blocks[i].reference);
  1370. ebml_free(matroska_cluster, &cluster);
  1371. return res;
  1372. }
  1373. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1374. {
  1375. MatroskaDemuxContext *matroska = s->priv_data;
  1376. while (matroska_deliver_packet(matroska, pkt)) {
  1377. if (matroska->done)
  1378. return AVERROR(EIO);
  1379. if (matroska_parse_cluster(matroska) < 0)
  1380. matroska->done = 1;
  1381. }
  1382. return 0;
  1383. }
  1384. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1385. int64_t timestamp, int flags)
  1386. {
  1387. MatroskaDemuxContext *matroska = s->priv_data;
  1388. AVStream *st = s->streams[stream_index];
  1389. int index;
  1390. index = av_index_search_timestamp(st, timestamp, flags);
  1391. if (index < 0)
  1392. return 0;
  1393. matroska_clear_queue(matroska);
  1394. url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
  1395. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1396. matroska->skip_to_stream = st;
  1397. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1398. return 0;
  1399. }
  1400. static int matroska_read_close(AVFormatContext *s)
  1401. {
  1402. MatroskaDemuxContext *matroska = s->priv_data;
  1403. MatroskaTrack *tracks = matroska->tracks.elem;
  1404. int n;
  1405. matroska_clear_queue(matroska);
  1406. for (n=0; n < matroska->tracks.nb_elem; n++)
  1407. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1408. av_free(tracks[n].audio.buf);
  1409. ebml_free(matroska_segment, matroska);
  1410. return 0;
  1411. }
  1412. AVInputFormat matroska_demuxer = {
  1413. "matroska",
  1414. NULL_IF_CONFIG_SMALL("Matroska file format"),
  1415. sizeof(MatroskaDemuxContext),
  1416. matroska_probe,
  1417. matroska_read_header,
  1418. matroska_read_packet,
  1419. matroska_read_close,
  1420. matroska_read_seek,
  1421. };