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.

2436 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 = tags[i].lang && strcmp(tags[i].lang, "und") ?
  1053. tags[i].lang : NULL;
  1054. if (!tags[i].name) {
  1055. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  1056. continue;
  1057. }
  1058. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  1059. else av_strlcpy(key, tags[i].name, sizeof(key));
  1060. if (tags[i].def || !lang) {
  1061. av_dict_set(metadata, key, tags[i].string, 0);
  1062. if (tags[i].sub.nb_elem)
  1063. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1064. }
  1065. if (lang) {
  1066. av_strlcat(key, "-", sizeof(key));
  1067. av_strlcat(key, lang, sizeof(key));
  1068. av_dict_set(metadata, key, tags[i].string, 0);
  1069. if (tags[i].sub.nb_elem)
  1070. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1071. }
  1072. }
  1073. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  1074. }
  1075. static void matroska_convert_tags(AVFormatContext *s)
  1076. {
  1077. MatroskaDemuxContext *matroska = s->priv_data;
  1078. MatroskaTags *tags = matroska->tags.elem;
  1079. int i, j;
  1080. for (i=0; i < matroska->tags.nb_elem; i++) {
  1081. if (tags[i].target.attachuid) {
  1082. MatroskaAttachement *attachment = matroska->attachments.elem;
  1083. for (j=0; j<matroska->attachments.nb_elem; j++)
  1084. if (attachment[j].uid == tags[i].target.attachuid
  1085. && attachment[j].stream)
  1086. matroska_convert_tag(s, &tags[i].tag,
  1087. &attachment[j].stream->metadata, NULL);
  1088. } else if (tags[i].target.chapteruid) {
  1089. MatroskaChapter *chapter = matroska->chapters.elem;
  1090. for (j=0; j<matroska->chapters.nb_elem; j++)
  1091. if (chapter[j].uid == tags[i].target.chapteruid
  1092. && chapter[j].chapter)
  1093. matroska_convert_tag(s, &tags[i].tag,
  1094. &chapter[j].chapter->metadata, NULL);
  1095. } else if (tags[i].target.trackuid) {
  1096. MatroskaTrack *track = matroska->tracks.elem;
  1097. for (j=0; j<matroska->tracks.nb_elem; j++)
  1098. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1099. matroska_convert_tag(s, &tags[i].tag,
  1100. &track[j].stream->metadata, NULL);
  1101. } else {
  1102. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1103. tags[i].target.type);
  1104. }
  1105. }
  1106. }
  1107. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
  1108. {
  1109. EbmlList *seekhead_list = &matroska->seekhead;
  1110. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1111. uint32_t level_up = matroska->level_up;
  1112. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1113. uint32_t saved_id = matroska->current_id;
  1114. MatroskaLevel level;
  1115. int64_t offset;
  1116. int ret = 0;
  1117. if (idx >= seekhead_list->nb_elem
  1118. || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
  1119. || seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1120. return 0;
  1121. /* seek */
  1122. offset = seekhead[idx].pos + matroska->segment_start;
  1123. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1124. /* We don't want to lose our seekhead level, so we add
  1125. * a dummy. This is a crude hack. */
  1126. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1127. av_log(matroska->ctx, AV_LOG_INFO,
  1128. "Max EBML element depth (%d) reached, "
  1129. "cannot parse further.\n", EBML_MAX_DEPTH);
  1130. ret = AVERROR_INVALIDDATA;
  1131. } else {
  1132. level.start = 0;
  1133. level.length = (uint64_t)-1;
  1134. matroska->levels[matroska->num_levels] = level;
  1135. matroska->num_levels++;
  1136. matroska->current_id = 0;
  1137. ret = ebml_parse(matroska, matroska_segment, matroska);
  1138. /* remove dummy level */
  1139. while (matroska->num_levels) {
  1140. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1141. if (length == (uint64_t)-1)
  1142. break;
  1143. }
  1144. }
  1145. }
  1146. /* seek back */
  1147. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1148. matroska->level_up = level_up;
  1149. matroska->current_id = saved_id;
  1150. return ret;
  1151. }
  1152. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1153. {
  1154. EbmlList *seekhead_list = &matroska->seekhead;
  1155. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1156. int i;
  1157. // we should not do any seeking in the streaming case
  1158. if (!matroska->ctx->pb->seekable ||
  1159. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1160. return;
  1161. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1162. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1163. if (seekhead[i].pos <= before_pos)
  1164. continue;
  1165. // defer cues parsing until we actually need cue data.
  1166. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1167. matroska->cues_parsing_deferred = 1;
  1168. continue;
  1169. }
  1170. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1171. break;
  1172. }
  1173. }
  1174. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1175. EbmlList *seekhead_list = &matroska->seekhead;
  1176. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1177. EbmlList *index_list;
  1178. MatroskaIndex *index;
  1179. int index_scale = 1;
  1180. int i, j;
  1181. for (i = 0; i < seekhead_list->nb_elem; i++)
  1182. if (seekhead[i].id == MATROSKA_ID_CUES)
  1183. break;
  1184. assert(i <= seekhead_list->nb_elem);
  1185. matroska_parse_seekhead_entry(matroska, i);
  1186. index_list = &matroska->index;
  1187. index = index_list->elem;
  1188. if (index_list->nb_elem
  1189. && index[0].time > 1E14/matroska->time_scale) {
  1190. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1191. index_scale = matroska->time_scale;
  1192. }
  1193. for (i = 0; i < index_list->nb_elem; i++) {
  1194. EbmlList *pos_list = &index[i].pos;
  1195. MatroskaIndexPos *pos = pos_list->elem;
  1196. for (j = 0; j < pos_list->nb_elem; j++) {
  1197. MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
  1198. if (track && track->stream)
  1199. av_add_index_entry(track->stream,
  1200. pos[j].pos + matroska->segment_start,
  1201. index[i].time/index_scale, 0, 0,
  1202. AVINDEX_KEYFRAME);
  1203. }
  1204. }
  1205. }
  1206. static int matroska_aac_profile(char *codec_id)
  1207. {
  1208. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1209. int profile;
  1210. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1211. if (strstr(codec_id, aac_profiles[profile]))
  1212. break;
  1213. return profile + 1;
  1214. }
  1215. static int matroska_aac_sri(int samplerate)
  1216. {
  1217. int sri;
  1218. for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1219. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1220. break;
  1221. return sri;
  1222. }
  1223. static int matroska_read_header(AVFormatContext *s)
  1224. {
  1225. MatroskaDemuxContext *matroska = s->priv_data;
  1226. EbmlList *attachements_list = &matroska->attachments;
  1227. MatroskaAttachement *attachements;
  1228. EbmlList *chapters_list = &matroska->chapters;
  1229. MatroskaChapter *chapters;
  1230. MatroskaTrack *tracks;
  1231. uint64_t max_start = 0;
  1232. int64_t pos;
  1233. Ebml ebml = { 0 };
  1234. AVStream *st;
  1235. int i, j, res;
  1236. matroska->ctx = s;
  1237. /* First read the EBML header. */
  1238. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1239. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1240. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
  1241. av_log(matroska->ctx, AV_LOG_ERROR,
  1242. "EBML header using unsupported features\n"
  1243. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1244. ebml.version, ebml.doctype, ebml.doctype_version);
  1245. ebml_free(ebml_syntax, &ebml);
  1246. return AVERROR_PATCHWELCOME;
  1247. }
  1248. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1249. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1250. break;
  1251. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1252. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1253. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1254. ebml_free(ebml_syntax, &ebml);
  1255. return AVERROR_INVALIDDATA;
  1256. }
  1257. }
  1258. ebml_free(ebml_syntax, &ebml);
  1259. /* The next thing is a segment. */
  1260. pos = avio_tell(matroska->ctx->pb);
  1261. res = ebml_parse(matroska, matroska_segments, matroska);
  1262. // try resyncing until we find a EBML_STOP type element.
  1263. while (res != 1) {
  1264. res = matroska_resync(matroska, pos);
  1265. if (res < 0)
  1266. return res;
  1267. pos = avio_tell(matroska->ctx->pb);
  1268. res = ebml_parse(matroska, matroska_segment, matroska);
  1269. }
  1270. matroska_execute_seekhead(matroska);
  1271. if (!matroska->time_scale)
  1272. matroska->time_scale = 1000000;
  1273. if (matroska->duration)
  1274. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1275. * 1000 / AV_TIME_BASE;
  1276. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1277. tracks = matroska->tracks.elem;
  1278. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1279. MatroskaTrack *track = &tracks[i];
  1280. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1281. EbmlList *encodings_list = &tracks->encodings;
  1282. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1283. uint8_t *extradata = NULL;
  1284. int extradata_size = 0;
  1285. int extradata_offset = 0;
  1286. AVIOContext b;
  1287. /* Apply some sanity checks. */
  1288. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1289. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1290. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1291. av_log(matroska->ctx, AV_LOG_INFO,
  1292. "Unknown or unsupported track type %"PRIu64"\n",
  1293. track->type);
  1294. continue;
  1295. }
  1296. if (track->codec_id == NULL)
  1297. continue;
  1298. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1299. if (!track->default_duration && track->video.frame_rate > 0)
  1300. track->default_duration = 1000000000/track->video.frame_rate;
  1301. if (!track->video.display_width)
  1302. track->video.display_width = track->video.pixel_width;
  1303. if (!track->video.display_height)
  1304. track->video.display_height = track->video.pixel_height;
  1305. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1306. if (!track->audio.out_samplerate)
  1307. track->audio.out_samplerate = track->audio.samplerate;
  1308. }
  1309. if (encodings_list->nb_elem > 1) {
  1310. av_log(matroska->ctx, AV_LOG_ERROR,
  1311. "Multiple combined encodings not supported");
  1312. } else if (encodings_list->nb_elem == 1) {
  1313. if (encodings[0].type ||
  1314. (
  1315. #if CONFIG_ZLIB
  1316. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1317. #endif
  1318. #if CONFIG_BZLIB
  1319. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1320. #endif
  1321. #if CONFIG_LZO
  1322. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
  1323. #endif
  1324. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
  1325. encodings[0].scope = 0;
  1326. av_log(matroska->ctx, AV_LOG_ERROR,
  1327. "Unsupported encoding type");
  1328. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1329. uint8_t *codec_priv = track->codec_priv.data;
  1330. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1331. &track->codec_priv.size,
  1332. track);
  1333. if (ret < 0) {
  1334. track->codec_priv.data = NULL;
  1335. track->codec_priv.size = 0;
  1336. av_log(matroska->ctx, AV_LOG_ERROR,
  1337. "Failed to decode codec private data\n");
  1338. }
  1339. if (codec_priv != track->codec_priv.data)
  1340. av_free(codec_priv);
  1341. }
  1342. }
  1343. for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
  1344. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1345. strlen(ff_mkv_codec_tags[j].str))){
  1346. codec_id= ff_mkv_codec_tags[j].id;
  1347. break;
  1348. }
  1349. }
  1350. st = track->stream = avformat_new_stream(s, NULL);
  1351. if (st == NULL)
  1352. return AVERROR(ENOMEM);
  1353. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1354. && track->codec_priv.size >= 40
  1355. && track->codec_priv.data != NULL) {
  1356. track->ms_compat = 1;
  1357. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1358. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1359. extradata_offset = 40;
  1360. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1361. && track->codec_priv.size >= 14
  1362. && track->codec_priv.data != NULL) {
  1363. int ret;
  1364. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1365. 0, NULL, NULL, NULL, NULL);
  1366. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1367. if (ret < 0)
  1368. return ret;
  1369. codec_id = st->codec->codec_id;
  1370. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1371. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1372. && (track->codec_priv.size >= 86)
  1373. && (track->codec_priv.data != NULL)) {
  1374. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1375. codec_id=ff_codec_get_id(ff_codec_movvideo_tags, track->video.fourcc);
  1376. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1377. switch (track->audio.bitdepth) {
  1378. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1379. case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
  1380. case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
  1381. }
  1382. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1383. switch (track->audio.bitdepth) {
  1384. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1385. case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
  1386. case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
  1387. }
  1388. } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1389. codec_id = AV_CODEC_ID_PCM_F64LE;
  1390. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1391. int profile = matroska_aac_profile(track->codec_id);
  1392. int sri = matroska_aac_sri(track->audio.samplerate);
  1393. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1394. if (extradata == NULL)
  1395. return AVERROR(ENOMEM);
  1396. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1397. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1398. if (strstr(track->codec_id, "SBR")) {
  1399. sri = matroska_aac_sri(track->audio.out_samplerate);
  1400. extradata[2] = 0x56;
  1401. extradata[3] = 0xE5;
  1402. extradata[4] = 0x80 | (sri<<3);
  1403. extradata_size = 5;
  1404. } else
  1405. extradata_size = 2;
  1406. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
  1407. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1408. Create the "atom size", "tag", and "tag version" fields the
  1409. decoder expects manually. */
  1410. extradata_size = 12 + track->codec_priv.size;
  1411. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1412. if (extradata == NULL)
  1413. return AVERROR(ENOMEM);
  1414. AV_WB32(extradata, extradata_size);
  1415. memcpy(&extradata[4], "alac", 4);
  1416. AV_WB32(&extradata[8], 0);
  1417. memcpy(&extradata[12], track->codec_priv.data,
  1418. track->codec_priv.size);
  1419. } else if (codec_id == AV_CODEC_ID_TTA) {
  1420. extradata_size = 30;
  1421. extradata = av_mallocz(extradata_size);
  1422. if (extradata == NULL)
  1423. return AVERROR(ENOMEM);
  1424. ffio_init_context(&b, extradata, extradata_size, 1,
  1425. NULL, NULL, NULL, NULL);
  1426. avio_write(&b, "TTA1", 4);
  1427. avio_wl16(&b, 1);
  1428. avio_wl16(&b, track->audio.channels);
  1429. avio_wl16(&b, track->audio.bitdepth);
  1430. avio_wl32(&b, track->audio.out_samplerate);
  1431. avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1432. } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
  1433. codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
  1434. extradata_offset = 26;
  1435. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1436. track->audio.out_samplerate = 8000;
  1437. track->audio.channels = 1;
  1438. } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
  1439. codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
  1440. int flavor;
  1441. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1442. 0, NULL, NULL, NULL, NULL);
  1443. avio_skip(&b, 22);
  1444. flavor = avio_rb16(&b);
  1445. track->audio.coded_framesize = avio_rb32(&b);
  1446. avio_skip(&b, 12);
  1447. track->audio.sub_packet_h = avio_rb16(&b);
  1448. track->audio.frame_size = avio_rb16(&b);
  1449. track->audio.sub_packet_size = avio_rb16(&b);
  1450. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1451. if (codec_id == AV_CODEC_ID_RA_288) {
  1452. st->codec->block_align = track->audio.coded_framesize;
  1453. track->codec_priv.size = 0;
  1454. } else {
  1455. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1456. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1457. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1458. st->codec->bit_rate = sipr_bit_rate[flavor];
  1459. }
  1460. st->codec->block_align = track->audio.sub_packet_size;
  1461. extradata_offset = 78;
  1462. }
  1463. }
  1464. track->codec_priv.size -= extradata_offset;
  1465. if (codec_id == AV_CODEC_ID_NONE)
  1466. av_log(matroska->ctx, AV_LOG_INFO,
  1467. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1468. if (track->time_scale < 0.01)
  1469. track->time_scale = 1.0;
  1470. avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1471. st->codec->codec_id = codec_id;
  1472. st->start_time = 0;
  1473. if (strcmp(track->language, "und"))
  1474. av_dict_set(&st->metadata, "language", track->language, 0);
  1475. av_dict_set(&st->metadata, "title", track->name, 0);
  1476. if (track->flag_default)
  1477. st->disposition |= AV_DISPOSITION_DEFAULT;
  1478. if (track->flag_forced)
  1479. st->disposition |= AV_DISPOSITION_FORCED;
  1480. if (!st->codec->extradata) {
  1481. if(extradata){
  1482. st->codec->extradata = extradata;
  1483. st->codec->extradata_size = extradata_size;
  1484. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1485. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1486. FF_INPUT_BUFFER_PADDING_SIZE);
  1487. if(st->codec->extradata == NULL)
  1488. return AVERROR(ENOMEM);
  1489. st->codec->extradata_size = track->codec_priv.size;
  1490. memcpy(st->codec->extradata,
  1491. track->codec_priv.data + extradata_offset,
  1492. track->codec_priv.size);
  1493. }
  1494. }
  1495. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1496. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1497. st->codec->codec_tag = track->video.fourcc;
  1498. st->codec->width = track->video.pixel_width;
  1499. st->codec->height = track->video.pixel_height;
  1500. av_reduce(&st->sample_aspect_ratio.num,
  1501. &st->sample_aspect_ratio.den,
  1502. st->codec->height * track->video.display_width,
  1503. st->codec-> width * track->video.display_height,
  1504. 255);
  1505. if (st->codec->codec_id != AV_CODEC_ID_H264)
  1506. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1507. if (track->default_duration) {
  1508. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1509. 1000000000, track->default_duration, 30000);
  1510. }
  1511. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1512. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1513. st->codec->sample_rate = track->audio.out_samplerate;
  1514. st->codec->channels = track->audio.channels;
  1515. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1516. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1517. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1518. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1519. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1520. matroska->contains_ssa = 1;
  1521. }
  1522. }
  1523. attachements = attachements_list->elem;
  1524. for (j=0; j<attachements_list->nb_elem; j++) {
  1525. if (!(attachements[j].filename && attachements[j].mime &&
  1526. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1527. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1528. } else {
  1529. AVStream *st = avformat_new_stream(s, NULL);
  1530. if (st == NULL)
  1531. break;
  1532. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1533. av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
  1534. st->codec->codec_id = AV_CODEC_ID_NONE;
  1535. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1536. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1537. if(st->codec->extradata == NULL)
  1538. break;
  1539. st->codec->extradata_size = attachements[j].bin.size;
  1540. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1541. for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1542. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1543. strlen(ff_mkv_mime_tags[i].str))) {
  1544. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1545. break;
  1546. }
  1547. }
  1548. attachements[j].stream = st;
  1549. }
  1550. }
  1551. chapters = chapters_list->elem;
  1552. for (i=0; i<chapters_list->nb_elem; i++)
  1553. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1554. && (max_start==0 || chapters[i].start > max_start)) {
  1555. chapters[i].chapter =
  1556. avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1557. chapters[i].start, chapters[i].end,
  1558. chapters[i].title);
  1559. av_dict_set(&chapters[i].chapter->metadata,
  1560. "title", chapters[i].title, 0);
  1561. max_start = chapters[i].start;
  1562. }
  1563. matroska_convert_tags(s);
  1564. return 0;
  1565. }
  1566. /*
  1567. * Put one packet in an application-supplied AVPacket struct.
  1568. * Returns 0 on success or -1 on failure.
  1569. */
  1570. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1571. AVPacket *pkt)
  1572. {
  1573. if (matroska->num_packets > 0) {
  1574. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1575. av_free(matroska->packets[0]);
  1576. if (matroska->num_packets > 1) {
  1577. void *newpackets;
  1578. memmove(&matroska->packets[0], &matroska->packets[1],
  1579. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1580. newpackets = av_realloc(matroska->packets,
  1581. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1582. if (newpackets)
  1583. matroska->packets = newpackets;
  1584. } else {
  1585. av_freep(&matroska->packets);
  1586. matroska->prev_pkt = NULL;
  1587. }
  1588. matroska->num_packets--;
  1589. return 0;
  1590. }
  1591. return -1;
  1592. }
  1593. /*
  1594. * Free all packets in our internal queue.
  1595. */
  1596. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1597. {
  1598. matroska->prev_pkt = NULL;
  1599. if (matroska->packets) {
  1600. int n;
  1601. for (n = 0; n < matroska->num_packets; n++) {
  1602. av_free_packet(matroska->packets[n]);
  1603. av_free(matroska->packets[n]);
  1604. }
  1605. av_freep(&matroska->packets);
  1606. matroska->num_packets = 0;
  1607. }
  1608. }
  1609. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1610. int* buf_size, int type,
  1611. uint32_t **lace_buf, int *laces)
  1612. {
  1613. int res = 0, n, size = *buf_size;
  1614. uint8_t *data = *buf;
  1615. uint32_t *lace_size;
  1616. if (!type) {
  1617. *laces = 1;
  1618. *lace_buf = av_mallocz(sizeof(int));
  1619. if (!*lace_buf)
  1620. return AVERROR(ENOMEM);
  1621. *lace_buf[0] = size;
  1622. return 0;
  1623. }
  1624. assert(size > 0);
  1625. *laces = *data + 1;
  1626. data += 1;
  1627. size -= 1;
  1628. lace_size = av_mallocz(*laces * sizeof(int));
  1629. if (!lace_size)
  1630. return AVERROR(ENOMEM);
  1631. switch (type) {
  1632. case 0x1: /* Xiph lacing */ {
  1633. uint8_t temp;
  1634. uint32_t total = 0;
  1635. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1636. while (1) {
  1637. if (size == 0) {
  1638. res = AVERROR_EOF;
  1639. break;
  1640. }
  1641. temp = *data;
  1642. lace_size[n] += temp;
  1643. data += 1;
  1644. size -= 1;
  1645. if (temp != 0xff)
  1646. break;
  1647. }
  1648. total += lace_size[n];
  1649. }
  1650. if (size <= total) {
  1651. res = AVERROR_INVALIDDATA;
  1652. break;
  1653. }
  1654. lace_size[n] = size - total;
  1655. break;
  1656. }
  1657. case 0x2: /* fixed-size lacing */
  1658. if (size % (*laces)) {
  1659. res = AVERROR_INVALIDDATA;
  1660. break;
  1661. }
  1662. for (n = 0; n < *laces; n++)
  1663. lace_size[n] = size / *laces;
  1664. break;
  1665. case 0x3: /* EBML lacing */ {
  1666. uint64_t num;
  1667. uint64_t total;
  1668. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1669. if (n < 0) {
  1670. av_log(matroska->ctx, AV_LOG_INFO,
  1671. "EBML block data error\n");
  1672. res = n;
  1673. break;
  1674. }
  1675. data += n;
  1676. size -= n;
  1677. total = lace_size[0] = num;
  1678. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1679. int64_t snum;
  1680. int r;
  1681. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1682. if (r < 0) {
  1683. av_log(matroska->ctx, AV_LOG_INFO,
  1684. "EBML block data error\n");
  1685. res = r;
  1686. break;
  1687. }
  1688. data += r;
  1689. size -= r;
  1690. lace_size[n] = lace_size[n - 1] + snum;
  1691. total += lace_size[n];
  1692. }
  1693. if (size <= total) {
  1694. res = AVERROR_INVALIDDATA;
  1695. break;
  1696. }
  1697. lace_size[*laces - 1] = size - total;
  1698. break;
  1699. }
  1700. }
  1701. *buf = data;
  1702. *lace_buf = lace_size;
  1703. *buf_size = size;
  1704. return res;
  1705. }
  1706. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1707. MatroskaTrack *track,
  1708. AVStream *st,
  1709. uint8_t *data, int size,
  1710. uint64_t timecode, uint64_t duration,
  1711. int64_t pos)
  1712. {
  1713. int a = st->codec->block_align;
  1714. int sps = track->audio.sub_packet_size;
  1715. int cfs = track->audio.coded_framesize;
  1716. int h = track->audio.sub_packet_h;
  1717. int y = track->audio.sub_packet_cnt;
  1718. int w = track->audio.frame_size;
  1719. int x;
  1720. if (!track->audio.pkt_cnt) {
  1721. if (track->audio.sub_packet_cnt == 0)
  1722. track->audio.buf_timecode = timecode;
  1723. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1724. if (size < cfs * h / 2) {
  1725. av_log(matroska->ctx, AV_LOG_ERROR,
  1726. "Corrupt int4 RM-style audio packet size\n");
  1727. return AVERROR_INVALIDDATA;
  1728. }
  1729. for (x=0; x<h/2; x++)
  1730. memcpy(track->audio.buf+x*2*w+y*cfs,
  1731. data+x*cfs, cfs);
  1732. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1733. if (size < w) {
  1734. av_log(matroska->ctx, AV_LOG_ERROR,
  1735. "Corrupt sipr RM-style audio packet size\n");
  1736. return AVERROR_INVALIDDATA;
  1737. }
  1738. memcpy(track->audio.buf + y*w, data, w);
  1739. } else {
  1740. if (size < sps * w / sps) {
  1741. av_log(matroska->ctx, AV_LOG_ERROR,
  1742. "Corrupt generic RM-style audio packet size\n");
  1743. return AVERROR_INVALIDDATA;
  1744. }
  1745. for (x=0; x<w/sps; x++)
  1746. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1747. }
  1748. if (++track->audio.sub_packet_cnt >= h) {
  1749. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1750. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1751. track->audio.sub_packet_cnt = 0;
  1752. track->audio.pkt_cnt = h*w / a;
  1753. }
  1754. }
  1755. while (track->audio.pkt_cnt) {
  1756. AVPacket *pkt = av_mallocz(sizeof(AVPacket));
  1757. av_new_packet(pkt, a);
  1758. memcpy(pkt->data, track->audio.buf
  1759. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1760. pkt->pts = track->audio.buf_timecode;
  1761. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1762. pkt->pos = pos;
  1763. pkt->stream_index = st->index;
  1764. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1765. }
  1766. return 0;
  1767. }
  1768. /* reconstruct full wavpack blocks from mangled matroska ones */
  1769. static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
  1770. uint8_t **pdst, int *size)
  1771. {
  1772. uint8_t *dst = NULL;
  1773. int dstlen = 0;
  1774. int srclen = *size;
  1775. uint32_t samples;
  1776. uint16_t ver;
  1777. int ret, offset = 0;
  1778. if (srclen < 12 || track->stream->codec->extradata_size < 2)
  1779. return AVERROR_INVALIDDATA;
  1780. ver = AV_RL16(track->stream->codec->extradata);
  1781. samples = AV_RL32(src);
  1782. src += 4;
  1783. srclen -= 4;
  1784. while (srclen >= 8) {
  1785. int multiblock;
  1786. uint32_t blocksize;
  1787. uint8_t *tmp;
  1788. uint32_t flags = AV_RL32(src);
  1789. uint32_t crc = AV_RL32(src + 4);
  1790. src += 8;
  1791. srclen -= 8;
  1792. multiblock = (flags & 0x1800) != 0x1800;
  1793. if (multiblock) {
  1794. if (srclen < 4) {
  1795. ret = AVERROR_INVALIDDATA;
  1796. goto fail;
  1797. }
  1798. blocksize = AV_RL32(src);
  1799. src += 4;
  1800. srclen -= 4;
  1801. } else
  1802. blocksize = srclen;
  1803. if (blocksize > srclen) {
  1804. ret = AVERROR_INVALIDDATA;
  1805. goto fail;
  1806. }
  1807. tmp = av_realloc(dst, dstlen + blocksize + 32);
  1808. if (!tmp) {
  1809. ret = AVERROR(ENOMEM);
  1810. goto fail;
  1811. }
  1812. dst = tmp;
  1813. dstlen += blocksize + 32;
  1814. AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
  1815. AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
  1816. AV_WL16(dst + offset + 8, ver); // version
  1817. AV_WL16(dst + offset + 10, 0); // track/index_no
  1818. AV_WL32(dst + offset + 12, 0); // total samples
  1819. AV_WL32(dst + offset + 16, 0); // block index
  1820. AV_WL32(dst + offset + 20, samples); // number of samples
  1821. AV_WL32(dst + offset + 24, flags); // flags
  1822. AV_WL32(dst + offset + 28, crc); // crc
  1823. memcpy (dst + offset + 32, src, blocksize); // block data
  1824. src += blocksize;
  1825. srclen -= blocksize;
  1826. offset += blocksize + 32;
  1827. }
  1828. *pdst = dst;
  1829. *size = dstlen;
  1830. return 0;
  1831. fail:
  1832. av_freep(&dst);
  1833. return ret;
  1834. }
  1835. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  1836. MatroskaTrack *track,
  1837. AVStream *st,
  1838. uint8_t *data, int pkt_size,
  1839. uint64_t timecode, uint64_t duration,
  1840. int64_t pos, int is_keyframe)
  1841. {
  1842. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1843. uint8_t *pkt_data = data;
  1844. int offset = 0, res;
  1845. AVPacket *pkt;
  1846. if (encodings && encodings->scope & 1) {
  1847. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  1848. if (res < 0)
  1849. return res;
  1850. }
  1851. if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
  1852. uint8_t *wv_data;
  1853. res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
  1854. if (res < 0) {
  1855. av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
  1856. goto fail;
  1857. }
  1858. if (pkt_data != data)
  1859. av_freep(&pkt_data);
  1860. pkt_data = wv_data;
  1861. }
  1862. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  1863. offset = 8;
  1864. pkt = av_mallocz(sizeof(AVPacket));
  1865. /* XXX: prevent data copy... */
  1866. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  1867. av_free(pkt);
  1868. return AVERROR(ENOMEM);
  1869. }
  1870. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  1871. uint8_t *buf = pkt->data;
  1872. bytestream_put_be32(&buf, pkt_size);
  1873. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  1874. }
  1875. memcpy(pkt->data + offset, pkt_data, pkt_size);
  1876. if (pkt_data != data)
  1877. av_free(pkt_data);
  1878. pkt->flags = is_keyframe;
  1879. pkt->stream_index = st->index;
  1880. if (track->ms_compat)
  1881. pkt->dts = timecode;
  1882. else
  1883. pkt->pts = timecode;
  1884. pkt->pos = pos;
  1885. if (st->codec->codec_id == AV_CODEC_ID_TEXT)
  1886. pkt->convergence_duration = duration;
  1887. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1888. pkt->duration = duration;
  1889. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1890. matroska_fix_ass_packet(matroska, pkt, duration);
  1891. if (matroska->prev_pkt &&
  1892. timecode != AV_NOPTS_VALUE &&
  1893. matroska->prev_pkt->pts == timecode &&
  1894. matroska->prev_pkt->stream_index == st->index &&
  1895. st->codec->codec_id == AV_CODEC_ID_SSA)
  1896. matroska_merge_packets(matroska->prev_pkt, pkt);
  1897. else {
  1898. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1899. matroska->prev_pkt = pkt;
  1900. }
  1901. return 0;
  1902. fail:
  1903. if (pkt_data != data)
  1904. av_freep(&pkt_data);
  1905. return res;
  1906. }
  1907. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1908. int size, int64_t pos, uint64_t cluster_time,
  1909. uint64_t block_duration, int is_keyframe,
  1910. int64_t cluster_pos)
  1911. {
  1912. uint64_t timecode = AV_NOPTS_VALUE;
  1913. MatroskaTrack *track;
  1914. int res = 0;
  1915. AVStream *st;
  1916. int16_t block_time;
  1917. uint32_t *lace_size = NULL;
  1918. int n, flags, laces = 0;
  1919. uint64_t num, duration;
  1920. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1921. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1922. return n;
  1923. }
  1924. data += n;
  1925. size -= n;
  1926. track = matroska_find_track_by_num(matroska, num);
  1927. if (!track || !track->stream) {
  1928. av_log(matroska->ctx, AV_LOG_INFO,
  1929. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1930. return AVERROR_INVALIDDATA;
  1931. } else if (size <= 3)
  1932. return 0;
  1933. st = track->stream;
  1934. if (st->discard >= AVDISCARD_ALL)
  1935. return res;
  1936. block_time = AV_RB16(data);
  1937. data += 2;
  1938. flags = *data++;
  1939. size -= 3;
  1940. if (is_keyframe == -1)
  1941. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1942. if (cluster_time != (uint64_t)-1
  1943. && (block_time >= 0 || cluster_time >= -block_time)) {
  1944. timecode = cluster_time + block_time;
  1945. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1946. && timecode < track->end_timecode)
  1947. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1948. if (is_keyframe)
  1949. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1950. }
  1951. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1952. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1953. return res;
  1954. matroska->skip_to_keyframe = 0;
  1955. }
  1956. res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
  1957. &lace_size, &laces);
  1958. if (res)
  1959. goto end;
  1960. if (block_duration != AV_NOPTS_VALUE) {
  1961. duration = block_duration / laces;
  1962. if (block_duration != duration * laces) {
  1963. av_log(matroska->ctx, AV_LOG_WARNING,
  1964. "Incorrect block_duration, possibly corrupted container");
  1965. }
  1966. } else {
  1967. duration = track->default_duration / matroska->time_scale;
  1968. block_duration = duration * laces;
  1969. }
  1970. if (timecode != AV_NOPTS_VALUE)
  1971. track->end_timecode =
  1972. FFMAX(track->end_timecode, timecode + block_duration);
  1973. for (n = 0; n < laces; n++) {
  1974. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  1975. st->codec->codec_id == AV_CODEC_ID_COOK ||
  1976. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  1977. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  1978. st->codec->block_align && track->audio.sub_packet_size) {
  1979. res = matroska_parse_rm_audio(matroska, track, st, data,
  1980. lace_size[n],
  1981. timecode, duration, pos);
  1982. if (res)
  1983. goto end;
  1984. } else {
  1985. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  1986. timecode, duration,
  1987. pos, !n? is_keyframe : 0);
  1988. if (res)
  1989. goto end;
  1990. }
  1991. if (timecode != AV_NOPTS_VALUE)
  1992. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1993. data += lace_size[n];
  1994. }
  1995. end:
  1996. av_free(lace_size);
  1997. return res;
  1998. }
  1999. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  2000. {
  2001. EbmlList *blocks_list;
  2002. MatroskaBlock *blocks;
  2003. int i, res;
  2004. res = ebml_parse(matroska,
  2005. matroska_cluster_incremental_parsing,
  2006. &matroska->current_cluster);
  2007. if (res == 1) {
  2008. /* New Cluster */
  2009. if (matroska->current_cluster_pos)
  2010. ebml_level_end(matroska);
  2011. ebml_free(matroska_cluster, &matroska->current_cluster);
  2012. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2013. matroska->current_cluster_num_blocks = 0;
  2014. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2015. matroska->prev_pkt = NULL;
  2016. /* sizeof the ID which was already read */
  2017. if (matroska->current_id)
  2018. matroska->current_cluster_pos -= 4;
  2019. res = ebml_parse(matroska,
  2020. matroska_clusters_incremental,
  2021. &matroska->current_cluster);
  2022. /* Try parsing the block again. */
  2023. if (res == 1)
  2024. res = ebml_parse(matroska,
  2025. matroska_cluster_incremental_parsing,
  2026. &matroska->current_cluster);
  2027. }
  2028. if (!res &&
  2029. matroska->current_cluster_num_blocks <
  2030. matroska->current_cluster.blocks.nb_elem) {
  2031. blocks_list = &matroska->current_cluster.blocks;
  2032. blocks = blocks_list->elem;
  2033. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2034. i = blocks_list->nb_elem - 1;
  2035. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2036. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2037. if (!blocks[i].non_simple)
  2038. blocks[i].duration = AV_NOPTS_VALUE;
  2039. res = matroska_parse_block(matroska,
  2040. blocks[i].bin.data, blocks[i].bin.size,
  2041. blocks[i].bin.pos,
  2042. matroska->current_cluster.timecode,
  2043. blocks[i].duration, is_keyframe,
  2044. matroska->current_cluster_pos);
  2045. }
  2046. }
  2047. if (res < 0) matroska->done = 1;
  2048. return res;
  2049. }
  2050. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2051. {
  2052. MatroskaCluster cluster = { 0 };
  2053. EbmlList *blocks_list;
  2054. MatroskaBlock *blocks;
  2055. int i, res;
  2056. int64_t pos;
  2057. if (!matroska->contains_ssa)
  2058. return matroska_parse_cluster_incremental(matroska);
  2059. pos = avio_tell(matroska->ctx->pb);
  2060. matroska->prev_pkt = NULL;
  2061. if (matroska->current_id)
  2062. pos -= 4; /* sizeof the ID which was already read */
  2063. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2064. blocks_list = &cluster.blocks;
  2065. blocks = blocks_list->elem;
  2066. for (i=0; i<blocks_list->nb_elem && !res; i++)
  2067. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2068. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2069. if (!blocks[i].non_simple)
  2070. blocks[i].duration = AV_NOPTS_VALUE;
  2071. res=matroska_parse_block(matroska,
  2072. blocks[i].bin.data, blocks[i].bin.size,
  2073. blocks[i].bin.pos, cluster.timecode,
  2074. blocks[i].duration, is_keyframe,
  2075. pos);
  2076. }
  2077. ebml_free(matroska_cluster, &cluster);
  2078. return res;
  2079. }
  2080. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2081. {
  2082. MatroskaDemuxContext *matroska = s->priv_data;
  2083. int ret = 0;
  2084. while (!ret && matroska_deliver_packet(matroska, pkt)) {
  2085. int64_t pos = avio_tell(matroska->ctx->pb);
  2086. if (matroska->done)
  2087. return AVERROR_EOF;
  2088. if (matroska_parse_cluster(matroska) < 0)
  2089. ret = matroska_resync(matroska, pos);
  2090. }
  2091. if (ret == AVERROR_INVALIDDATA && pkt->data) {
  2092. pkt->flags |= AV_PKT_FLAG_CORRUPT;
  2093. return 0;
  2094. }
  2095. return ret;
  2096. }
  2097. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2098. int64_t timestamp, int flags)
  2099. {
  2100. MatroskaDemuxContext *matroska = s->priv_data;
  2101. MatroskaTrack *tracks = matroska->tracks.elem;
  2102. AVStream *st = s->streams[stream_index];
  2103. int i, index, index_sub, index_min;
  2104. /* Parse the CUES now since we need the index data to seek. */
  2105. if (matroska->cues_parsing_deferred) {
  2106. matroska_parse_cues(matroska);
  2107. matroska->cues_parsing_deferred = 0;
  2108. }
  2109. if (!st->nb_index_entries)
  2110. return 0;
  2111. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2112. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2113. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  2114. matroska->current_id = 0;
  2115. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2116. matroska_clear_queue(matroska);
  2117. if (matroska_parse_cluster(matroska) < 0)
  2118. break;
  2119. }
  2120. }
  2121. matroska_clear_queue(matroska);
  2122. if (index < 0)
  2123. return 0;
  2124. index_min = index;
  2125. for (i=0; i < matroska->tracks.nb_elem; i++) {
  2126. tracks[i].audio.pkt_cnt = 0;
  2127. tracks[i].audio.sub_packet_cnt = 0;
  2128. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2129. tracks[i].end_timecode = 0;
  2130. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  2131. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  2132. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  2133. if (index_sub >= 0
  2134. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  2135. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  2136. index_min = index_sub;
  2137. }
  2138. }
  2139. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2140. matroska->current_id = 0;
  2141. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2142. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2143. matroska->done = 0;
  2144. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2145. return 0;
  2146. }
  2147. static int matroska_read_close(AVFormatContext *s)
  2148. {
  2149. MatroskaDemuxContext *matroska = s->priv_data;
  2150. MatroskaTrack *tracks = matroska->tracks.elem;
  2151. int n;
  2152. matroska_clear_queue(matroska);
  2153. for (n=0; n < matroska->tracks.nb_elem; n++)
  2154. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2155. av_free(tracks[n].audio.buf);
  2156. ebml_free(matroska_cluster, &matroska->current_cluster);
  2157. ebml_free(matroska_segment, matroska);
  2158. return 0;
  2159. }
  2160. AVInputFormat ff_matroska_demuxer = {
  2161. .name = "matroska,webm",
  2162. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2163. .priv_data_size = sizeof(MatroskaDemuxContext),
  2164. .read_probe = matroska_probe,
  2165. .read_header = matroska_read_header,
  2166. .read_packet = matroska_read_packet,
  2167. .read_close = matroska_read_close,
  2168. .read_seek = matroska_read_seek,
  2169. };