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.

2435 lines
84KB

  1. /*
  2. * Matroska file demuxer
  3. * Copyright (c) 2003-2008 The Libav Project
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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. * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
  25. * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
  26. * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
  27. * @see 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. #include "avio_internal.h"
  33. /* For ff_codec_get_id(). */
  34. #include "riff.h"
  35. #include "isom.h"
  36. #include "rmsipr.h"
  37. #include "matroska.h"
  38. #include "libavcodec/bytestream.h"
  39. #include "libavcodec/mpeg4audio.h"
  40. #include "libavutil/intfloat.h"
  41. #include "libavutil/intreadwrite.h"
  42. #include "libavutil/avstring.h"
  43. #include "libavutil/lzo.h"
  44. #include "libavutil/dict.h"
  45. #if CONFIG_ZLIB
  46. #include <zlib.h>
  47. #endif
  48. #if CONFIG_BZLIB
  49. #include <bzlib.h>
  50. #endif
  51. typedef enum {
  52. EBML_NONE,
  53. EBML_UINT,
  54. EBML_FLOAT,
  55. EBML_STR,
  56. EBML_UTF8,
  57. EBML_BIN,
  58. EBML_NEST,
  59. EBML_PASS,
  60. EBML_STOP,
  61. EBML_TYPE_COUNT
  62. } EbmlType;
  63. typedef const struct EbmlSyntax {
  64. uint32_t id;
  65. EbmlType type;
  66. int list_elem_size;
  67. int data_offset;
  68. union {
  69. uint64_t u;
  70. double f;
  71. const char *s;
  72. const struct EbmlSyntax *n;
  73. } def;
  74. } EbmlSyntax;
  75. typedef struct {
  76. int nb_elem;
  77. void *elem;
  78. } EbmlList;
  79. typedef struct {
  80. int size;
  81. uint8_t *data;
  82. int64_t pos;
  83. } EbmlBin;
  84. typedef struct {
  85. uint64_t version;
  86. uint64_t max_size;
  87. uint64_t id_length;
  88. char *doctype;
  89. uint64_t doctype_version;
  90. } Ebml;
  91. typedef struct {
  92. uint64_t algo;
  93. EbmlBin settings;
  94. } MatroskaTrackCompression;
  95. typedef struct {
  96. uint64_t scope;
  97. uint64_t type;
  98. MatroskaTrackCompression compression;
  99. } MatroskaTrackEncoding;
  100. typedef struct {
  101. double frame_rate;
  102. uint64_t display_width;
  103. uint64_t display_height;
  104. uint64_t pixel_width;
  105. uint64_t pixel_height;
  106. uint64_t fourcc;
  107. } MatroskaTrackVideo;
  108. typedef struct {
  109. double samplerate;
  110. double out_samplerate;
  111. uint64_t bitdepth;
  112. uint64_t channels;
  113. /* real audio header (extracted from extradata) */
  114. int coded_framesize;
  115. int sub_packet_h;
  116. int frame_size;
  117. int sub_packet_size;
  118. int sub_packet_cnt;
  119. int pkt_cnt;
  120. uint64_t buf_timecode;
  121. uint8_t *buf;
  122. } MatroskaTrackAudio;
  123. typedef struct {
  124. uint64_t num;
  125. uint64_t uid;
  126. uint64_t type;
  127. char *name;
  128. char *codec_id;
  129. EbmlBin codec_priv;
  130. char *language;
  131. double time_scale;
  132. uint64_t default_duration;
  133. uint64_t flag_default;
  134. uint64_t flag_forced;
  135. MatroskaTrackVideo video;
  136. MatroskaTrackAudio audio;
  137. EbmlList encodings;
  138. AVStream *stream;
  139. int64_t end_timecode;
  140. int ms_compat;
  141. } MatroskaTrack;
  142. typedef struct {
  143. uint64_t uid;
  144. char *filename;
  145. char *mime;
  146. EbmlBin bin;
  147. AVStream *stream;
  148. } MatroskaAttachement;
  149. typedef struct {
  150. uint64_t start;
  151. uint64_t end;
  152. uint64_t uid;
  153. char *title;
  154. AVChapter *chapter;
  155. } MatroskaChapter;
  156. typedef struct {
  157. uint64_t track;
  158. uint64_t pos;
  159. } MatroskaIndexPos;
  160. typedef struct {
  161. uint64_t time;
  162. EbmlList pos;
  163. } MatroskaIndex;
  164. typedef struct {
  165. char *name;
  166. char *string;
  167. char *lang;
  168. uint64_t def;
  169. EbmlList sub;
  170. } MatroskaTag;
  171. typedef struct {
  172. char *type;
  173. uint64_t typevalue;
  174. uint64_t trackuid;
  175. uint64_t chapteruid;
  176. uint64_t attachuid;
  177. } MatroskaTagTarget;
  178. typedef struct {
  179. MatroskaTagTarget target;
  180. EbmlList tag;
  181. } MatroskaTags;
  182. typedef struct {
  183. uint64_t id;
  184. uint64_t pos;
  185. } MatroskaSeekhead;
  186. typedef struct {
  187. uint64_t start;
  188. uint64_t length;
  189. } MatroskaLevel;
  190. typedef struct {
  191. uint64_t timecode;
  192. EbmlList blocks;
  193. } MatroskaCluster;
  194. typedef struct {
  195. AVFormatContext *ctx;
  196. /* EBML stuff */
  197. int num_levels;
  198. MatroskaLevel levels[EBML_MAX_DEPTH];
  199. int level_up;
  200. uint32_t current_id;
  201. uint64_t time_scale;
  202. double duration;
  203. char *title;
  204. EbmlList tracks;
  205. EbmlList attachments;
  206. EbmlList chapters;
  207. EbmlList index;
  208. EbmlList tags;
  209. EbmlList seekhead;
  210. /* byte position of the segment inside the stream */
  211. int64_t segment_start;
  212. /* the packet queue */
  213. AVPacket **packets;
  214. int num_packets;
  215. AVPacket *prev_pkt;
  216. int done;
  217. /* What to skip before effectively reading a packet. */
  218. int skip_to_keyframe;
  219. uint64_t skip_to_timecode;
  220. /* File has a CUES element, but we defer parsing until it is needed. */
  221. int cues_parsing_deferred;
  222. int current_cluster_num_blocks;
  223. int64_t current_cluster_pos;
  224. MatroskaCluster current_cluster;
  225. /* File has SSA subtitles which prevent incremental cluster parsing. */
  226. int contains_ssa;
  227. } MatroskaDemuxContext;
  228. typedef struct {
  229. uint64_t duration;
  230. int64_t reference;
  231. uint64_t non_simple;
  232. EbmlBin bin;
  233. } MatroskaBlock;
  234. static EbmlSyntax ebml_header[] = {
  235. { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
  236. { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
  237. { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
  238. { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
  239. { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
  240. { EBML_ID_EBMLVERSION, EBML_NONE },
  241. { EBML_ID_DOCTYPEVERSION, EBML_NONE },
  242. { 0 }
  243. };
  244. static EbmlSyntax ebml_syntax[] = {
  245. { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
  246. { 0 }
  247. };
  248. static EbmlSyntax matroska_info[] = {
  249. { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
  250. { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
  251. { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
  252. { MATROSKA_ID_WRITINGAPP, EBML_NONE },
  253. { MATROSKA_ID_MUXINGAPP, EBML_NONE },
  254. { MATROSKA_ID_DATEUTC, EBML_NONE },
  255. { MATROSKA_ID_SEGMENTUID, EBML_NONE },
  256. { 0 }
  257. };
  258. static EbmlSyntax matroska_track_video[] = {
  259. { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
  260. { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
  261. { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
  262. { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
  263. { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
  264. { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
  265. { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
  266. { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
  267. { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
  268. { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
  269. { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
  270. { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
  271. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
  272. { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
  273. { 0 }
  274. };
  275. static EbmlSyntax matroska_track_audio[] = {
  276. { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
  277. { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
  278. { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
  279. { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
  280. { 0 }
  281. };
  282. static EbmlSyntax matroska_track_encoding_compression[] = {
  283. { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
  284. { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
  285. { 0 }
  286. };
  287. static EbmlSyntax matroska_track_encoding[] = {
  288. { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
  289. { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
  290. { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
  291. { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
  292. { 0 }
  293. };
  294. static EbmlSyntax matroska_track_encodings[] = {
  295. { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
  296. { 0 }
  297. };
  298. static EbmlSyntax matroska_track[] = {
  299. { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
  300. { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
  301. { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
  302. { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
  303. { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
  304. { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
  305. { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
  306. { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
  307. { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
  308. { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
  309. { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
  310. { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
  311. { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
  312. { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
  313. { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
  314. { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
  315. { MATROSKA_ID_CODECNAME, EBML_NONE },
  316. { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
  317. { MATROSKA_ID_CODECINFOURL, EBML_NONE },
  318. { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
  319. { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
  320. { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
  321. { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
  322. { 0 }
  323. };
  324. static EbmlSyntax matroska_tracks[] = {
  325. { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
  326. { 0 }
  327. };
  328. static EbmlSyntax matroska_attachment[] = {
  329. { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
  330. { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
  331. { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
  332. { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
  333. { MATROSKA_ID_FILEDESC, EBML_NONE },
  334. { 0 }
  335. };
  336. static EbmlSyntax matroska_attachments[] = {
  337. { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
  338. { 0 }
  339. };
  340. static EbmlSyntax matroska_chapter_display[] = {
  341. { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
  342. { MATROSKA_ID_CHAPLANG, EBML_NONE },
  343. { 0 }
  344. };
  345. static EbmlSyntax matroska_chapter_entry[] = {
  346. { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
  347. { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
  348. { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
  349. { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
  350. { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
  351. { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
  352. { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
  353. { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
  354. { 0 }
  355. };
  356. static EbmlSyntax matroska_chapter[] = {
  357. { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
  358. { MATROSKA_ID_EDITIONUID, EBML_NONE },
  359. { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
  360. { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  361. { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
  362. { 0 }
  363. };
  364. static EbmlSyntax matroska_chapters[] = {
  365. { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
  366. { 0 }
  367. };
  368. static EbmlSyntax matroska_index_pos[] = {
  369. { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
  370. { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
  371. { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
  372. { 0 }
  373. };
  374. static EbmlSyntax matroska_index_entry[] = {
  375. { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
  376. { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
  377. { 0 }
  378. };
  379. static EbmlSyntax matroska_index[] = {
  380. { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
  381. { 0 }
  382. };
  383. static EbmlSyntax matroska_simpletag[] = {
  384. { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
  385. { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
  386. { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
  387. { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  388. { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  389. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
  390. { 0 }
  391. };
  392. static EbmlSyntax matroska_tagtargets[] = {
  393. { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
  394. { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
  395. { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
  396. { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
  397. { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
  398. { 0 }
  399. };
  400. static EbmlSyntax matroska_tag[] = {
  401. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
  402. { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
  403. { 0 }
  404. };
  405. static EbmlSyntax matroska_tags[] = {
  406. { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
  407. { 0 }
  408. };
  409. static EbmlSyntax matroska_seekhead_entry[] = {
  410. { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
  411. { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
  412. { 0 }
  413. };
  414. static EbmlSyntax matroska_seekhead[] = {
  415. { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
  416. { 0 }
  417. };
  418. static EbmlSyntax matroska_segment[] = {
  419. { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
  420. { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
  421. { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
  422. { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
  423. { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
  424. { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
  425. { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
  426. { MATROSKA_ID_CLUSTER, EBML_STOP },
  427. { 0 }
  428. };
  429. static EbmlSyntax matroska_segments[] = {
  430. { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
  431. { 0 }
  432. };
  433. static EbmlSyntax matroska_blockgroup[] = {
  434. { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  435. { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  436. { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
  437. { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
  438. { MATROSKA_ID_CODECSTATE, EBML_NONE },
  439. { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
  440. { 0 }
  441. };
  442. static EbmlSyntax matroska_cluster[] = {
  443. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  444. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  445. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  446. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  447. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  448. { 0 }
  449. };
  450. static EbmlSyntax matroska_clusters[] = {
  451. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
  452. { MATROSKA_ID_INFO, EBML_NONE },
  453. { MATROSKA_ID_CUES, EBML_NONE },
  454. { MATROSKA_ID_TAGS, EBML_NONE },
  455. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  456. { 0 }
  457. };
  458. static EbmlSyntax matroska_cluster_incremental_parsing[] = {
  459. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  460. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  461. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  462. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  463. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  464. { MATROSKA_ID_INFO, EBML_NONE },
  465. { MATROSKA_ID_CUES, EBML_NONE },
  466. { MATROSKA_ID_TAGS, EBML_NONE },
  467. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  468. { MATROSKA_ID_CLUSTER, EBML_STOP },
  469. { 0 }
  470. };
  471. static EbmlSyntax matroska_cluster_incremental[] = {
  472. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  473. { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
  474. { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
  475. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  476. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  477. { 0 }
  478. };
  479. static EbmlSyntax matroska_clusters_incremental[] = {
  480. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
  481. { MATROSKA_ID_INFO, EBML_NONE },
  482. { MATROSKA_ID_CUES, EBML_NONE },
  483. { MATROSKA_ID_TAGS, EBML_NONE },
  484. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  485. { 0 }
  486. };
  487. static const char *const matroska_doctypes[] = { "matroska", "webm" };
  488. static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
  489. {
  490. AVIOContext *pb = matroska->ctx->pb;
  491. uint32_t id;
  492. matroska->current_id = 0;
  493. matroska->num_levels = 0;
  494. /* seek to next position to resync from */
  495. if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
  496. goto eof;
  497. id = avio_rb32(pb);
  498. // try to find a toplevel element
  499. while (!pb->eof_reached) {
  500. if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
  501. id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
  502. id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
  503. id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
  504. matroska->current_id = id;
  505. return 0;
  506. }
  507. id = (id << 8) | avio_r8(pb);
  508. }
  509. eof:
  510. matroska->done = 1;
  511. return AVERROR_EOF;
  512. }
  513. /*
  514. * Return: Whether we reached the end of a level in the hierarchy or not.
  515. */
  516. static int ebml_level_end(MatroskaDemuxContext *matroska)
  517. {
  518. AVIOContext *pb = matroska->ctx->pb;
  519. int64_t pos = avio_tell(pb);
  520. if (matroska->num_levels > 0) {
  521. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  522. if (pos - level->start >= level->length || matroska->current_id) {
  523. matroska->num_levels--;
  524. return 1;
  525. }
  526. }
  527. return 0;
  528. }
  529. /*
  530. * Read: an "EBML number", which is defined as a variable-length
  531. * array of bytes. The first byte indicates the length by giving a
  532. * number of 0-bits followed by a one. The position of the first
  533. * "one" bit inside the first byte indicates the length of this
  534. * number.
  535. * Returns: number of bytes read, < 0 on error
  536. */
  537. static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
  538. int max_size, uint64_t *number)
  539. {
  540. int read = 1, n = 1;
  541. uint64_t total = 0;
  542. /* The first byte tells us the length in bytes - avio_r8() can normally
  543. * return 0, but since that's not a valid first ebmlID byte, we can
  544. * use it safely here to catch EOS. */
  545. if (!(total = avio_r8(pb))) {
  546. /* we might encounter EOS here */
  547. if (!pb->eof_reached) {
  548. int64_t pos = avio_tell(pb);
  549. av_log(matroska->ctx, AV_LOG_ERROR,
  550. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  551. pos, pos);
  552. return pb->error ? pb->error : AVERROR(EIO);
  553. }
  554. return AVERROR_EOF;
  555. }
  556. /* get the length of the EBML number */
  557. read = 8 - ff_log2_tab[total];
  558. if (read > max_size) {
  559. int64_t pos = avio_tell(pb) - 1;
  560. av_log(matroska->ctx, AV_LOG_ERROR,
  561. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  562. (uint8_t) total, pos, pos);
  563. return AVERROR_INVALIDDATA;
  564. }
  565. /* read out length */
  566. total ^= 1 << ff_log2_tab[total];
  567. while (n++ < read)
  568. total = (total << 8) | avio_r8(pb);
  569. *number = total;
  570. return read;
  571. }
  572. /**
  573. * Read a EBML length value.
  574. * This needs special handling for the "unknown length" case which has multiple
  575. * encodings.
  576. */
  577. static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
  578. uint64_t *number)
  579. {
  580. int res = ebml_read_num(matroska, pb, 8, number);
  581. if (res > 0 && *number + 1 == 1ULL << (7 * res))
  582. *number = 0xffffffffffffffULL;
  583. return res;
  584. }
  585. /*
  586. * Read the next element as an unsigned int.
  587. * 0 is success, < 0 is failure.
  588. */
  589. static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
  590. {
  591. int n = 0;
  592. if (size > 8)
  593. return AVERROR_INVALIDDATA;
  594. /* big-endian ordering; build up number */
  595. *num = 0;
  596. while (n++ < size)
  597. *num = (*num << 8) | avio_r8(pb);
  598. return 0;
  599. }
  600. /*
  601. * Read the next element as a float.
  602. * 0 is success, < 0 is failure.
  603. */
  604. static int ebml_read_float(AVIOContext *pb, int size, double *num)
  605. {
  606. if (size == 0) {
  607. *num = 0;
  608. } else if (size == 4) {
  609. *num = av_int2float(avio_rb32(pb));
  610. } else if (size == 8){
  611. *num = av_int2double(avio_rb64(pb));
  612. } else
  613. return AVERROR_INVALIDDATA;
  614. return 0;
  615. }
  616. /*
  617. * Read the next element as an ASCII string.
  618. * 0 is success, < 0 is failure.
  619. */
  620. static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
  621. {
  622. char *res;
  623. /* EBML strings are usually not 0-terminated, so we allocate one
  624. * byte more, read the string and NULL-terminate it ourselves. */
  625. if (!(res = av_malloc(size + 1)))
  626. return AVERROR(ENOMEM);
  627. if (avio_read(pb, (uint8_t *) res, size) != size) {
  628. av_free(res);
  629. return AVERROR(EIO);
  630. }
  631. (res)[size] = '\0';
  632. av_free(*str);
  633. *str = res;
  634. return 0;
  635. }
  636. /*
  637. * Read the next element as binary data.
  638. * 0 is success, < 0 is failure.
  639. */
  640. static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  641. {
  642. av_free(bin->data);
  643. if (!(bin->data = av_malloc(length)))
  644. return AVERROR(ENOMEM);
  645. bin->size = length;
  646. bin->pos = avio_tell(pb);
  647. if (avio_read(pb, bin->data, length) != length) {
  648. av_freep(&bin->data);
  649. return AVERROR(EIO);
  650. }
  651. return 0;
  652. }
  653. /*
  654. * Read the next element, but only the header. The contents
  655. * are supposed to be sub-elements which can be read separately.
  656. * 0 is success, < 0 is failure.
  657. */
  658. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  659. {
  660. AVIOContext *pb = matroska->ctx->pb;
  661. MatroskaLevel *level;
  662. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  663. av_log(matroska->ctx, AV_LOG_ERROR,
  664. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  665. return AVERROR(ENOSYS);
  666. }
  667. level = &matroska->levels[matroska->num_levels++];
  668. level->start = avio_tell(pb);
  669. level->length = length;
  670. return 0;
  671. }
  672. /*
  673. * Read signed/unsigned "EBML" numbers.
  674. * Return: number of bytes processed, < 0 on error
  675. */
  676. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  677. uint8_t *data, uint32_t size, uint64_t *num)
  678. {
  679. AVIOContext pb;
  680. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  681. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  682. }
  683. /*
  684. * Same as above, but signed.
  685. */
  686. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  687. uint8_t *data, uint32_t size, int64_t *num)
  688. {
  689. uint64_t unum;
  690. int res;
  691. /* read as unsigned number first */
  692. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  693. return res;
  694. /* make signed (weird way) */
  695. *num = unum - ((1LL << (7*res - 1)) - 1);
  696. return res;
  697. }
  698. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  699. EbmlSyntax *syntax, void *data);
  700. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  701. uint32_t id, void *data)
  702. {
  703. int i;
  704. for (i=0; syntax[i].id; i++)
  705. if (id == syntax[i].id)
  706. break;
  707. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  708. matroska->num_levels > 0 &&
  709. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  710. return 0; // we reached the end of an unknown size cluster
  711. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
  712. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  713. if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
  714. return AVERROR_INVALIDDATA;
  715. }
  716. return ebml_parse_elem(matroska, &syntax[i], data);
  717. }
  718. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  719. void *data)
  720. {
  721. if (!matroska->current_id) {
  722. uint64_t id;
  723. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  724. if (res < 0)
  725. return res;
  726. matroska->current_id = id | 1 << 7*res;
  727. }
  728. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  729. }
  730. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  731. void *data)
  732. {
  733. int i, res = 0;
  734. for (i=0; syntax[i].id; i++)
  735. switch (syntax[i].type) {
  736. case EBML_UINT:
  737. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  738. break;
  739. case EBML_FLOAT:
  740. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  741. break;
  742. case EBML_STR:
  743. case EBML_UTF8:
  744. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  745. break;
  746. }
  747. while (!res && !ebml_level_end(matroska))
  748. res = ebml_parse(matroska, syntax, data);
  749. return res;
  750. }
  751. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  752. EbmlSyntax *syntax, void *data)
  753. {
  754. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  755. [EBML_UINT] = 8,
  756. [EBML_FLOAT] = 8,
  757. // max. 16 MB for strings
  758. [EBML_STR] = 0x1000000,
  759. [EBML_UTF8] = 0x1000000,
  760. // max. 256 MB for binary data
  761. [EBML_BIN] = 0x10000000,
  762. // no limits for anything else
  763. };
  764. AVIOContext *pb = matroska->ctx->pb;
  765. uint32_t id = syntax->id;
  766. uint64_t length;
  767. int res;
  768. void *newelem;
  769. data = (char *)data + syntax->data_offset;
  770. if (syntax->list_elem_size) {
  771. EbmlList *list = data;
  772. newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  773. if (!newelem)
  774. return AVERROR(ENOMEM);
  775. list->elem = newelem;
  776. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  777. memset(data, 0, syntax->list_elem_size);
  778. list->nb_elem++;
  779. }
  780. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  781. matroska->current_id = 0;
  782. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  783. return res;
  784. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  785. av_log(matroska->ctx, AV_LOG_ERROR,
  786. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  787. length, max_lengths[syntax->type], syntax->type);
  788. return AVERROR_INVALIDDATA;
  789. }
  790. }
  791. switch (syntax->type) {
  792. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  793. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  794. case EBML_STR:
  795. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  796. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  797. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  798. return res;
  799. if (id == MATROSKA_ID_SEGMENT)
  800. matroska->segment_start = avio_tell(matroska->ctx->pb);
  801. return ebml_parse_nest(matroska, syntax->def.n, data);
  802. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  803. case EBML_STOP: return 1;
  804. default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
  805. }
  806. if (res == AVERROR_INVALIDDATA)
  807. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  808. else if (res == AVERROR(EIO))
  809. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  810. return res;
  811. }
  812. static void ebml_free(EbmlSyntax *syntax, void *data)
  813. {
  814. int i, j;
  815. for (i=0; syntax[i].id; i++) {
  816. void *data_off = (char *)data + syntax[i].data_offset;
  817. switch (syntax[i].type) {
  818. case EBML_STR:
  819. case EBML_UTF8: av_freep(data_off); break;
  820. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  821. case EBML_NEST:
  822. if (syntax[i].list_elem_size) {
  823. EbmlList *list = data_off;
  824. char *ptr = list->elem;
  825. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  826. ebml_free(syntax[i].def.n, ptr);
  827. av_free(list->elem);
  828. } else
  829. ebml_free(syntax[i].def.n, data_off);
  830. default: break;
  831. }
  832. }
  833. }
  834. /*
  835. * Autodetecting...
  836. */
  837. static int matroska_probe(AVProbeData *p)
  838. {
  839. uint64_t total = 0;
  840. int len_mask = 0x80, size = 1, n = 1, i;
  841. /* EBML header? */
  842. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  843. return 0;
  844. /* length of header */
  845. total = p->buf[4];
  846. while (size <= 8 && !(total & len_mask)) {
  847. size++;
  848. len_mask >>= 1;
  849. }
  850. if (size > 8)
  851. return 0;
  852. total &= (len_mask - 1);
  853. while (n < size)
  854. total = (total << 8) | p->buf[4 + n++];
  855. /* Does the probe data contain the whole header? */
  856. if (p->buf_size < 4 + size + total)
  857. return 0;
  858. /* The header should contain a known document type. For now,
  859. * we don't parse the whole header but simply check for the
  860. * availability of that array of characters inside the header.
  861. * Not fully fool-proof, but good enough. */
  862. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  863. int probelen = strlen(matroska_doctypes[i]);
  864. if (total < probelen)
  865. continue;
  866. for (n = 4+size; n <= 4+size+total-probelen; n++)
  867. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  868. return AVPROBE_SCORE_MAX;
  869. }
  870. // probably valid EBML header but no recognized doctype
  871. return AVPROBE_SCORE_EXTENSION;
  872. }
  873. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  874. int num)
  875. {
  876. MatroskaTrack *tracks = matroska->tracks.elem;
  877. int i;
  878. for (i=0; i < matroska->tracks.nb_elem; i++)
  879. if (tracks[i].num == num)
  880. return &tracks[i];
  881. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  882. return NULL;
  883. }
  884. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  885. MatroskaTrack *track)
  886. {
  887. MatroskaTrackEncoding *encodings = track->encodings.elem;
  888. uint8_t* data = *buf;
  889. int isize = *buf_size;
  890. uint8_t* pkt_data = NULL;
  891. uint8_t av_unused *newpktdata;
  892. int pkt_size = isize;
  893. int result = 0;
  894. int olen;
  895. if (pkt_size >= 10000000)
  896. return AVERROR_INVALIDDATA;
  897. switch (encodings[0].compression.algo) {
  898. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
  899. int header_size = encodings[0].compression.settings.size;
  900. uint8_t *header = encodings[0].compression.settings.data;
  901. if (!header_size)
  902. return 0;
  903. pkt_size = isize + header_size;
  904. pkt_data = av_malloc(pkt_size);
  905. if (!pkt_data)
  906. return AVERROR(ENOMEM);
  907. memcpy(pkt_data, header, header_size);
  908. memcpy(pkt_data + header_size, data, isize);
  909. break;
  910. }
  911. #if CONFIG_LZO
  912. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  913. do {
  914. olen = pkt_size *= 3;
  915. newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
  916. if (!newpktdata) {
  917. result = AVERROR(ENOMEM);
  918. goto failed;
  919. }
  920. pkt_data = newpktdata;
  921. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  922. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  923. if (result) {
  924. result = AVERROR_INVALIDDATA;
  925. goto failed;
  926. }
  927. pkt_size -= olen;
  928. break;
  929. #endif
  930. #if CONFIG_ZLIB
  931. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  932. z_stream zstream = {0};
  933. if (inflateInit(&zstream) != Z_OK)
  934. return -1;
  935. zstream.next_in = data;
  936. zstream.avail_in = isize;
  937. do {
  938. pkt_size *= 3;
  939. newpktdata = av_realloc(pkt_data, pkt_size);
  940. if (!newpktdata) {
  941. inflateEnd(&zstream);
  942. goto failed;
  943. }
  944. pkt_data = newpktdata;
  945. zstream.avail_out = pkt_size - zstream.total_out;
  946. zstream.next_out = pkt_data + zstream.total_out;
  947. result = inflate(&zstream, Z_NO_FLUSH);
  948. } while (result==Z_OK && pkt_size<10000000);
  949. pkt_size = zstream.total_out;
  950. inflateEnd(&zstream);
  951. if (result != Z_STREAM_END) {
  952. if (result == Z_MEM_ERROR)
  953. result = AVERROR(ENOMEM);
  954. else
  955. result = AVERROR_INVALIDDATA;
  956. goto failed;
  957. }
  958. break;
  959. }
  960. #endif
  961. #if CONFIG_BZLIB
  962. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  963. bz_stream bzstream = {0};
  964. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  965. return -1;
  966. bzstream.next_in = data;
  967. bzstream.avail_in = isize;
  968. do {
  969. pkt_size *= 3;
  970. newpktdata = av_realloc(pkt_data, pkt_size);
  971. if (!newpktdata) {
  972. BZ2_bzDecompressEnd(&bzstream);
  973. goto failed;
  974. }
  975. pkt_data = newpktdata;
  976. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  977. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  978. result = BZ2_bzDecompress(&bzstream);
  979. } while (result==BZ_OK && pkt_size<10000000);
  980. pkt_size = bzstream.total_out_lo32;
  981. BZ2_bzDecompressEnd(&bzstream);
  982. if (result != BZ_STREAM_END) {
  983. if (result == BZ_MEM_ERROR)
  984. result = AVERROR(ENOMEM);
  985. else
  986. result = AVERROR_INVALIDDATA;
  987. goto failed;
  988. }
  989. break;
  990. }
  991. #endif
  992. default:
  993. return AVERROR_INVALIDDATA;
  994. }
  995. *buf = pkt_data;
  996. *buf_size = pkt_size;
  997. return 0;
  998. failed:
  999. av_free(pkt_data);
  1000. return result;
  1001. }
  1002. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  1003. AVPacket *pkt, uint64_t display_duration)
  1004. {
  1005. AVBufferRef *line;
  1006. char *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  1007. for (; *ptr!=',' && ptr<end-1; ptr++);
  1008. if (*ptr == ',')
  1009. layer = ++ptr;
  1010. for (; *ptr!=',' && ptr<end-1; ptr++);
  1011. if (*ptr == ',') {
  1012. int64_t end_pts = pkt->pts + display_duration;
  1013. int sc = matroska->time_scale * pkt->pts / 10000000;
  1014. int ec = matroska->time_scale * end_pts / 10000000;
  1015. int sh, sm, ss, eh, em, es, len;
  1016. sh = sc/360000; sc -= 360000*sh;
  1017. sm = sc/ 6000; sc -= 6000*sm;
  1018. ss = sc/ 100; sc -= 100*ss;
  1019. eh = ec/360000; ec -= 360000*eh;
  1020. em = ec/ 6000; ec -= 6000*em;
  1021. es = ec/ 100; ec -= 100*es;
  1022. *ptr++ = '\0';
  1023. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  1024. if (!(line = av_buffer_alloc(len)))
  1025. return;
  1026. snprintf(line->data, len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  1027. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  1028. av_buffer_unref(&pkt->buf);
  1029. pkt->buf = line;
  1030. pkt->data = line->data;
  1031. pkt->size = strlen(line->data);
  1032. }
  1033. }
  1034. static int matroska_merge_packets(AVPacket *out, AVPacket *in)
  1035. {
  1036. int old_size = out->size;
  1037. int ret = av_grow_packet(out, in->size);
  1038. if (ret < 0)
  1039. return ret;
  1040. memcpy(out->data + old_size, in->data, in->size);
  1041. av_free_packet(in);
  1042. av_free(in);
  1043. return 0;
  1044. }
  1045. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  1046. AVDictionary **metadata, char *prefix)
  1047. {
  1048. MatroskaTag *tags = list->elem;
  1049. char key[1024];
  1050. int i;
  1051. for (i=0; i < list->nb_elem; i++) {
  1052. const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  1053. if (!tags[i].name) {
  1054. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  1055. continue;
  1056. }
  1057. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  1058. else av_strlcpy(key, tags[i].name, sizeof(key));
  1059. if (tags[i].def || !lang) {
  1060. av_dict_set(metadata, key, tags[i].string, 0);
  1061. if (tags[i].sub.nb_elem)
  1062. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1063. }
  1064. if (lang) {
  1065. av_strlcat(key, "-", sizeof(key));
  1066. av_strlcat(key, lang, sizeof(key));
  1067. av_dict_set(metadata, key, tags[i].string, 0);
  1068. if (tags[i].sub.nb_elem)
  1069. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1070. }
  1071. }
  1072. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  1073. }
  1074. static void matroska_convert_tags(AVFormatContext *s)
  1075. {
  1076. MatroskaDemuxContext *matroska = s->priv_data;
  1077. MatroskaTags *tags = matroska->tags.elem;
  1078. int i, j;
  1079. for (i=0; i < matroska->tags.nb_elem; i++) {
  1080. if (tags[i].target.attachuid) {
  1081. MatroskaAttachement *attachment = matroska->attachments.elem;
  1082. for (j=0; j<matroska->attachments.nb_elem; j++)
  1083. if (attachment[j].uid == tags[i].target.attachuid
  1084. && attachment[j].stream)
  1085. matroska_convert_tag(s, &tags[i].tag,
  1086. &attachment[j].stream->metadata, NULL);
  1087. } else if (tags[i].target.chapteruid) {
  1088. MatroskaChapter *chapter = matroska->chapters.elem;
  1089. for (j=0; j<matroska->chapters.nb_elem; j++)
  1090. if (chapter[j].uid == tags[i].target.chapteruid
  1091. && chapter[j].chapter)
  1092. matroska_convert_tag(s, &tags[i].tag,
  1093. &chapter[j].chapter->metadata, NULL);
  1094. } else if (tags[i].target.trackuid) {
  1095. MatroskaTrack *track = matroska->tracks.elem;
  1096. for (j=0; j<matroska->tracks.nb_elem; j++)
  1097. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1098. matroska_convert_tag(s, &tags[i].tag,
  1099. &track[j].stream->metadata, NULL);
  1100. } else {
  1101. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1102. tags[i].target.type);
  1103. }
  1104. }
  1105. }
  1106. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
  1107. {
  1108. EbmlList *seekhead_list = &matroska->seekhead;
  1109. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1110. uint32_t level_up = matroska->level_up;
  1111. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1112. uint32_t saved_id = matroska->current_id;
  1113. MatroskaLevel level;
  1114. int64_t offset;
  1115. int ret = 0;
  1116. if (idx >= seekhead_list->nb_elem
  1117. || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
  1118. || seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1119. return 0;
  1120. /* seek */
  1121. offset = seekhead[idx].pos + matroska->segment_start;
  1122. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1123. /* We don't want to lose our seekhead level, so we add
  1124. * a dummy. This is a crude hack. */
  1125. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1126. av_log(matroska->ctx, AV_LOG_INFO,
  1127. "Max EBML element depth (%d) reached, "
  1128. "cannot parse further.\n", EBML_MAX_DEPTH);
  1129. ret = AVERROR_INVALIDDATA;
  1130. } else {
  1131. level.start = 0;
  1132. level.length = (uint64_t)-1;
  1133. matroska->levels[matroska->num_levels] = level;
  1134. matroska->num_levels++;
  1135. matroska->current_id = 0;
  1136. ret = ebml_parse(matroska, matroska_segment, matroska);
  1137. /* remove dummy level */
  1138. while (matroska->num_levels) {
  1139. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1140. if (length == (uint64_t)-1)
  1141. break;
  1142. }
  1143. }
  1144. }
  1145. /* seek back */
  1146. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1147. matroska->level_up = level_up;
  1148. matroska->current_id = saved_id;
  1149. return ret;
  1150. }
  1151. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1152. {
  1153. EbmlList *seekhead_list = &matroska->seekhead;
  1154. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1155. int i;
  1156. // we should not do any seeking in the streaming case
  1157. if (!matroska->ctx->pb->seekable ||
  1158. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1159. return;
  1160. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1161. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1162. if (seekhead[i].pos <= before_pos)
  1163. continue;
  1164. // defer cues parsing until we actually need cue data.
  1165. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1166. matroska->cues_parsing_deferred = 1;
  1167. continue;
  1168. }
  1169. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1170. break;
  1171. }
  1172. }
  1173. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1174. EbmlList *seekhead_list = &matroska->seekhead;
  1175. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1176. EbmlList *index_list;
  1177. MatroskaIndex *index;
  1178. int index_scale = 1;
  1179. int i, j;
  1180. for (i = 0; i < seekhead_list->nb_elem; i++)
  1181. if (seekhead[i].id == MATROSKA_ID_CUES)
  1182. break;
  1183. assert(i <= seekhead_list->nb_elem);
  1184. matroska_parse_seekhead_entry(matroska, i);
  1185. index_list = &matroska->index;
  1186. index = index_list->elem;
  1187. if (index_list->nb_elem
  1188. && index[0].time > 1E14/matroska->time_scale) {
  1189. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1190. index_scale = matroska->time_scale;
  1191. }
  1192. for (i = 0; i < index_list->nb_elem; i++) {
  1193. EbmlList *pos_list = &index[i].pos;
  1194. MatroskaIndexPos *pos = pos_list->elem;
  1195. for (j = 0; j < pos_list->nb_elem; j++) {
  1196. MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
  1197. if (track && track->stream)
  1198. av_add_index_entry(track->stream,
  1199. pos[j].pos + matroska->segment_start,
  1200. index[i].time/index_scale, 0, 0,
  1201. AVINDEX_KEYFRAME);
  1202. }
  1203. }
  1204. }
  1205. static int matroska_aac_profile(char *codec_id)
  1206. {
  1207. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1208. int profile;
  1209. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1210. if (strstr(codec_id, aac_profiles[profile]))
  1211. break;
  1212. return profile + 1;
  1213. }
  1214. static int matroska_aac_sri(int samplerate)
  1215. {
  1216. int sri;
  1217. for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1218. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1219. break;
  1220. return sri;
  1221. }
  1222. static int matroska_read_header(AVFormatContext *s)
  1223. {
  1224. MatroskaDemuxContext *matroska = s->priv_data;
  1225. EbmlList *attachements_list = &matroska->attachments;
  1226. MatroskaAttachement *attachements;
  1227. EbmlList *chapters_list = &matroska->chapters;
  1228. MatroskaChapter *chapters;
  1229. MatroskaTrack *tracks;
  1230. uint64_t max_start = 0;
  1231. int64_t pos;
  1232. Ebml ebml = { 0 };
  1233. AVStream *st;
  1234. int i, j, res;
  1235. matroska->ctx = s;
  1236. /* First read the EBML header. */
  1237. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1238. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1239. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
  1240. av_log(matroska->ctx, AV_LOG_ERROR,
  1241. "EBML header using unsupported features\n"
  1242. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1243. ebml.version, ebml.doctype, ebml.doctype_version);
  1244. ebml_free(ebml_syntax, &ebml);
  1245. return AVERROR_PATCHWELCOME;
  1246. }
  1247. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1248. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1249. break;
  1250. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1251. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1252. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1253. ebml_free(ebml_syntax, &ebml);
  1254. return AVERROR_INVALIDDATA;
  1255. }
  1256. }
  1257. ebml_free(ebml_syntax, &ebml);
  1258. /* The next thing is a segment. */
  1259. pos = avio_tell(matroska->ctx->pb);
  1260. res = ebml_parse(matroska, matroska_segments, matroska);
  1261. // try resyncing until we find a EBML_STOP type element.
  1262. while (res != 1) {
  1263. res = matroska_resync(matroska, pos);
  1264. if (res < 0)
  1265. return res;
  1266. pos = avio_tell(matroska->ctx->pb);
  1267. res = ebml_parse(matroska, matroska_segment, matroska);
  1268. }
  1269. matroska_execute_seekhead(matroska);
  1270. if (!matroska->time_scale)
  1271. matroska->time_scale = 1000000;
  1272. if (matroska->duration)
  1273. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1274. * 1000 / AV_TIME_BASE;
  1275. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1276. tracks = matroska->tracks.elem;
  1277. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1278. MatroskaTrack *track = &tracks[i];
  1279. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1280. EbmlList *encodings_list = &tracks->encodings;
  1281. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1282. uint8_t *extradata = NULL;
  1283. int extradata_size = 0;
  1284. int extradata_offset = 0;
  1285. AVIOContext b;
  1286. /* Apply some sanity checks. */
  1287. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1288. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1289. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1290. av_log(matroska->ctx, AV_LOG_INFO,
  1291. "Unknown or unsupported track type %"PRIu64"\n",
  1292. track->type);
  1293. continue;
  1294. }
  1295. if (track->codec_id == NULL)
  1296. continue;
  1297. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1298. if (!track->default_duration && track->video.frame_rate > 0)
  1299. track->default_duration = 1000000000/track->video.frame_rate;
  1300. if (!track->video.display_width)
  1301. track->video.display_width = track->video.pixel_width;
  1302. if (!track->video.display_height)
  1303. track->video.display_height = track->video.pixel_height;
  1304. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1305. if (!track->audio.out_samplerate)
  1306. track->audio.out_samplerate = track->audio.samplerate;
  1307. }
  1308. if (encodings_list->nb_elem > 1) {
  1309. av_log(matroska->ctx, AV_LOG_ERROR,
  1310. "Multiple combined encodings not supported");
  1311. } else if (encodings_list->nb_elem == 1) {
  1312. if (encodings[0].type ||
  1313. (
  1314. #if CONFIG_ZLIB
  1315. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1316. #endif
  1317. #if CONFIG_BZLIB
  1318. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1319. #endif
  1320. #if CONFIG_LZO
  1321. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
  1322. #endif
  1323. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
  1324. encodings[0].scope = 0;
  1325. av_log(matroska->ctx, AV_LOG_ERROR,
  1326. "Unsupported encoding type");
  1327. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1328. uint8_t *codec_priv = track->codec_priv.data;
  1329. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1330. &track->codec_priv.size,
  1331. track);
  1332. if (ret < 0) {
  1333. track->codec_priv.data = NULL;
  1334. track->codec_priv.size = 0;
  1335. av_log(matroska->ctx, AV_LOG_ERROR,
  1336. "Failed to decode codec private data\n");
  1337. }
  1338. if (codec_priv != track->codec_priv.data)
  1339. av_free(codec_priv);
  1340. }
  1341. }
  1342. for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
  1343. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1344. strlen(ff_mkv_codec_tags[j].str))){
  1345. codec_id= ff_mkv_codec_tags[j].id;
  1346. break;
  1347. }
  1348. }
  1349. st = track->stream = avformat_new_stream(s, NULL);
  1350. if (st == NULL)
  1351. return AVERROR(ENOMEM);
  1352. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1353. && track->codec_priv.size >= 40
  1354. && track->codec_priv.data != NULL) {
  1355. track->ms_compat = 1;
  1356. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1357. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1358. extradata_offset = 40;
  1359. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1360. && track->codec_priv.size >= 14
  1361. && track->codec_priv.data != NULL) {
  1362. int ret;
  1363. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1364. 0, NULL, NULL, NULL, NULL);
  1365. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1366. if (ret < 0)
  1367. return ret;
  1368. codec_id = st->codec->codec_id;
  1369. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1370. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1371. && (track->codec_priv.size >= 86)
  1372. && (track->codec_priv.data != NULL)) {
  1373. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1374. codec_id=ff_codec_get_id(ff_codec_movvideo_tags, track->video.fourcc);
  1375. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1376. switch (track->audio.bitdepth) {
  1377. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1378. case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
  1379. case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
  1380. }
  1381. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1382. switch (track->audio.bitdepth) {
  1383. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1384. case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
  1385. case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
  1386. }
  1387. } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1388. codec_id = AV_CODEC_ID_PCM_F64LE;
  1389. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1390. int profile = matroska_aac_profile(track->codec_id);
  1391. int sri = matroska_aac_sri(track->audio.samplerate);
  1392. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1393. if (extradata == NULL)
  1394. return AVERROR(ENOMEM);
  1395. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1396. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1397. if (strstr(track->codec_id, "SBR")) {
  1398. sri = matroska_aac_sri(track->audio.out_samplerate);
  1399. extradata[2] = 0x56;
  1400. extradata[3] = 0xE5;
  1401. extradata[4] = 0x80 | (sri<<3);
  1402. extradata_size = 5;
  1403. } else
  1404. extradata_size = 2;
  1405. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
  1406. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1407. Create the "atom size", "tag", and "tag version" fields the
  1408. decoder expects manually. */
  1409. extradata_size = 12 + track->codec_priv.size;
  1410. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1411. if (extradata == NULL)
  1412. return AVERROR(ENOMEM);
  1413. AV_WB32(extradata, extradata_size);
  1414. memcpy(&extradata[4], "alac", 4);
  1415. AV_WB32(&extradata[8], 0);
  1416. memcpy(&extradata[12], track->codec_priv.data,
  1417. track->codec_priv.size);
  1418. } else if (codec_id == AV_CODEC_ID_TTA) {
  1419. extradata_size = 30;
  1420. extradata = av_mallocz(extradata_size);
  1421. if (extradata == NULL)
  1422. return AVERROR(ENOMEM);
  1423. ffio_init_context(&b, extradata, extradata_size, 1,
  1424. NULL, NULL, NULL, NULL);
  1425. avio_write(&b, "TTA1", 4);
  1426. avio_wl16(&b, 1);
  1427. avio_wl16(&b, track->audio.channels);
  1428. avio_wl16(&b, track->audio.bitdepth);
  1429. avio_wl32(&b, track->audio.out_samplerate);
  1430. avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1431. } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
  1432. codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
  1433. extradata_offset = 26;
  1434. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1435. track->audio.out_samplerate = 8000;
  1436. track->audio.channels = 1;
  1437. } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
  1438. codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
  1439. int flavor;
  1440. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1441. 0, NULL, NULL, NULL, NULL);
  1442. avio_skip(&b, 22);
  1443. flavor = avio_rb16(&b);
  1444. track->audio.coded_framesize = avio_rb32(&b);
  1445. avio_skip(&b, 12);
  1446. track->audio.sub_packet_h = avio_rb16(&b);
  1447. track->audio.frame_size = avio_rb16(&b);
  1448. track->audio.sub_packet_size = avio_rb16(&b);
  1449. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1450. if (codec_id == AV_CODEC_ID_RA_288) {
  1451. st->codec->block_align = track->audio.coded_framesize;
  1452. track->codec_priv.size = 0;
  1453. } else {
  1454. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1455. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1456. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1457. st->codec->bit_rate = sipr_bit_rate[flavor];
  1458. }
  1459. st->codec->block_align = track->audio.sub_packet_size;
  1460. extradata_offset = 78;
  1461. }
  1462. }
  1463. track->codec_priv.size -= extradata_offset;
  1464. if (codec_id == AV_CODEC_ID_NONE)
  1465. av_log(matroska->ctx, AV_LOG_INFO,
  1466. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1467. if (track->time_scale < 0.01)
  1468. track->time_scale = 1.0;
  1469. avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1470. st->codec->codec_id = codec_id;
  1471. st->start_time = 0;
  1472. if (strcmp(track->language, "und"))
  1473. av_dict_set(&st->metadata, "language", track->language, 0);
  1474. av_dict_set(&st->metadata, "title", track->name, 0);
  1475. if (track->flag_default)
  1476. st->disposition |= AV_DISPOSITION_DEFAULT;
  1477. if (track->flag_forced)
  1478. st->disposition |= AV_DISPOSITION_FORCED;
  1479. if (!st->codec->extradata) {
  1480. if(extradata){
  1481. st->codec->extradata = extradata;
  1482. st->codec->extradata_size = extradata_size;
  1483. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1484. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1485. FF_INPUT_BUFFER_PADDING_SIZE);
  1486. if(st->codec->extradata == NULL)
  1487. return AVERROR(ENOMEM);
  1488. st->codec->extradata_size = track->codec_priv.size;
  1489. memcpy(st->codec->extradata,
  1490. track->codec_priv.data + extradata_offset,
  1491. track->codec_priv.size);
  1492. }
  1493. }
  1494. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1495. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1496. st->codec->codec_tag = track->video.fourcc;
  1497. st->codec->width = track->video.pixel_width;
  1498. st->codec->height = track->video.pixel_height;
  1499. av_reduce(&st->sample_aspect_ratio.num,
  1500. &st->sample_aspect_ratio.den,
  1501. st->codec->height * track->video.display_width,
  1502. st->codec-> width * track->video.display_height,
  1503. 255);
  1504. if (st->codec->codec_id != AV_CODEC_ID_H264)
  1505. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1506. if (track->default_duration) {
  1507. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1508. 1000000000, track->default_duration, 30000);
  1509. }
  1510. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1511. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1512. st->codec->sample_rate = track->audio.out_samplerate;
  1513. st->codec->channels = track->audio.channels;
  1514. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1515. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1516. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1517. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1518. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1519. matroska->contains_ssa = 1;
  1520. }
  1521. }
  1522. attachements = attachements_list->elem;
  1523. for (j=0; j<attachements_list->nb_elem; j++) {
  1524. if (!(attachements[j].filename && attachements[j].mime &&
  1525. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1526. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1527. } else {
  1528. AVStream *st = avformat_new_stream(s, NULL);
  1529. if (st == NULL)
  1530. break;
  1531. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1532. av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
  1533. st->codec->codec_id = AV_CODEC_ID_NONE;
  1534. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1535. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1536. if(st->codec->extradata == NULL)
  1537. break;
  1538. st->codec->extradata_size = attachements[j].bin.size;
  1539. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1540. for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1541. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1542. strlen(ff_mkv_mime_tags[i].str))) {
  1543. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1544. break;
  1545. }
  1546. }
  1547. attachements[j].stream = st;
  1548. }
  1549. }
  1550. chapters = chapters_list->elem;
  1551. for (i=0; i<chapters_list->nb_elem; i++)
  1552. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1553. && (max_start==0 || chapters[i].start > max_start)) {
  1554. chapters[i].chapter =
  1555. avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1556. chapters[i].start, chapters[i].end,
  1557. chapters[i].title);
  1558. av_dict_set(&chapters[i].chapter->metadata,
  1559. "title", chapters[i].title, 0);
  1560. max_start = chapters[i].start;
  1561. }
  1562. matroska_convert_tags(s);
  1563. return 0;
  1564. }
  1565. /*
  1566. * Put one packet in an application-supplied AVPacket struct.
  1567. * Returns 0 on success or -1 on failure.
  1568. */
  1569. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1570. AVPacket *pkt)
  1571. {
  1572. if (matroska->num_packets > 0) {
  1573. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1574. av_free(matroska->packets[0]);
  1575. if (matroska->num_packets > 1) {
  1576. void *newpackets;
  1577. memmove(&matroska->packets[0], &matroska->packets[1],
  1578. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1579. newpackets = av_realloc(matroska->packets,
  1580. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1581. if (newpackets)
  1582. matroska->packets = newpackets;
  1583. } else {
  1584. av_freep(&matroska->packets);
  1585. matroska->prev_pkt = NULL;
  1586. }
  1587. matroska->num_packets--;
  1588. return 0;
  1589. }
  1590. return -1;
  1591. }
  1592. /*
  1593. * Free all packets in our internal queue.
  1594. */
  1595. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1596. {
  1597. matroska->prev_pkt = NULL;
  1598. if (matroska->packets) {
  1599. int n;
  1600. for (n = 0; n < matroska->num_packets; n++) {
  1601. av_free_packet(matroska->packets[n]);
  1602. av_free(matroska->packets[n]);
  1603. }
  1604. av_freep(&matroska->packets);
  1605. matroska->num_packets = 0;
  1606. }
  1607. }
  1608. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1609. int* buf_size, int type,
  1610. uint32_t **lace_buf, int *laces)
  1611. {
  1612. int res = 0, n, size = *buf_size;
  1613. uint8_t *data = *buf;
  1614. uint32_t *lace_size;
  1615. if (!type) {
  1616. *laces = 1;
  1617. *lace_buf = av_mallocz(sizeof(int));
  1618. if (!*lace_buf)
  1619. return AVERROR(ENOMEM);
  1620. *lace_buf[0] = size;
  1621. return 0;
  1622. }
  1623. assert(size > 0);
  1624. *laces = *data + 1;
  1625. data += 1;
  1626. size -= 1;
  1627. lace_size = av_mallocz(*laces * sizeof(int));
  1628. if (!lace_size)
  1629. return AVERROR(ENOMEM);
  1630. switch (type) {
  1631. case 0x1: /* Xiph lacing */ {
  1632. uint8_t temp;
  1633. uint32_t total = 0;
  1634. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1635. while (1) {
  1636. if (size == 0) {
  1637. res = AVERROR_EOF;
  1638. break;
  1639. }
  1640. temp = *data;
  1641. lace_size[n] += temp;
  1642. data += 1;
  1643. size -= 1;
  1644. if (temp != 0xff)
  1645. break;
  1646. }
  1647. total += lace_size[n];
  1648. }
  1649. if (size <= total) {
  1650. res = AVERROR_INVALIDDATA;
  1651. break;
  1652. }
  1653. lace_size[n] = size - total;
  1654. break;
  1655. }
  1656. case 0x2: /* fixed-size lacing */
  1657. if (size % (*laces)) {
  1658. res = AVERROR_INVALIDDATA;
  1659. break;
  1660. }
  1661. for (n = 0; n < *laces; n++)
  1662. lace_size[n] = size / *laces;
  1663. break;
  1664. case 0x3: /* EBML lacing */ {
  1665. uint64_t num;
  1666. uint64_t total;
  1667. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1668. if (n < 0) {
  1669. av_log(matroska->ctx, AV_LOG_INFO,
  1670. "EBML block data error\n");
  1671. res = n;
  1672. break;
  1673. }
  1674. data += n;
  1675. size -= n;
  1676. total = lace_size[0] = num;
  1677. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1678. int64_t snum;
  1679. int r;
  1680. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1681. if (r < 0) {
  1682. av_log(matroska->ctx, AV_LOG_INFO,
  1683. "EBML block data error\n");
  1684. res = r;
  1685. break;
  1686. }
  1687. data += r;
  1688. size -= r;
  1689. lace_size[n] = lace_size[n - 1] + snum;
  1690. total += lace_size[n];
  1691. }
  1692. if (size <= total) {
  1693. res = AVERROR_INVALIDDATA;
  1694. break;
  1695. }
  1696. lace_size[*laces - 1] = size - total;
  1697. break;
  1698. }
  1699. }
  1700. *buf = data;
  1701. *lace_buf = lace_size;
  1702. *buf_size = size;
  1703. return res;
  1704. }
  1705. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1706. MatroskaTrack *track,
  1707. AVStream *st,
  1708. uint8_t *data, int size,
  1709. uint64_t timecode, uint64_t duration,
  1710. int64_t pos)
  1711. {
  1712. int a = st->codec->block_align;
  1713. int sps = track->audio.sub_packet_size;
  1714. int cfs = track->audio.coded_framesize;
  1715. int h = track->audio.sub_packet_h;
  1716. int y = track->audio.sub_packet_cnt;
  1717. int w = track->audio.frame_size;
  1718. int x;
  1719. if (!track->audio.pkt_cnt) {
  1720. if (track->audio.sub_packet_cnt == 0)
  1721. track->audio.buf_timecode = timecode;
  1722. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1723. if (size < cfs * h / 2) {
  1724. av_log(matroska->ctx, AV_LOG_ERROR,
  1725. "Corrupt int4 RM-style audio packet size\n");
  1726. return AVERROR_INVALIDDATA;
  1727. }
  1728. for (x=0; x<h/2; x++)
  1729. memcpy(track->audio.buf+x*2*w+y*cfs,
  1730. data+x*cfs, cfs);
  1731. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1732. if (size < w) {
  1733. av_log(matroska->ctx, AV_LOG_ERROR,
  1734. "Corrupt sipr RM-style audio packet size\n");
  1735. return AVERROR_INVALIDDATA;
  1736. }
  1737. memcpy(track->audio.buf + y*w, data, w);
  1738. } else {
  1739. if (size < sps * w / sps) {
  1740. av_log(matroska->ctx, AV_LOG_ERROR,
  1741. "Corrupt generic RM-style audio packet size\n");
  1742. return AVERROR_INVALIDDATA;
  1743. }
  1744. for (x=0; x<w/sps; x++)
  1745. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1746. }
  1747. if (++track->audio.sub_packet_cnt >= h) {
  1748. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1749. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1750. track->audio.sub_packet_cnt = 0;
  1751. track->audio.pkt_cnt = h*w / a;
  1752. }
  1753. }
  1754. while (track->audio.pkt_cnt) {
  1755. AVPacket *pkt = av_mallocz(sizeof(AVPacket));
  1756. av_new_packet(pkt, a);
  1757. memcpy(pkt->data, track->audio.buf
  1758. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1759. pkt->pts = track->audio.buf_timecode;
  1760. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1761. pkt->pos = pos;
  1762. pkt->stream_index = st->index;
  1763. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1764. }
  1765. return 0;
  1766. }
  1767. /* reconstruct full wavpack blocks from mangled matroska ones */
  1768. static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
  1769. uint8_t **pdst, int *size)
  1770. {
  1771. uint8_t *dst = NULL;
  1772. int dstlen = 0;
  1773. int srclen = *size;
  1774. uint32_t samples;
  1775. uint16_t ver;
  1776. int ret, offset = 0;
  1777. if (srclen < 12 || track->stream->codec->extradata_size < 2)
  1778. return AVERROR_INVALIDDATA;
  1779. ver = AV_RL16(track->stream->codec->extradata);
  1780. samples = AV_RL32(src);
  1781. src += 4;
  1782. srclen -= 4;
  1783. while (srclen >= 8) {
  1784. int multiblock;
  1785. uint32_t blocksize;
  1786. uint8_t *tmp;
  1787. uint32_t flags = AV_RL32(src);
  1788. uint32_t crc = AV_RL32(src + 4);
  1789. src += 8;
  1790. srclen -= 8;
  1791. multiblock = (flags & 0x1800) != 0x1800;
  1792. if (multiblock) {
  1793. if (srclen < 4) {
  1794. ret = AVERROR_INVALIDDATA;
  1795. goto fail;
  1796. }
  1797. blocksize = AV_RL32(src);
  1798. src += 4;
  1799. srclen -= 4;
  1800. } else
  1801. blocksize = srclen;
  1802. if (blocksize > srclen) {
  1803. ret = AVERROR_INVALIDDATA;
  1804. goto fail;
  1805. }
  1806. tmp = av_realloc(dst, dstlen + blocksize + 32);
  1807. if (!tmp) {
  1808. ret = AVERROR(ENOMEM);
  1809. goto fail;
  1810. }
  1811. dst = tmp;
  1812. dstlen += blocksize + 32;
  1813. AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
  1814. AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
  1815. AV_WL16(dst + offset + 8, ver); // version
  1816. AV_WL16(dst + offset + 10, 0); // track/index_no
  1817. AV_WL32(dst + offset + 12, 0); // total samples
  1818. AV_WL32(dst + offset + 16, 0); // block index
  1819. AV_WL32(dst + offset + 20, samples); // number of samples
  1820. AV_WL32(dst + offset + 24, flags); // flags
  1821. AV_WL32(dst + offset + 28, crc); // crc
  1822. memcpy (dst + offset + 32, src, blocksize); // block data
  1823. src += blocksize;
  1824. srclen -= blocksize;
  1825. offset += blocksize + 32;
  1826. }
  1827. *pdst = dst;
  1828. *size = dstlen;
  1829. return 0;
  1830. fail:
  1831. av_freep(&dst);
  1832. return ret;
  1833. }
  1834. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  1835. MatroskaTrack *track,
  1836. AVStream *st,
  1837. uint8_t *data, int pkt_size,
  1838. uint64_t timecode, uint64_t duration,
  1839. int64_t pos, int is_keyframe)
  1840. {
  1841. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1842. uint8_t *pkt_data = data;
  1843. int offset = 0, res;
  1844. AVPacket *pkt;
  1845. if (encodings && encodings->scope & 1) {
  1846. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  1847. if (res < 0)
  1848. return res;
  1849. }
  1850. if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
  1851. uint8_t *wv_data;
  1852. res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
  1853. if (res < 0) {
  1854. av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
  1855. goto fail;
  1856. }
  1857. if (pkt_data != data)
  1858. av_freep(&pkt_data);
  1859. pkt_data = wv_data;
  1860. }
  1861. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  1862. offset = 8;
  1863. pkt = av_mallocz(sizeof(AVPacket));
  1864. /* XXX: prevent data copy... */
  1865. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  1866. av_free(pkt);
  1867. return AVERROR(ENOMEM);
  1868. }
  1869. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  1870. uint8_t *buf = pkt->data;
  1871. bytestream_put_be32(&buf, pkt_size);
  1872. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  1873. }
  1874. memcpy(pkt->data + offset, pkt_data, pkt_size);
  1875. if (pkt_data != data)
  1876. av_free(pkt_data);
  1877. pkt->flags = is_keyframe;
  1878. pkt->stream_index = st->index;
  1879. if (track->ms_compat)
  1880. pkt->dts = timecode;
  1881. else
  1882. pkt->pts = timecode;
  1883. pkt->pos = pos;
  1884. if (st->codec->codec_id == AV_CODEC_ID_TEXT)
  1885. pkt->convergence_duration = duration;
  1886. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1887. pkt->duration = duration;
  1888. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1889. matroska_fix_ass_packet(matroska, pkt, duration);
  1890. if (matroska->prev_pkt &&
  1891. timecode != AV_NOPTS_VALUE &&
  1892. matroska->prev_pkt->pts == timecode &&
  1893. matroska->prev_pkt->stream_index == st->index &&
  1894. st->codec->codec_id == AV_CODEC_ID_SSA)
  1895. matroska_merge_packets(matroska->prev_pkt, pkt);
  1896. else {
  1897. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1898. matroska->prev_pkt = pkt;
  1899. }
  1900. return 0;
  1901. fail:
  1902. if (pkt_data != data)
  1903. av_freep(&pkt_data);
  1904. return res;
  1905. }
  1906. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1907. int size, int64_t pos, uint64_t cluster_time,
  1908. uint64_t block_duration, int is_keyframe,
  1909. int64_t cluster_pos)
  1910. {
  1911. uint64_t timecode = AV_NOPTS_VALUE;
  1912. MatroskaTrack *track;
  1913. int res = 0;
  1914. AVStream *st;
  1915. int16_t block_time;
  1916. uint32_t *lace_size = NULL;
  1917. int n, flags, laces = 0;
  1918. uint64_t num, duration;
  1919. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1920. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1921. return n;
  1922. }
  1923. data += n;
  1924. size -= n;
  1925. track = matroska_find_track_by_num(matroska, num);
  1926. if (!track || !track->stream) {
  1927. av_log(matroska->ctx, AV_LOG_INFO,
  1928. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1929. return AVERROR_INVALIDDATA;
  1930. } else if (size <= 3)
  1931. return 0;
  1932. st = track->stream;
  1933. if (st->discard >= AVDISCARD_ALL)
  1934. return res;
  1935. block_time = AV_RB16(data);
  1936. data += 2;
  1937. flags = *data++;
  1938. size -= 3;
  1939. if (is_keyframe == -1)
  1940. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1941. if (cluster_time != (uint64_t)-1
  1942. && (block_time >= 0 || cluster_time >= -block_time)) {
  1943. timecode = cluster_time + block_time;
  1944. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1945. && timecode < track->end_timecode)
  1946. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1947. if (is_keyframe)
  1948. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1949. }
  1950. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1951. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1952. return res;
  1953. matroska->skip_to_keyframe = 0;
  1954. }
  1955. res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
  1956. &lace_size, &laces);
  1957. if (res)
  1958. goto end;
  1959. if (block_duration != AV_NOPTS_VALUE) {
  1960. duration = block_duration / laces;
  1961. if (block_duration != duration * laces) {
  1962. av_log(matroska->ctx, AV_LOG_WARNING,
  1963. "Incorrect block_duration, possibly corrupted container");
  1964. }
  1965. } else {
  1966. duration = track->default_duration / matroska->time_scale;
  1967. block_duration = duration * laces;
  1968. }
  1969. if (timecode != AV_NOPTS_VALUE)
  1970. track->end_timecode =
  1971. FFMAX(track->end_timecode, timecode + block_duration);
  1972. for (n = 0; n < laces; n++) {
  1973. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  1974. st->codec->codec_id == AV_CODEC_ID_COOK ||
  1975. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  1976. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  1977. st->codec->block_align && track->audio.sub_packet_size) {
  1978. res = matroska_parse_rm_audio(matroska, track, st, data,
  1979. lace_size[n],
  1980. timecode, duration, pos);
  1981. if (res)
  1982. goto end;
  1983. } else {
  1984. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  1985. timecode, duration,
  1986. pos, !n? is_keyframe : 0);
  1987. if (res)
  1988. goto end;
  1989. }
  1990. if (timecode != AV_NOPTS_VALUE)
  1991. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1992. data += lace_size[n];
  1993. }
  1994. end:
  1995. av_free(lace_size);
  1996. return res;
  1997. }
  1998. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  1999. {
  2000. EbmlList *blocks_list;
  2001. MatroskaBlock *blocks;
  2002. int i, res;
  2003. res = ebml_parse(matroska,
  2004. matroska_cluster_incremental_parsing,
  2005. &matroska->current_cluster);
  2006. if (res == 1) {
  2007. /* New Cluster */
  2008. if (matroska->current_cluster_pos)
  2009. ebml_level_end(matroska);
  2010. ebml_free(matroska_cluster, &matroska->current_cluster);
  2011. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2012. matroska->current_cluster_num_blocks = 0;
  2013. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2014. matroska->prev_pkt = NULL;
  2015. /* sizeof the ID which was already read */
  2016. if (matroska->current_id)
  2017. matroska->current_cluster_pos -= 4;
  2018. res = ebml_parse(matroska,
  2019. matroska_clusters_incremental,
  2020. &matroska->current_cluster);
  2021. /* Try parsing the block again. */
  2022. if (res == 1)
  2023. res = ebml_parse(matroska,
  2024. matroska_cluster_incremental_parsing,
  2025. &matroska->current_cluster);
  2026. }
  2027. if (!res &&
  2028. matroska->current_cluster_num_blocks <
  2029. matroska->current_cluster.blocks.nb_elem) {
  2030. blocks_list = &matroska->current_cluster.blocks;
  2031. blocks = blocks_list->elem;
  2032. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2033. i = blocks_list->nb_elem - 1;
  2034. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2035. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2036. if (!blocks[i].non_simple)
  2037. blocks[i].duration = AV_NOPTS_VALUE;
  2038. res = matroska_parse_block(matroska,
  2039. blocks[i].bin.data, blocks[i].bin.size,
  2040. blocks[i].bin.pos,
  2041. matroska->current_cluster.timecode,
  2042. blocks[i].duration, is_keyframe,
  2043. matroska->current_cluster_pos);
  2044. }
  2045. }
  2046. if (res < 0) matroska->done = 1;
  2047. return res;
  2048. }
  2049. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2050. {
  2051. MatroskaCluster cluster = { 0 };
  2052. EbmlList *blocks_list;
  2053. MatroskaBlock *blocks;
  2054. int i, res;
  2055. int64_t pos;
  2056. if (!matroska->contains_ssa)
  2057. return matroska_parse_cluster_incremental(matroska);
  2058. pos = avio_tell(matroska->ctx->pb);
  2059. matroska->prev_pkt = NULL;
  2060. if (matroska->current_id)
  2061. pos -= 4; /* sizeof the ID which was already read */
  2062. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2063. blocks_list = &cluster.blocks;
  2064. blocks = blocks_list->elem;
  2065. for (i=0; i<blocks_list->nb_elem && !res; i++)
  2066. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2067. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2068. if (!blocks[i].non_simple)
  2069. blocks[i].duration = AV_NOPTS_VALUE;
  2070. res=matroska_parse_block(matroska,
  2071. blocks[i].bin.data, blocks[i].bin.size,
  2072. blocks[i].bin.pos, cluster.timecode,
  2073. blocks[i].duration, is_keyframe,
  2074. pos);
  2075. }
  2076. ebml_free(matroska_cluster, &cluster);
  2077. return res;
  2078. }
  2079. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2080. {
  2081. MatroskaDemuxContext *matroska = s->priv_data;
  2082. int ret = 0;
  2083. while (!ret && matroska_deliver_packet(matroska, pkt)) {
  2084. int64_t pos = avio_tell(matroska->ctx->pb);
  2085. if (matroska->done)
  2086. return AVERROR_EOF;
  2087. if (matroska_parse_cluster(matroska) < 0)
  2088. ret = matroska_resync(matroska, pos);
  2089. }
  2090. if (ret == AVERROR_INVALIDDATA && pkt->data) {
  2091. pkt->flags |= AV_PKT_FLAG_CORRUPT;
  2092. return 0;
  2093. }
  2094. return ret;
  2095. }
  2096. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2097. int64_t timestamp, int flags)
  2098. {
  2099. MatroskaDemuxContext *matroska = s->priv_data;
  2100. MatroskaTrack *tracks = matroska->tracks.elem;
  2101. AVStream *st = s->streams[stream_index];
  2102. int i, index, index_sub, index_min;
  2103. /* Parse the CUES now since we need the index data to seek. */
  2104. if (matroska->cues_parsing_deferred) {
  2105. matroska_parse_cues(matroska);
  2106. matroska->cues_parsing_deferred = 0;
  2107. }
  2108. if (!st->nb_index_entries)
  2109. return 0;
  2110. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2111. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2112. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  2113. matroska->current_id = 0;
  2114. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2115. matroska_clear_queue(matroska);
  2116. if (matroska_parse_cluster(matroska) < 0)
  2117. break;
  2118. }
  2119. }
  2120. matroska_clear_queue(matroska);
  2121. if (index < 0)
  2122. return 0;
  2123. index_min = index;
  2124. for (i=0; i < matroska->tracks.nb_elem; i++) {
  2125. tracks[i].audio.pkt_cnt = 0;
  2126. tracks[i].audio.sub_packet_cnt = 0;
  2127. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2128. tracks[i].end_timecode = 0;
  2129. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  2130. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  2131. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  2132. if (index_sub >= 0
  2133. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  2134. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  2135. index_min = index_sub;
  2136. }
  2137. }
  2138. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2139. matroska->current_id = 0;
  2140. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2141. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2142. matroska->done = 0;
  2143. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2144. return 0;
  2145. }
  2146. static int matroska_read_close(AVFormatContext *s)
  2147. {
  2148. MatroskaDemuxContext *matroska = s->priv_data;
  2149. MatroskaTrack *tracks = matroska->tracks.elem;
  2150. int n;
  2151. matroska_clear_queue(matroska);
  2152. for (n=0; n < matroska->tracks.nb_elem; n++)
  2153. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2154. av_free(tracks[n].audio.buf);
  2155. ebml_free(matroska_cluster, &matroska->current_cluster);
  2156. ebml_free(matroska_segment, matroska);
  2157. return 0;
  2158. }
  2159. AVInputFormat ff_matroska_demuxer = {
  2160. .name = "matroska,webm",
  2161. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2162. .priv_data_size = sizeof(MatroskaDemuxContext),
  2163. .read_probe = matroska_probe,
  2164. .read_header = matroska_read_header,
  2165. .read_packet = matroska_read_packet,
  2166. .read_close = matroska_read_close,
  2167. .read_seek = matroska_read_seek,
  2168. };