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.

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