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.

2187 lines
78KB

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