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.

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