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.

1896 lines
68KB

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