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.

2297 lines
80KB

  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. { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
  439. { 0 }
  440. };
  441. static EbmlSyntax matroska_cluster[] = {
  442. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  443. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  444. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  445. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  446. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  447. { 0 }
  448. };
  449. static EbmlSyntax matroska_clusters[] = {
  450. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
  451. { MATROSKA_ID_INFO, EBML_NONE },
  452. { MATROSKA_ID_CUES, EBML_NONE },
  453. { MATROSKA_ID_TAGS, EBML_NONE },
  454. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  455. { 0 }
  456. };
  457. static EbmlSyntax matroska_cluster_incremental_parsing[] = {
  458. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  459. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  460. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  461. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  462. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  463. { MATROSKA_ID_INFO, EBML_NONE },
  464. { MATROSKA_ID_CUES, EBML_NONE },
  465. { MATROSKA_ID_TAGS, EBML_NONE },
  466. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  467. { MATROSKA_ID_CLUSTER, EBML_STOP },
  468. { 0 }
  469. };
  470. static EbmlSyntax matroska_cluster_incremental[] = {
  471. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  472. { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
  473. { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
  474. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  475. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  476. { 0 }
  477. };
  478. static EbmlSyntax matroska_clusters_incremental[] = {
  479. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
  480. { MATROSKA_ID_INFO, EBML_NONE },
  481. { MATROSKA_ID_CUES, EBML_NONE },
  482. { MATROSKA_ID_TAGS, EBML_NONE },
  483. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  484. { 0 }
  485. };
  486. static const char *const matroska_doctypes[] = { "matroska", "webm" };
  487. /*
  488. * Return: Whether we reached the end of a level in the hierarchy or not.
  489. */
  490. static int ebml_level_end(MatroskaDemuxContext *matroska)
  491. {
  492. AVIOContext *pb = matroska->ctx->pb;
  493. int64_t pos = avio_tell(pb);
  494. if (matroska->num_levels > 0) {
  495. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  496. if (pos - level->start >= level->length || matroska->current_id) {
  497. matroska->num_levels--;
  498. return 1;
  499. }
  500. }
  501. return 0;
  502. }
  503. /*
  504. * Read: an "EBML number", which is defined as a variable-length
  505. * array of bytes. The first byte indicates the length by giving a
  506. * number of 0-bits followed by a one. The position of the first
  507. * "one" bit inside the first byte indicates the length of this
  508. * number.
  509. * Returns: number of bytes read, < 0 on error
  510. */
  511. static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
  512. int max_size, uint64_t *number)
  513. {
  514. int read = 1, n = 1;
  515. uint64_t total = 0;
  516. /* The first byte tells us the length in bytes - avio_r8() can normally
  517. * return 0, but since that's not a valid first ebmlID byte, we can
  518. * use it safely here to catch EOS. */
  519. if (!(total = avio_r8(pb))) {
  520. /* we might encounter EOS here */
  521. if (!pb->eof_reached) {
  522. int64_t pos = avio_tell(pb);
  523. av_log(matroska->ctx, AV_LOG_ERROR,
  524. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  525. pos, pos);
  526. return pb->error ? pb->error : AVERROR(EIO);
  527. }
  528. return AVERROR_EOF;
  529. }
  530. /* get the length of the EBML number */
  531. read = 8 - ff_log2_tab[total];
  532. if (read > max_size) {
  533. int64_t pos = avio_tell(pb) - 1;
  534. av_log(matroska->ctx, AV_LOG_ERROR,
  535. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  536. (uint8_t) total, pos, pos);
  537. return AVERROR_INVALIDDATA;
  538. }
  539. /* read out length */
  540. total ^= 1 << ff_log2_tab[total];
  541. while (n++ < read)
  542. total = (total << 8) | avio_r8(pb);
  543. *number = total;
  544. return read;
  545. }
  546. /**
  547. * Read a EBML length value.
  548. * This needs special handling for the "unknown length" case which has multiple
  549. * encodings.
  550. */
  551. static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
  552. uint64_t *number)
  553. {
  554. int res = ebml_read_num(matroska, pb, 8, number);
  555. if (res > 0 && *number + 1 == 1ULL << (7 * res))
  556. *number = 0xffffffffffffffULL;
  557. return res;
  558. }
  559. /*
  560. * Read the next element as an unsigned int.
  561. * 0 is success, < 0 is failure.
  562. */
  563. static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
  564. {
  565. int n = 0;
  566. if (size > 8)
  567. return AVERROR_INVALIDDATA;
  568. /* big-endian ordering; build up number */
  569. *num = 0;
  570. while (n++ < size)
  571. *num = (*num << 8) | avio_r8(pb);
  572. return 0;
  573. }
  574. /*
  575. * Read the next element as a float.
  576. * 0 is success, < 0 is failure.
  577. */
  578. static int ebml_read_float(AVIOContext *pb, int size, double *num)
  579. {
  580. if (size == 0) {
  581. *num = 0;
  582. } else if (size == 4) {
  583. *num = av_int2float(avio_rb32(pb));
  584. } else if (size == 8){
  585. *num = av_int2double(avio_rb64(pb));
  586. } else
  587. return AVERROR_INVALIDDATA;
  588. return 0;
  589. }
  590. /*
  591. * Read the next element as an ASCII string.
  592. * 0 is success, < 0 is failure.
  593. */
  594. static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
  595. {
  596. char *res;
  597. /* EBML strings are usually not 0-terminated, so we allocate one
  598. * byte more, read the string and NULL-terminate it ourselves. */
  599. if (!(res = av_malloc(size + 1)))
  600. return AVERROR(ENOMEM);
  601. if (avio_read(pb, (uint8_t *) res, size) != size) {
  602. av_free(res);
  603. return AVERROR(EIO);
  604. }
  605. (res)[size] = '\0';
  606. av_free(*str);
  607. *str = res;
  608. return 0;
  609. }
  610. /*
  611. * Read the next element as binary data.
  612. * 0 is success, < 0 is failure.
  613. */
  614. static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  615. {
  616. av_free(bin->data);
  617. if (!(bin->data = av_malloc(length)))
  618. return AVERROR(ENOMEM);
  619. bin->size = length;
  620. bin->pos = avio_tell(pb);
  621. if (avio_read(pb, bin->data, length) != length) {
  622. av_freep(&bin->data);
  623. return AVERROR(EIO);
  624. }
  625. return 0;
  626. }
  627. /*
  628. * Read the next element, but only the header. The contents
  629. * are supposed to be sub-elements which can be read separately.
  630. * 0 is success, < 0 is failure.
  631. */
  632. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  633. {
  634. AVIOContext *pb = matroska->ctx->pb;
  635. MatroskaLevel *level;
  636. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  637. av_log(matroska->ctx, AV_LOG_ERROR,
  638. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  639. return AVERROR(ENOSYS);
  640. }
  641. level = &matroska->levels[matroska->num_levels++];
  642. level->start = avio_tell(pb);
  643. level->length = length;
  644. return 0;
  645. }
  646. /*
  647. * Read signed/unsigned "EBML" numbers.
  648. * Return: number of bytes processed, < 0 on error
  649. */
  650. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  651. uint8_t *data, uint32_t size, uint64_t *num)
  652. {
  653. AVIOContext pb;
  654. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  655. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  656. }
  657. /*
  658. * Same as above, but signed.
  659. */
  660. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  661. uint8_t *data, uint32_t size, int64_t *num)
  662. {
  663. uint64_t unum;
  664. int res;
  665. /* read as unsigned number first */
  666. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  667. return res;
  668. /* make signed (weird way) */
  669. *num = unum - ((1LL << (7*res - 1)) - 1);
  670. return res;
  671. }
  672. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  673. EbmlSyntax *syntax, void *data);
  674. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  675. uint32_t id, void *data)
  676. {
  677. int i;
  678. for (i=0; syntax[i].id; i++)
  679. if (id == syntax[i].id)
  680. break;
  681. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  682. matroska->num_levels > 0 &&
  683. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  684. return 0; // we reached the end of an unknown size cluster
  685. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
  686. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  687. if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
  688. return AVERROR_INVALIDDATA;
  689. }
  690. return ebml_parse_elem(matroska, &syntax[i], data);
  691. }
  692. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  693. void *data)
  694. {
  695. if (!matroska->current_id) {
  696. uint64_t id;
  697. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  698. if (res < 0)
  699. return res;
  700. matroska->current_id = id | 1 << 7*res;
  701. }
  702. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  703. }
  704. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  705. void *data)
  706. {
  707. int i, res = 0;
  708. for (i=0; syntax[i].id; i++)
  709. switch (syntax[i].type) {
  710. case EBML_UINT:
  711. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  712. break;
  713. case EBML_FLOAT:
  714. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  715. break;
  716. case EBML_STR:
  717. case EBML_UTF8:
  718. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  719. break;
  720. }
  721. while (!res && !ebml_level_end(matroska))
  722. res = ebml_parse(matroska, syntax, data);
  723. return res;
  724. }
  725. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  726. EbmlSyntax *syntax, void *data)
  727. {
  728. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  729. [EBML_UINT] = 8,
  730. [EBML_FLOAT] = 8,
  731. // max. 16 MB for strings
  732. [EBML_STR] = 0x1000000,
  733. [EBML_UTF8] = 0x1000000,
  734. // max. 256 MB for binary data
  735. [EBML_BIN] = 0x10000000,
  736. // no limits for anything else
  737. };
  738. AVIOContext *pb = matroska->ctx->pb;
  739. uint32_t id = syntax->id;
  740. uint64_t length;
  741. int res;
  742. void *newelem;
  743. data = (char *)data + syntax->data_offset;
  744. if (syntax->list_elem_size) {
  745. EbmlList *list = data;
  746. newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  747. if (!newelem)
  748. return AVERROR(ENOMEM);
  749. list->elem = newelem;
  750. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  751. memset(data, 0, syntax->list_elem_size);
  752. list->nb_elem++;
  753. }
  754. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  755. matroska->current_id = 0;
  756. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  757. return res;
  758. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  759. av_log(matroska->ctx, AV_LOG_ERROR,
  760. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  761. length, max_lengths[syntax->type], syntax->type);
  762. return AVERROR_INVALIDDATA;
  763. }
  764. }
  765. switch (syntax->type) {
  766. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  767. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  768. case EBML_STR:
  769. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  770. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  771. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  772. return res;
  773. if (id == MATROSKA_ID_SEGMENT)
  774. matroska->segment_start = avio_tell(matroska->ctx->pb);
  775. return ebml_parse_nest(matroska, syntax->def.n, data);
  776. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  777. case EBML_STOP: return 1;
  778. default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
  779. }
  780. if (res == AVERROR_INVALIDDATA)
  781. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  782. else if (res == AVERROR(EIO))
  783. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  784. return res;
  785. }
  786. static void ebml_free(EbmlSyntax *syntax, void *data)
  787. {
  788. int i, j;
  789. for (i=0; syntax[i].id; i++) {
  790. void *data_off = (char *)data + syntax[i].data_offset;
  791. switch (syntax[i].type) {
  792. case EBML_STR:
  793. case EBML_UTF8: av_freep(data_off); break;
  794. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  795. case EBML_NEST:
  796. if (syntax[i].list_elem_size) {
  797. EbmlList *list = data_off;
  798. char *ptr = list->elem;
  799. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  800. ebml_free(syntax[i].def.n, ptr);
  801. av_free(list->elem);
  802. } else
  803. ebml_free(syntax[i].def.n, data_off);
  804. default: break;
  805. }
  806. }
  807. }
  808. /*
  809. * Autodetecting...
  810. */
  811. static int matroska_probe(AVProbeData *p)
  812. {
  813. uint64_t total = 0;
  814. int len_mask = 0x80, size = 1, n = 1, i;
  815. /* EBML header? */
  816. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  817. return 0;
  818. /* length of header */
  819. total = p->buf[4];
  820. while (size <= 8 && !(total & len_mask)) {
  821. size++;
  822. len_mask >>= 1;
  823. }
  824. if (size > 8)
  825. return 0;
  826. total &= (len_mask - 1);
  827. while (n < size)
  828. total = (total << 8) | p->buf[4 + n++];
  829. /* Does the probe data contain the whole header? */
  830. if (p->buf_size < 4 + size + total)
  831. return 0;
  832. /* The header should contain a known document type. For now,
  833. * we don't parse the whole header but simply check for the
  834. * availability of that array of characters inside the header.
  835. * Not fully fool-proof, but good enough. */
  836. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  837. int probelen = strlen(matroska_doctypes[i]);
  838. if (total < probelen)
  839. continue;
  840. for (n = 4+size; n <= 4+size+total-probelen; n++)
  841. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  842. return AVPROBE_SCORE_MAX;
  843. }
  844. // probably valid EBML header but no recognized doctype
  845. return AVPROBE_SCORE_MAX/2;
  846. }
  847. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  848. int num)
  849. {
  850. MatroskaTrack *tracks = matroska->tracks.elem;
  851. int i;
  852. for (i=0; i < matroska->tracks.nb_elem; i++)
  853. if (tracks[i].num == num)
  854. return &tracks[i];
  855. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  856. return NULL;
  857. }
  858. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  859. MatroskaTrack *track)
  860. {
  861. MatroskaTrackEncoding *encodings = track->encodings.elem;
  862. uint8_t* data = *buf;
  863. int isize = *buf_size;
  864. uint8_t* pkt_data = NULL;
  865. uint8_t av_unused *newpktdata;
  866. int pkt_size = isize;
  867. int result = 0;
  868. int olen;
  869. if (pkt_size >= 10000000)
  870. return AVERROR_INVALIDDATA;
  871. switch (encodings[0].compression.algo) {
  872. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
  873. int header_size = encodings[0].compression.settings.size;
  874. uint8_t *header = encodings[0].compression.settings.data;
  875. if (!header_size)
  876. return 0;
  877. pkt_size = isize + header_size;
  878. pkt_data = av_malloc(pkt_size);
  879. if (!pkt_data)
  880. return AVERROR(ENOMEM);
  881. memcpy(pkt_data, header, header_size);
  882. memcpy(pkt_data + header_size, data, isize);
  883. break;
  884. }
  885. #if CONFIG_LZO
  886. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  887. do {
  888. olen = pkt_size *= 3;
  889. newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
  890. if (!newpktdata) {
  891. result = AVERROR(ENOMEM);
  892. goto failed;
  893. }
  894. pkt_data = newpktdata;
  895. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  896. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  897. if (result) {
  898. result = AVERROR_INVALIDDATA;
  899. goto failed;
  900. }
  901. pkt_size -= olen;
  902. break;
  903. #endif
  904. #if CONFIG_ZLIB
  905. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  906. z_stream zstream = {0};
  907. if (inflateInit(&zstream) != Z_OK)
  908. return -1;
  909. zstream.next_in = data;
  910. zstream.avail_in = isize;
  911. do {
  912. pkt_size *= 3;
  913. newpktdata = av_realloc(pkt_data, pkt_size);
  914. if (!newpktdata) {
  915. inflateEnd(&zstream);
  916. goto failed;
  917. }
  918. pkt_data = newpktdata;
  919. zstream.avail_out = pkt_size - zstream.total_out;
  920. zstream.next_out = pkt_data + zstream.total_out;
  921. result = inflate(&zstream, Z_NO_FLUSH);
  922. } while (result==Z_OK && pkt_size<10000000);
  923. pkt_size = zstream.total_out;
  924. inflateEnd(&zstream);
  925. if (result != Z_STREAM_END) {
  926. if (result == Z_MEM_ERROR)
  927. result = AVERROR(ENOMEM);
  928. else
  929. result = AVERROR_INVALIDDATA;
  930. goto failed;
  931. }
  932. break;
  933. }
  934. #endif
  935. #if CONFIG_BZLIB
  936. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  937. bz_stream bzstream = {0};
  938. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  939. return -1;
  940. bzstream.next_in = data;
  941. bzstream.avail_in = isize;
  942. do {
  943. pkt_size *= 3;
  944. newpktdata = av_realloc(pkt_data, pkt_size);
  945. if (!newpktdata) {
  946. BZ2_bzDecompressEnd(&bzstream);
  947. goto failed;
  948. }
  949. pkt_data = newpktdata;
  950. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  951. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  952. result = BZ2_bzDecompress(&bzstream);
  953. } while (result==BZ_OK && pkt_size<10000000);
  954. pkt_size = bzstream.total_out_lo32;
  955. BZ2_bzDecompressEnd(&bzstream);
  956. if (result != BZ_STREAM_END) {
  957. if (result == BZ_MEM_ERROR)
  958. result = AVERROR(ENOMEM);
  959. else
  960. result = AVERROR_INVALIDDATA;
  961. goto failed;
  962. }
  963. break;
  964. }
  965. #endif
  966. default:
  967. return AVERROR_INVALIDDATA;
  968. }
  969. *buf = pkt_data;
  970. *buf_size = pkt_size;
  971. return 0;
  972. failed:
  973. av_free(pkt_data);
  974. return result;
  975. }
  976. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  977. AVPacket *pkt, uint64_t display_duration)
  978. {
  979. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  980. for (; *ptr!=',' && ptr<end-1; ptr++);
  981. if (*ptr == ',')
  982. layer = ++ptr;
  983. for (; *ptr!=',' && ptr<end-1; ptr++);
  984. if (*ptr == ',') {
  985. int64_t end_pts = pkt->pts + display_duration;
  986. int sc = matroska->time_scale * pkt->pts / 10000000;
  987. int ec = matroska->time_scale * end_pts / 10000000;
  988. int sh, sm, ss, eh, em, es, len;
  989. sh = sc/360000; sc -= 360000*sh;
  990. sm = sc/ 6000; sc -= 6000*sm;
  991. ss = sc/ 100; sc -= 100*ss;
  992. eh = ec/360000; ec -= 360000*eh;
  993. em = ec/ 6000; ec -= 6000*em;
  994. es = ec/ 100; ec -= 100*es;
  995. *ptr++ = '\0';
  996. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  997. if (!(line = av_malloc(len)))
  998. return;
  999. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  1000. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  1001. av_free(pkt->data);
  1002. pkt->data = line;
  1003. pkt->size = strlen(line);
  1004. }
  1005. }
  1006. static int matroska_merge_packets(AVPacket *out, AVPacket *in)
  1007. {
  1008. int old_size = out->size;
  1009. int ret = av_grow_packet(out, in->size);
  1010. if (ret < 0)
  1011. return ret;
  1012. memcpy(out->data + old_size, in->data, in->size);
  1013. av_free_packet(in);
  1014. av_free(in);
  1015. return 0;
  1016. }
  1017. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  1018. AVDictionary **metadata, char *prefix)
  1019. {
  1020. MatroskaTag *tags = list->elem;
  1021. char key[1024];
  1022. int i;
  1023. for (i=0; i < list->nb_elem; i++) {
  1024. const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  1025. if (!tags[i].name) {
  1026. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  1027. continue;
  1028. }
  1029. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  1030. else av_strlcpy(key, tags[i].name, sizeof(key));
  1031. if (tags[i].def || !lang) {
  1032. av_dict_set(metadata, key, tags[i].string, 0);
  1033. if (tags[i].sub.nb_elem)
  1034. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1035. }
  1036. if (lang) {
  1037. av_strlcat(key, "-", sizeof(key));
  1038. av_strlcat(key, lang, sizeof(key));
  1039. av_dict_set(metadata, key, tags[i].string, 0);
  1040. if (tags[i].sub.nb_elem)
  1041. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1042. }
  1043. }
  1044. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  1045. }
  1046. static void matroska_convert_tags(AVFormatContext *s)
  1047. {
  1048. MatroskaDemuxContext *matroska = s->priv_data;
  1049. MatroskaTags *tags = matroska->tags.elem;
  1050. int i, j;
  1051. for (i=0; i < matroska->tags.nb_elem; i++) {
  1052. if (tags[i].target.attachuid) {
  1053. MatroskaAttachement *attachment = matroska->attachments.elem;
  1054. for (j=0; j<matroska->attachments.nb_elem; j++)
  1055. if (attachment[j].uid == tags[i].target.attachuid
  1056. && attachment[j].stream)
  1057. matroska_convert_tag(s, &tags[i].tag,
  1058. &attachment[j].stream->metadata, NULL);
  1059. } else if (tags[i].target.chapteruid) {
  1060. MatroskaChapter *chapter = matroska->chapters.elem;
  1061. for (j=0; j<matroska->chapters.nb_elem; j++)
  1062. if (chapter[j].uid == tags[i].target.chapteruid
  1063. && chapter[j].chapter)
  1064. matroska_convert_tag(s, &tags[i].tag,
  1065. &chapter[j].chapter->metadata, NULL);
  1066. } else if (tags[i].target.trackuid) {
  1067. MatroskaTrack *track = matroska->tracks.elem;
  1068. for (j=0; j<matroska->tracks.nb_elem; j++)
  1069. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1070. matroska_convert_tag(s, &tags[i].tag,
  1071. &track[j].stream->metadata, NULL);
  1072. } else {
  1073. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1074. tags[i].target.type);
  1075. }
  1076. }
  1077. }
  1078. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
  1079. {
  1080. EbmlList *seekhead_list = &matroska->seekhead;
  1081. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1082. uint32_t level_up = matroska->level_up;
  1083. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1084. uint32_t saved_id = matroska->current_id;
  1085. MatroskaLevel level;
  1086. int64_t offset;
  1087. int ret = 0;
  1088. if (idx >= seekhead_list->nb_elem
  1089. || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
  1090. || seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1091. return 0;
  1092. /* seek */
  1093. offset = seekhead[idx].pos + matroska->segment_start;
  1094. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1095. /* We don't want to lose our seekhead level, so we add
  1096. * a dummy. This is a crude hack. */
  1097. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1098. av_log(matroska->ctx, AV_LOG_INFO,
  1099. "Max EBML element depth (%d) reached, "
  1100. "cannot parse further.\n", EBML_MAX_DEPTH);
  1101. ret = AVERROR_INVALIDDATA;
  1102. } else {
  1103. level.start = 0;
  1104. level.length = (uint64_t)-1;
  1105. matroska->levels[matroska->num_levels] = level;
  1106. matroska->num_levels++;
  1107. matroska->current_id = 0;
  1108. ret = ebml_parse(matroska, matroska_segment, matroska);
  1109. /* remove dummy level */
  1110. while (matroska->num_levels) {
  1111. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1112. if (length == (uint64_t)-1)
  1113. break;
  1114. }
  1115. }
  1116. }
  1117. /* seek back */
  1118. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1119. matroska->level_up = level_up;
  1120. matroska->current_id = saved_id;
  1121. return ret;
  1122. }
  1123. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1124. {
  1125. EbmlList *seekhead_list = &matroska->seekhead;
  1126. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1127. int i;
  1128. // we should not do any seeking in the streaming case
  1129. if (!matroska->ctx->pb->seekable ||
  1130. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1131. return;
  1132. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1133. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1134. if (seekhead[i].pos <= before_pos)
  1135. continue;
  1136. // defer cues parsing until we actually need cue data.
  1137. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1138. matroska->cues_parsing_deferred = 1;
  1139. continue;
  1140. }
  1141. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1142. break;
  1143. }
  1144. }
  1145. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1146. EbmlList *seekhead_list = &matroska->seekhead;
  1147. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1148. EbmlList *index_list;
  1149. MatroskaIndex *index;
  1150. int index_scale = 1;
  1151. int i, j;
  1152. for (i = 0; i < seekhead_list->nb_elem; i++)
  1153. if (seekhead[i].id == MATROSKA_ID_CUES)
  1154. break;
  1155. assert(i <= seekhead_list->nb_elem);
  1156. matroska_parse_seekhead_entry(matroska, i);
  1157. index_list = &matroska->index;
  1158. index = index_list->elem;
  1159. if (index_list->nb_elem
  1160. && index[0].time > 1E14/matroska->time_scale) {
  1161. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1162. index_scale = matroska->time_scale;
  1163. }
  1164. for (i = 0; i < index_list->nb_elem; i++) {
  1165. EbmlList *pos_list = &index[i].pos;
  1166. MatroskaIndexPos *pos = pos_list->elem;
  1167. for (j = 0; j < pos_list->nb_elem; j++) {
  1168. MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
  1169. if (track && track->stream)
  1170. av_add_index_entry(track->stream,
  1171. pos[j].pos + matroska->segment_start,
  1172. index[i].time/index_scale, 0, 0,
  1173. AVINDEX_KEYFRAME);
  1174. }
  1175. }
  1176. }
  1177. static int matroska_aac_profile(char *codec_id)
  1178. {
  1179. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1180. int profile;
  1181. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1182. if (strstr(codec_id, aac_profiles[profile]))
  1183. break;
  1184. return profile + 1;
  1185. }
  1186. static int matroska_aac_sri(int samplerate)
  1187. {
  1188. int sri;
  1189. for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1190. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1191. break;
  1192. return sri;
  1193. }
  1194. static int matroska_read_header(AVFormatContext *s)
  1195. {
  1196. MatroskaDemuxContext *matroska = s->priv_data;
  1197. EbmlList *attachements_list = &matroska->attachments;
  1198. MatroskaAttachement *attachements;
  1199. EbmlList *chapters_list = &matroska->chapters;
  1200. MatroskaChapter *chapters;
  1201. MatroskaTrack *tracks;
  1202. uint64_t max_start = 0;
  1203. Ebml ebml = { 0 };
  1204. AVStream *st;
  1205. int i, j, res;
  1206. matroska->ctx = s;
  1207. /* First read the EBML header. */
  1208. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1209. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1210. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
  1211. av_log(matroska->ctx, AV_LOG_ERROR,
  1212. "EBML header using unsupported features\n"
  1213. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1214. ebml.version, ebml.doctype, ebml.doctype_version);
  1215. ebml_free(ebml_syntax, &ebml);
  1216. return AVERROR_PATCHWELCOME;
  1217. }
  1218. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1219. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1220. break;
  1221. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1222. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1223. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1224. ebml_free(ebml_syntax, &ebml);
  1225. return AVERROR_INVALIDDATA;
  1226. }
  1227. }
  1228. ebml_free(ebml_syntax, &ebml);
  1229. /* The next thing is a segment. */
  1230. if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
  1231. return res;
  1232. matroska_execute_seekhead(matroska);
  1233. if (!matroska->time_scale)
  1234. matroska->time_scale = 1000000;
  1235. if (matroska->duration)
  1236. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1237. * 1000 / AV_TIME_BASE;
  1238. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1239. tracks = matroska->tracks.elem;
  1240. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1241. MatroskaTrack *track = &tracks[i];
  1242. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1243. EbmlList *encodings_list = &tracks->encodings;
  1244. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1245. uint8_t *extradata = NULL;
  1246. int extradata_size = 0;
  1247. int extradata_offset = 0;
  1248. AVIOContext b;
  1249. /* Apply some sanity checks. */
  1250. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1251. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1252. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1253. av_log(matroska->ctx, AV_LOG_INFO,
  1254. "Unknown or unsupported track type %"PRIu64"\n",
  1255. track->type);
  1256. continue;
  1257. }
  1258. if (track->codec_id == NULL)
  1259. continue;
  1260. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1261. if (!track->default_duration && track->video.frame_rate > 0)
  1262. track->default_duration = 1000000000/track->video.frame_rate;
  1263. if (!track->video.display_width)
  1264. track->video.display_width = track->video.pixel_width;
  1265. if (!track->video.display_height)
  1266. track->video.display_height = track->video.pixel_height;
  1267. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1268. if (!track->audio.out_samplerate)
  1269. track->audio.out_samplerate = track->audio.samplerate;
  1270. }
  1271. if (encodings_list->nb_elem > 1) {
  1272. av_log(matroska->ctx, AV_LOG_ERROR,
  1273. "Multiple combined encodings not supported");
  1274. } else if (encodings_list->nb_elem == 1) {
  1275. if (encodings[0].type ||
  1276. (
  1277. #if CONFIG_ZLIB
  1278. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1279. #endif
  1280. #if CONFIG_BZLIB
  1281. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1282. #endif
  1283. #if CONFIG_LZO
  1284. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
  1285. #endif
  1286. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
  1287. encodings[0].scope = 0;
  1288. av_log(matroska->ctx, AV_LOG_ERROR,
  1289. "Unsupported encoding type");
  1290. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1291. uint8_t *codec_priv = track->codec_priv.data;
  1292. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1293. &track->codec_priv.size,
  1294. track);
  1295. if (ret < 0) {
  1296. track->codec_priv.data = NULL;
  1297. track->codec_priv.size = 0;
  1298. av_log(matroska->ctx, AV_LOG_ERROR,
  1299. "Failed to decode codec private data\n");
  1300. }
  1301. if (codec_priv != track->codec_priv.data)
  1302. av_free(codec_priv);
  1303. }
  1304. }
  1305. for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
  1306. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1307. strlen(ff_mkv_codec_tags[j].str))){
  1308. codec_id= ff_mkv_codec_tags[j].id;
  1309. break;
  1310. }
  1311. }
  1312. st = track->stream = avformat_new_stream(s, NULL);
  1313. if (st == NULL)
  1314. return AVERROR(ENOMEM);
  1315. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1316. && track->codec_priv.size >= 40
  1317. && track->codec_priv.data != NULL) {
  1318. track->ms_compat = 1;
  1319. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1320. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1321. extradata_offset = 40;
  1322. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1323. && track->codec_priv.size >= 14
  1324. && track->codec_priv.data != NULL) {
  1325. int ret;
  1326. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1327. AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
  1328. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1329. if (ret < 0)
  1330. return ret;
  1331. codec_id = st->codec->codec_id;
  1332. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1333. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1334. && (track->codec_priv.size >= 86)
  1335. && (track->codec_priv.data != NULL)) {
  1336. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1337. codec_id=ff_codec_get_id(ff_codec_movvideo_tags, track->video.fourcc);
  1338. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1339. switch (track->audio.bitdepth) {
  1340. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1341. case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
  1342. case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
  1343. }
  1344. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1345. switch (track->audio.bitdepth) {
  1346. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1347. case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
  1348. case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
  1349. }
  1350. } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1351. codec_id = AV_CODEC_ID_PCM_F64LE;
  1352. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1353. int profile = matroska_aac_profile(track->codec_id);
  1354. int sri = matroska_aac_sri(track->audio.samplerate);
  1355. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1356. if (extradata == NULL)
  1357. return AVERROR(ENOMEM);
  1358. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1359. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1360. if (strstr(track->codec_id, "SBR")) {
  1361. sri = matroska_aac_sri(track->audio.out_samplerate);
  1362. extradata[2] = 0x56;
  1363. extradata[3] = 0xE5;
  1364. extradata[4] = 0x80 | (sri<<3);
  1365. extradata_size = 5;
  1366. } else
  1367. extradata_size = 2;
  1368. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size) {
  1369. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1370. Create the "atom size", "tag", and "tag version" fields the
  1371. decoder expects manually. */
  1372. extradata_size = 12 + track->codec_priv.size;
  1373. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1374. if (extradata == NULL)
  1375. return AVERROR(ENOMEM);
  1376. AV_WB32(extradata, extradata_size);
  1377. memcpy(&extradata[4], "alac", 4);
  1378. AV_WB32(&extradata[8], 0);
  1379. memcpy(&extradata[12], track->codec_priv.data,
  1380. track->codec_priv.size);
  1381. } else if (codec_id == AV_CODEC_ID_TTA) {
  1382. extradata_size = 30;
  1383. extradata = av_mallocz(extradata_size);
  1384. if (extradata == NULL)
  1385. return AVERROR(ENOMEM);
  1386. ffio_init_context(&b, extradata, extradata_size, 1,
  1387. NULL, NULL, NULL, NULL);
  1388. avio_write(&b, "TTA1", 4);
  1389. avio_wl16(&b, 1);
  1390. avio_wl16(&b, track->audio.channels);
  1391. avio_wl16(&b, track->audio.bitdepth);
  1392. avio_wl32(&b, track->audio.out_samplerate);
  1393. avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1394. } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
  1395. codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
  1396. extradata_offset = 26;
  1397. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1398. track->audio.out_samplerate = 8000;
  1399. track->audio.channels = 1;
  1400. } else if (codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
  1401. codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR) {
  1402. int flavor;
  1403. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1404. 0, NULL, NULL, NULL, NULL);
  1405. avio_skip(&b, 22);
  1406. flavor = avio_rb16(&b);
  1407. track->audio.coded_framesize = avio_rb32(&b);
  1408. avio_skip(&b, 12);
  1409. track->audio.sub_packet_h = avio_rb16(&b);
  1410. track->audio.frame_size = avio_rb16(&b);
  1411. track->audio.sub_packet_size = avio_rb16(&b);
  1412. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1413. if (codec_id == AV_CODEC_ID_RA_288) {
  1414. st->codec->block_align = track->audio.coded_framesize;
  1415. track->codec_priv.size = 0;
  1416. } else {
  1417. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1418. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1419. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1420. st->codec->bit_rate = sipr_bit_rate[flavor];
  1421. }
  1422. st->codec->block_align = track->audio.sub_packet_size;
  1423. extradata_offset = 78;
  1424. }
  1425. }
  1426. track->codec_priv.size -= extradata_offset;
  1427. if (codec_id == AV_CODEC_ID_NONE)
  1428. av_log(matroska->ctx, AV_LOG_INFO,
  1429. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1430. if (track->time_scale < 0.01)
  1431. track->time_scale = 1.0;
  1432. avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1433. st->codec->codec_id = codec_id;
  1434. st->start_time = 0;
  1435. if (strcmp(track->language, "und"))
  1436. av_dict_set(&st->metadata, "language", track->language, 0);
  1437. av_dict_set(&st->metadata, "title", track->name, 0);
  1438. if (track->flag_default)
  1439. st->disposition |= AV_DISPOSITION_DEFAULT;
  1440. if (track->flag_forced)
  1441. st->disposition |= AV_DISPOSITION_FORCED;
  1442. if (!st->codec->extradata) {
  1443. if(extradata){
  1444. st->codec->extradata = extradata;
  1445. st->codec->extradata_size = extradata_size;
  1446. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1447. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1448. FF_INPUT_BUFFER_PADDING_SIZE);
  1449. if(st->codec->extradata == NULL)
  1450. return AVERROR(ENOMEM);
  1451. st->codec->extradata_size = track->codec_priv.size;
  1452. memcpy(st->codec->extradata,
  1453. track->codec_priv.data + extradata_offset,
  1454. track->codec_priv.size);
  1455. }
  1456. }
  1457. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1458. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1459. st->codec->codec_tag = track->video.fourcc;
  1460. st->codec->width = track->video.pixel_width;
  1461. st->codec->height = track->video.pixel_height;
  1462. av_reduce(&st->sample_aspect_ratio.num,
  1463. &st->sample_aspect_ratio.den,
  1464. st->codec->height * track->video.display_width,
  1465. st->codec-> width * track->video.display_height,
  1466. 255);
  1467. if (st->codec->codec_id != AV_CODEC_ID_H264)
  1468. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1469. if (track->default_duration) {
  1470. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1471. 1000000000, track->default_duration, 30000);
  1472. #if FF_API_R_FRAME_RATE
  1473. st->r_frame_rate = st->avg_frame_rate;
  1474. #endif
  1475. }
  1476. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1477. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1478. st->codec->sample_rate = track->audio.out_samplerate;
  1479. st->codec->channels = track->audio.channels;
  1480. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1481. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1482. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1483. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1484. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1485. matroska->contains_ssa = 1;
  1486. }
  1487. }
  1488. attachements = attachements_list->elem;
  1489. for (j=0; j<attachements_list->nb_elem; j++) {
  1490. if (!(attachements[j].filename && attachements[j].mime &&
  1491. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1492. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1493. } else {
  1494. AVStream *st = avformat_new_stream(s, NULL);
  1495. if (st == NULL)
  1496. break;
  1497. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1498. av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
  1499. st->codec->codec_id = AV_CODEC_ID_NONE;
  1500. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1501. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1502. if(st->codec->extradata == NULL)
  1503. break;
  1504. st->codec->extradata_size = attachements[j].bin.size;
  1505. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1506. for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1507. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1508. strlen(ff_mkv_mime_tags[i].str))) {
  1509. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1510. break;
  1511. }
  1512. }
  1513. attachements[j].stream = st;
  1514. }
  1515. }
  1516. chapters = chapters_list->elem;
  1517. for (i=0; i<chapters_list->nb_elem; i++)
  1518. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1519. && (max_start==0 || chapters[i].start > max_start)) {
  1520. chapters[i].chapter =
  1521. avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1522. chapters[i].start, chapters[i].end,
  1523. chapters[i].title);
  1524. av_dict_set(&chapters[i].chapter->metadata,
  1525. "title", chapters[i].title, 0);
  1526. max_start = chapters[i].start;
  1527. }
  1528. matroska_convert_tags(s);
  1529. return 0;
  1530. }
  1531. /*
  1532. * Put one packet in an application-supplied AVPacket struct.
  1533. * Returns 0 on success or -1 on failure.
  1534. */
  1535. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1536. AVPacket *pkt)
  1537. {
  1538. if (matroska->num_packets > 0) {
  1539. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1540. av_free(matroska->packets[0]);
  1541. if (matroska->num_packets > 1) {
  1542. void *newpackets;
  1543. memmove(&matroska->packets[0], &matroska->packets[1],
  1544. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1545. newpackets = av_realloc(matroska->packets,
  1546. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1547. if (newpackets)
  1548. matroska->packets = newpackets;
  1549. } else {
  1550. av_freep(&matroska->packets);
  1551. matroska->prev_pkt = NULL;
  1552. }
  1553. matroska->num_packets--;
  1554. return 0;
  1555. }
  1556. return -1;
  1557. }
  1558. /*
  1559. * Free all packets in our internal queue.
  1560. */
  1561. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1562. {
  1563. if (matroska->packets) {
  1564. int n;
  1565. for (n = 0; n < matroska->num_packets; n++) {
  1566. av_free_packet(matroska->packets[n]);
  1567. av_free(matroska->packets[n]);
  1568. }
  1569. av_freep(&matroska->packets);
  1570. matroska->num_packets = 0;
  1571. }
  1572. }
  1573. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1574. int size, int type,
  1575. uint32_t **lace_buf, int *laces)
  1576. {
  1577. int res = 0, n;
  1578. uint8_t *data = *buf;
  1579. uint32_t *lace_size;
  1580. if (!type) {
  1581. *laces = 1;
  1582. *lace_buf = av_mallocz(sizeof(int));
  1583. if (!*lace_buf)
  1584. return AVERROR(ENOMEM);
  1585. *lace_buf[0] = size;
  1586. return 0;
  1587. }
  1588. assert(size > 0);
  1589. *laces = *data + 1;
  1590. data += 1;
  1591. size -= 1;
  1592. lace_size = av_mallocz(*laces * sizeof(int));
  1593. if (!lace_size)
  1594. return AVERROR(ENOMEM);
  1595. switch (type) {
  1596. case 0x1: /* Xiph lacing */ {
  1597. uint8_t temp;
  1598. uint32_t total = 0;
  1599. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1600. while (1) {
  1601. if (size == 0) {
  1602. res = AVERROR_EOF;
  1603. break;
  1604. }
  1605. temp = *data;
  1606. lace_size[n] += temp;
  1607. data += 1;
  1608. size -= 1;
  1609. if (temp != 0xff)
  1610. break;
  1611. }
  1612. total += lace_size[n];
  1613. }
  1614. if (size <= total) {
  1615. res = AVERROR_INVALIDDATA;
  1616. break;
  1617. }
  1618. lace_size[n] = size - total;
  1619. break;
  1620. }
  1621. case 0x2: /* fixed-size lacing */
  1622. if (size % (*laces)) {
  1623. res = AVERROR_INVALIDDATA;
  1624. break;
  1625. }
  1626. for (n = 0; n < *laces; n++)
  1627. lace_size[n] = size / *laces;
  1628. break;
  1629. case 0x3: /* EBML lacing */ {
  1630. uint64_t num;
  1631. uint32_t total;
  1632. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1633. if (n < 0) {
  1634. av_log(matroska->ctx, AV_LOG_INFO,
  1635. "EBML block data error\n");
  1636. res = n;
  1637. break;
  1638. }
  1639. data += n;
  1640. size -= n;
  1641. total = lace_size[0] = num;
  1642. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1643. int64_t snum;
  1644. int r;
  1645. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1646. if (r < 0) {
  1647. av_log(matroska->ctx, AV_LOG_INFO,
  1648. "EBML block data error\n");
  1649. res = r;
  1650. break;
  1651. }
  1652. data += r;
  1653. size -= r;
  1654. lace_size[n] = lace_size[n - 1] + snum;
  1655. total += lace_size[n];
  1656. }
  1657. if (size <= total) {
  1658. res = AVERROR_INVALIDDATA;
  1659. break;
  1660. }
  1661. lace_size[*laces - 1] = size - total;
  1662. break;
  1663. }
  1664. }
  1665. *buf = data;
  1666. *lace_buf = lace_size;
  1667. return res;
  1668. }
  1669. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1670. MatroskaTrack *track,
  1671. AVStream *st,
  1672. uint8_t *data, int size,
  1673. uint64_t timecode, uint64_t duration,
  1674. int64_t pos)
  1675. {
  1676. int a = st->codec->block_align;
  1677. int sps = track->audio.sub_packet_size;
  1678. int cfs = track->audio.coded_framesize;
  1679. int h = track->audio.sub_packet_h;
  1680. int y = track->audio.sub_packet_cnt;
  1681. int w = track->audio.frame_size;
  1682. int x;
  1683. if (!track->audio.pkt_cnt) {
  1684. if (track->audio.sub_packet_cnt == 0)
  1685. track->audio.buf_timecode = timecode;
  1686. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1687. if (size < cfs * h / 2) {
  1688. av_log(matroska->ctx, AV_LOG_ERROR,
  1689. "Corrupt int4 RM-style audio packet size\n");
  1690. return AVERROR_INVALIDDATA;
  1691. }
  1692. for (x=0; x<h/2; x++)
  1693. memcpy(track->audio.buf+x*2*w+y*cfs,
  1694. data+x*cfs, cfs);
  1695. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1696. if (size < w) {
  1697. av_log(matroska->ctx, AV_LOG_ERROR,
  1698. "Corrupt sipr RM-style audio packet size\n");
  1699. return AVERROR_INVALIDDATA;
  1700. }
  1701. memcpy(track->audio.buf + y*w, data, w);
  1702. } else {
  1703. if (size < sps * w / sps) {
  1704. av_log(matroska->ctx, AV_LOG_ERROR,
  1705. "Corrupt generic RM-style audio packet size\n");
  1706. return AVERROR_INVALIDDATA;
  1707. }
  1708. for (x=0; x<w/sps; x++)
  1709. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1710. }
  1711. if (++track->audio.sub_packet_cnt >= h) {
  1712. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1713. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1714. track->audio.sub_packet_cnt = 0;
  1715. track->audio.pkt_cnt = h*w / a;
  1716. }
  1717. }
  1718. while (track->audio.pkt_cnt) {
  1719. AVPacket *pkt = av_mallocz(sizeof(AVPacket));
  1720. av_new_packet(pkt, a);
  1721. memcpy(pkt->data, track->audio.buf
  1722. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1723. pkt->pts = track->audio.buf_timecode;
  1724. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1725. pkt->pos = pos;
  1726. pkt->stream_index = st->index;
  1727. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1728. }
  1729. return 0;
  1730. }
  1731. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  1732. MatroskaTrack *track,
  1733. AVStream *st,
  1734. uint8_t *data, int pkt_size,
  1735. uint64_t timecode, uint64_t duration,
  1736. int64_t pos, int is_keyframe)
  1737. {
  1738. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1739. uint8_t *pkt_data = data;
  1740. int offset = 0, res;
  1741. AVPacket *pkt;
  1742. if (encodings && encodings->scope & 1) {
  1743. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  1744. if (res < 0)
  1745. return res;
  1746. }
  1747. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  1748. offset = 8;
  1749. pkt = av_mallocz(sizeof(AVPacket));
  1750. /* XXX: prevent data copy... */
  1751. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  1752. av_free(pkt);
  1753. return AVERROR(ENOMEM);
  1754. }
  1755. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  1756. uint8_t *buf = pkt->data;
  1757. bytestream_put_be32(&buf, pkt_size);
  1758. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  1759. }
  1760. memcpy(pkt->data + offset, pkt_data, pkt_size);
  1761. if (pkt_data != data)
  1762. av_free(pkt_data);
  1763. pkt->flags = is_keyframe;
  1764. pkt->stream_index = st->index;
  1765. if (track->ms_compat)
  1766. pkt->dts = timecode;
  1767. else
  1768. pkt->pts = timecode;
  1769. pkt->pos = pos;
  1770. if (st->codec->codec_id == AV_CODEC_ID_TEXT)
  1771. pkt->convergence_duration = duration;
  1772. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1773. pkt->duration = duration;
  1774. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1775. matroska_fix_ass_packet(matroska, pkt, duration);
  1776. if (matroska->prev_pkt &&
  1777. timecode != AV_NOPTS_VALUE &&
  1778. matroska->prev_pkt->pts == timecode &&
  1779. matroska->prev_pkt->stream_index == st->index &&
  1780. st->codec->codec_id == AV_CODEC_ID_SSA)
  1781. matroska_merge_packets(matroska->prev_pkt, pkt);
  1782. else {
  1783. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1784. matroska->prev_pkt = pkt;
  1785. }
  1786. return 0;
  1787. }
  1788. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1789. int size, int64_t pos, uint64_t cluster_time,
  1790. uint64_t block_duration, int is_keyframe,
  1791. int64_t cluster_pos)
  1792. {
  1793. uint64_t timecode = AV_NOPTS_VALUE;
  1794. MatroskaTrack *track;
  1795. int res = 0;
  1796. AVStream *st;
  1797. int16_t block_time;
  1798. uint32_t *lace_size = NULL;
  1799. int n, flags, laces = 0;
  1800. uint64_t num, duration;
  1801. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1802. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1803. return n;
  1804. }
  1805. data += n;
  1806. size -= n;
  1807. track = matroska_find_track_by_num(matroska, num);
  1808. if (!track || !track->stream) {
  1809. av_log(matroska->ctx, AV_LOG_INFO,
  1810. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1811. return AVERROR_INVALIDDATA;
  1812. } else if (size <= 3)
  1813. return 0;
  1814. st = track->stream;
  1815. if (st->discard >= AVDISCARD_ALL)
  1816. return res;
  1817. block_time = AV_RB16(data);
  1818. data += 2;
  1819. flags = *data++;
  1820. size -= 3;
  1821. if (is_keyframe == -1)
  1822. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1823. if (cluster_time != (uint64_t)-1
  1824. && (block_time >= 0 || cluster_time >= -block_time)) {
  1825. timecode = cluster_time + block_time;
  1826. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1827. && timecode < track->end_timecode)
  1828. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1829. if (is_keyframe)
  1830. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1831. }
  1832. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1833. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1834. return res;
  1835. matroska->skip_to_keyframe = 0;
  1836. }
  1837. res = matroska_parse_laces(matroska, &data, size, (flags & 0x06) >> 1,
  1838. &lace_size, &laces);
  1839. if (res)
  1840. goto end;
  1841. if (block_duration != AV_NOPTS_VALUE) {
  1842. duration = block_duration / laces;
  1843. if (block_duration != duration * laces) {
  1844. av_log(matroska->ctx, AV_LOG_WARNING,
  1845. "Incorrect block_duration, possibly corrupted container");
  1846. }
  1847. } else {
  1848. duration = track->default_duration / matroska->time_scale;
  1849. block_duration = duration * laces;
  1850. }
  1851. if (timecode != AV_NOPTS_VALUE)
  1852. track->end_timecode =
  1853. FFMAX(track->end_timecode, timecode + block_duration);
  1854. for (n = 0; n < laces; n++) {
  1855. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  1856. st->codec->codec_id == AV_CODEC_ID_COOK ||
  1857. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  1858. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  1859. st->codec->block_align && track->audio.sub_packet_size) {
  1860. res = matroska_parse_rm_audio(matroska, track, st, data, size,
  1861. timecode, duration, pos);
  1862. if (res)
  1863. goto end;
  1864. } else {
  1865. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  1866. timecode, duration,
  1867. pos, !n? is_keyframe : 0);
  1868. if (res)
  1869. goto end;
  1870. }
  1871. if (timecode != AV_NOPTS_VALUE)
  1872. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1873. data += lace_size[n];
  1874. size -= lace_size[n];
  1875. }
  1876. end:
  1877. av_free(lace_size);
  1878. return res;
  1879. }
  1880. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  1881. {
  1882. EbmlList *blocks_list;
  1883. MatroskaBlock *blocks;
  1884. int i, res;
  1885. res = ebml_parse(matroska,
  1886. matroska_cluster_incremental_parsing,
  1887. &matroska->current_cluster);
  1888. if (res == 1) {
  1889. /* New Cluster */
  1890. if (matroska->current_cluster_pos)
  1891. ebml_level_end(matroska);
  1892. ebml_free(matroska_cluster, &matroska->current_cluster);
  1893. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  1894. matroska->current_cluster_num_blocks = 0;
  1895. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  1896. matroska->prev_pkt = NULL;
  1897. /* sizeof the ID which was already read */
  1898. if (matroska->current_id)
  1899. matroska->current_cluster_pos -= 4;
  1900. res = ebml_parse(matroska,
  1901. matroska_clusters_incremental,
  1902. &matroska->current_cluster);
  1903. /* Try parsing the block again. */
  1904. if (res == 1)
  1905. res = ebml_parse(matroska,
  1906. matroska_cluster_incremental_parsing,
  1907. &matroska->current_cluster);
  1908. }
  1909. if (!res &&
  1910. matroska->current_cluster_num_blocks <
  1911. matroska->current_cluster.blocks.nb_elem) {
  1912. blocks_list = &matroska->current_cluster.blocks;
  1913. blocks = blocks_list->elem;
  1914. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  1915. i = blocks_list->nb_elem - 1;
  1916. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1917. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1918. if (!blocks[i].non_simple)
  1919. blocks[i].duration = AV_NOPTS_VALUE;
  1920. res = matroska_parse_block(matroska,
  1921. blocks[i].bin.data, blocks[i].bin.size,
  1922. blocks[i].bin.pos,
  1923. matroska->current_cluster.timecode,
  1924. blocks[i].duration, is_keyframe,
  1925. matroska->current_cluster_pos);
  1926. }
  1927. }
  1928. if (res < 0) matroska->done = 1;
  1929. return res;
  1930. }
  1931. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1932. {
  1933. MatroskaCluster cluster = { 0 };
  1934. EbmlList *blocks_list;
  1935. MatroskaBlock *blocks;
  1936. int i, res;
  1937. int64_t pos;
  1938. if (!matroska->contains_ssa)
  1939. return matroska_parse_cluster_incremental(matroska);
  1940. pos = avio_tell(matroska->ctx->pb);
  1941. matroska->prev_pkt = NULL;
  1942. if (matroska->current_id)
  1943. pos -= 4; /* sizeof the ID which was already read */
  1944. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1945. blocks_list = &cluster.blocks;
  1946. blocks = blocks_list->elem;
  1947. for (i=0; i<blocks_list->nb_elem && !res; i++)
  1948. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1949. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1950. if (!blocks[i].non_simple)
  1951. blocks[i].duration = AV_NOPTS_VALUE;
  1952. res=matroska_parse_block(matroska,
  1953. blocks[i].bin.data, blocks[i].bin.size,
  1954. blocks[i].bin.pos, cluster.timecode,
  1955. blocks[i].duration, is_keyframe,
  1956. pos);
  1957. }
  1958. ebml_free(matroska_cluster, &cluster);
  1959. if (res < 0) matroska->done = 1;
  1960. return res;
  1961. }
  1962. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1963. {
  1964. MatroskaDemuxContext *matroska = s->priv_data;
  1965. int ret = 0;
  1966. while (!ret && matroska_deliver_packet(matroska, pkt)) {
  1967. if (matroska->done)
  1968. return AVERROR_EOF;
  1969. ret = matroska_parse_cluster(matroska);
  1970. }
  1971. if (ret == AVERROR_INVALIDDATA && pkt->data) {
  1972. pkt->flags |= AV_PKT_FLAG_CORRUPT;
  1973. return 0;
  1974. }
  1975. return ret;
  1976. }
  1977. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1978. int64_t timestamp, int flags)
  1979. {
  1980. MatroskaDemuxContext *matroska = s->priv_data;
  1981. MatroskaTrack *tracks = matroska->tracks.elem;
  1982. AVStream *st = s->streams[stream_index];
  1983. int i, index, index_sub, index_min;
  1984. /* Parse the CUES now since we need the index data to seek. */
  1985. if (matroska->cues_parsing_deferred) {
  1986. matroska_parse_cues(matroska);
  1987. matroska->cues_parsing_deferred = 0;
  1988. }
  1989. if (!st->nb_index_entries)
  1990. return 0;
  1991. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1992. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1993. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1994. matroska->current_id = 0;
  1995. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1996. matroska->prev_pkt = NULL;
  1997. matroska_clear_queue(matroska);
  1998. if (matroska_parse_cluster(matroska) < 0)
  1999. break;
  2000. }
  2001. }
  2002. matroska_clear_queue(matroska);
  2003. if (index < 0)
  2004. return 0;
  2005. index_min = index;
  2006. for (i=0; i < matroska->tracks.nb_elem; i++) {
  2007. tracks[i].audio.pkt_cnt = 0;
  2008. tracks[i].audio.sub_packet_cnt = 0;
  2009. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2010. tracks[i].end_timecode = 0;
  2011. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  2012. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  2013. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  2014. if (index_sub >= 0
  2015. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  2016. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  2017. index_min = index_sub;
  2018. }
  2019. }
  2020. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2021. matroska->current_id = 0;
  2022. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2023. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2024. matroska->done = 0;
  2025. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2026. return 0;
  2027. }
  2028. static int matroska_read_close(AVFormatContext *s)
  2029. {
  2030. MatroskaDemuxContext *matroska = s->priv_data;
  2031. MatroskaTrack *tracks = matroska->tracks.elem;
  2032. int n;
  2033. matroska_clear_queue(matroska);
  2034. for (n=0; n < matroska->tracks.nb_elem; n++)
  2035. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2036. av_free(tracks[n].audio.buf);
  2037. ebml_free(matroska_cluster, &matroska->current_cluster);
  2038. ebml_free(matroska_segment, matroska);
  2039. return 0;
  2040. }
  2041. AVInputFormat ff_matroska_demuxer = {
  2042. .name = "matroska,webm",
  2043. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2044. .priv_data_size = sizeof(MatroskaDemuxContext),
  2045. .read_probe = matroska_probe,
  2046. .read_header = matroska_read_header,
  2047. .read_packet = matroska_read_packet,
  2048. .read_close = matroska_read_close,
  2049. .read_seek = matroska_read_seek,
  2050. };