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.

2817 lines
98KB

  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 "rmsipr.h"
  37. #include "matroska.h"
  38. #include "libavcodec/bytestream.h"
  39. #include "libavcodec/mpeg4audio.h"
  40. #include "libavutil/base64.h"
  41. #include "libavutil/intfloat.h"
  42. #include "libavutil/intreadwrite.h"
  43. #include "libavutil/avstring.h"
  44. #include "libavutil/lzo.h"
  45. #include "libavutil/dict.h"
  46. #if CONFIG_ZLIB
  47. #include <zlib.h>
  48. #endif
  49. #if CONFIG_BZLIB
  50. #include <bzlib.h>
  51. #endif
  52. typedef enum {
  53. EBML_NONE,
  54. EBML_UINT,
  55. EBML_FLOAT,
  56. EBML_STR,
  57. EBML_UTF8,
  58. EBML_BIN,
  59. EBML_NEST,
  60. EBML_PASS,
  61. EBML_STOP,
  62. EBML_TYPE_COUNT
  63. } EbmlType;
  64. typedef const struct EbmlSyntax {
  65. uint32_t id;
  66. EbmlType type;
  67. int list_elem_size;
  68. int data_offset;
  69. union {
  70. uint64_t u;
  71. double f;
  72. const char *s;
  73. const struct EbmlSyntax *n;
  74. } def;
  75. } EbmlSyntax;
  76. typedef struct {
  77. int nb_elem;
  78. void *elem;
  79. } EbmlList;
  80. typedef struct {
  81. int size;
  82. uint8_t *data;
  83. int64_t pos;
  84. } EbmlBin;
  85. typedef struct {
  86. uint64_t version;
  87. uint64_t max_size;
  88. uint64_t id_length;
  89. char *doctype;
  90. uint64_t doctype_version;
  91. } Ebml;
  92. typedef struct {
  93. uint64_t algo;
  94. EbmlBin settings;
  95. } MatroskaTrackCompression;
  96. typedef struct {
  97. uint64_t algo;
  98. EbmlBin key_id;
  99. } MatroskaTrackEncryption;
  100. typedef struct {
  101. uint64_t scope;
  102. uint64_t type;
  103. MatroskaTrackCompression compression;
  104. MatroskaTrackEncryption encryption;
  105. } MatroskaTrackEncoding;
  106. typedef struct {
  107. double frame_rate;
  108. uint64_t display_width;
  109. uint64_t display_height;
  110. uint64_t pixel_width;
  111. uint64_t pixel_height;
  112. EbmlBin color_space;
  113. uint64_t stereo_mode;
  114. uint64_t alpha_mode;
  115. } MatroskaTrackVideo;
  116. typedef struct {
  117. double samplerate;
  118. double out_samplerate;
  119. uint64_t bitdepth;
  120. uint64_t channels;
  121. /* real audio header (extracted from extradata) */
  122. int coded_framesize;
  123. int sub_packet_h;
  124. int frame_size;
  125. int sub_packet_size;
  126. int sub_packet_cnt;
  127. int pkt_cnt;
  128. uint64_t buf_timecode;
  129. uint8_t *buf;
  130. } MatroskaTrackAudio;
  131. typedef struct {
  132. uint64_t uid;
  133. uint64_t type;
  134. } MatroskaTrackPlane;
  135. typedef struct {
  136. EbmlList combine_planes;
  137. } MatroskaTrackOperation;
  138. typedef struct {
  139. uint64_t num;
  140. uint64_t uid;
  141. uint64_t type;
  142. char *name;
  143. char *codec_id;
  144. EbmlBin codec_priv;
  145. char *language;
  146. double time_scale;
  147. uint64_t default_duration;
  148. uint64_t flag_default;
  149. uint64_t flag_forced;
  150. MatroskaTrackVideo video;
  151. MatroskaTrackAudio audio;
  152. MatroskaTrackOperation operation;
  153. EbmlList encodings;
  154. AVStream *stream;
  155. int64_t end_timecode;
  156. int ms_compat;
  157. uint64_t max_block_additional_id;
  158. } MatroskaTrack;
  159. typedef struct {
  160. uint64_t uid;
  161. char *filename;
  162. char *mime;
  163. EbmlBin bin;
  164. AVStream *stream;
  165. } MatroskaAttachement;
  166. typedef struct {
  167. uint64_t start;
  168. uint64_t end;
  169. uint64_t uid;
  170. char *title;
  171. AVChapter *chapter;
  172. } MatroskaChapter;
  173. typedef struct {
  174. uint64_t track;
  175. uint64_t pos;
  176. } MatroskaIndexPos;
  177. typedef struct {
  178. uint64_t time;
  179. EbmlList pos;
  180. } MatroskaIndex;
  181. typedef struct {
  182. char *name;
  183. char *string;
  184. char *lang;
  185. uint64_t def;
  186. EbmlList sub;
  187. } MatroskaTag;
  188. typedef struct {
  189. char *type;
  190. uint64_t typevalue;
  191. uint64_t trackuid;
  192. uint64_t chapteruid;
  193. uint64_t attachuid;
  194. } MatroskaTagTarget;
  195. typedef struct {
  196. MatroskaTagTarget target;
  197. EbmlList tag;
  198. } MatroskaTags;
  199. typedef struct {
  200. uint64_t id;
  201. uint64_t pos;
  202. } MatroskaSeekhead;
  203. typedef struct {
  204. uint64_t start;
  205. uint64_t length;
  206. } MatroskaLevel;
  207. typedef struct {
  208. uint64_t timecode;
  209. EbmlList blocks;
  210. } MatroskaCluster;
  211. typedef struct {
  212. AVFormatContext *ctx;
  213. /* EBML stuff */
  214. int num_levels;
  215. MatroskaLevel levels[EBML_MAX_DEPTH];
  216. int level_up;
  217. uint32_t current_id;
  218. uint64_t time_scale;
  219. double duration;
  220. char *title;
  221. EbmlBin date_utc;
  222. EbmlList tracks;
  223. EbmlList attachments;
  224. EbmlList chapters;
  225. EbmlList index;
  226. EbmlList tags;
  227. EbmlList seekhead;
  228. /* byte position of the segment inside the stream */
  229. int64_t segment_start;
  230. /* the packet queue */
  231. AVPacket **packets;
  232. int num_packets;
  233. AVPacket *prev_pkt;
  234. int done;
  235. /* What to skip before effectively reading a packet. */
  236. int skip_to_keyframe;
  237. uint64_t skip_to_timecode;
  238. /* File has a CUES element, but we defer parsing until it is needed. */
  239. int cues_parsing_deferred;
  240. int current_cluster_num_blocks;
  241. int64_t current_cluster_pos;
  242. MatroskaCluster current_cluster;
  243. /* File has SSA subtitles which prevent incremental cluster parsing. */
  244. int contains_ssa;
  245. } MatroskaDemuxContext;
  246. typedef struct {
  247. uint64_t duration;
  248. int64_t reference;
  249. uint64_t non_simple;
  250. EbmlBin bin;
  251. uint64_t additional_id;
  252. EbmlBin additional;
  253. } MatroskaBlock;
  254. static EbmlSyntax ebml_header[] = {
  255. { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
  256. { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
  257. { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
  258. { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
  259. { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
  260. { EBML_ID_EBMLVERSION, EBML_NONE },
  261. { EBML_ID_DOCTYPEVERSION, EBML_NONE },
  262. { 0 }
  263. };
  264. static EbmlSyntax ebml_syntax[] = {
  265. { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
  266. { 0 }
  267. };
  268. static EbmlSyntax matroska_info[] = {
  269. { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
  270. { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
  271. { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
  272. { MATROSKA_ID_WRITINGAPP, EBML_NONE },
  273. { MATROSKA_ID_MUXINGAPP, EBML_NONE },
  274. { MATROSKA_ID_DATEUTC, EBML_BIN, 0, offsetof(MatroskaDemuxContext,date_utc) },
  275. { MATROSKA_ID_SEGMENTUID, EBML_NONE },
  276. { 0 }
  277. };
  278. static EbmlSyntax matroska_track_video[] = {
  279. { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
  280. { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width), {.u=-1} },
  281. { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height), {.u=-1} },
  282. { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
  283. { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
  284. { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo,color_space) },
  285. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
  286. { MATROSKA_ID_VIDEOALPHAMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,alpha_mode) },
  287. { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
  288. { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
  289. { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
  290. { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
  291. { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
  292. { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
  293. { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
  294. { 0 }
  295. };
  296. static EbmlSyntax matroska_track_audio[] = {
  297. { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
  298. { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
  299. { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
  300. { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
  301. { 0 }
  302. };
  303. static EbmlSyntax matroska_track_encoding_compression[] = {
  304. { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
  305. { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
  306. { 0 }
  307. };
  308. static EbmlSyntax matroska_track_encoding_encryption[] = {
  309. { MATROSKA_ID_ENCODINGENCALGO, EBML_UINT, 0, offsetof(MatroskaTrackEncryption,algo), {.u=0} },
  310. { MATROSKA_ID_ENCODINGENCKEYID, EBML_BIN, 0, offsetof(MatroskaTrackEncryption,key_id) },
  311. { MATROSKA_ID_ENCODINGENCAESSETTINGS, EBML_NONE },
  312. { MATROSKA_ID_ENCODINGSIGALGO, EBML_NONE },
  313. { MATROSKA_ID_ENCODINGSIGHASHALGO, EBML_NONE },
  314. { MATROSKA_ID_ENCODINGSIGKEYID, EBML_NONE },
  315. { MATROSKA_ID_ENCODINGSIGNATURE, EBML_NONE },
  316. { 0 }
  317. };
  318. static EbmlSyntax matroska_track_encoding[] = {
  319. { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
  320. { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
  321. { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
  322. { MATROSKA_ID_ENCODINGENCRYPTION, EBML_NEST, 0, offsetof(MatroskaTrackEncoding,encryption), {.n=matroska_track_encoding_encryption} },
  323. { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
  324. { 0 }
  325. };
  326. static EbmlSyntax matroska_track_encodings[] = {
  327. { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
  328. { 0 }
  329. };
  330. static EbmlSyntax matroska_track_plane[] = {
  331. { MATROSKA_ID_TRACKPLANEUID, EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
  332. { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
  333. { 0 }
  334. };
  335. static EbmlSyntax matroska_track_combine_planes[] = {
  336. { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
  337. { 0 }
  338. };
  339. static EbmlSyntax matroska_track_operation[] = {
  340. { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
  341. { 0 }
  342. };
  343. static EbmlSyntax matroska_track[] = {
  344. { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
  345. { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
  346. { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
  347. { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
  348. { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
  349. { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
  350. { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
  351. { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
  352. { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
  353. { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
  354. { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
  355. { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
  356. { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
  357. { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
  358. { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
  359. { MATROSKA_ID_TRACKMAXBLKADDID, EBML_UINT, 0, offsetof(MatroskaTrack,max_block_additional_id) },
  360. { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
  361. { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
  362. { MATROSKA_ID_CODECNAME, EBML_NONE },
  363. { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
  364. { MATROSKA_ID_CODECINFOURL, EBML_NONE },
  365. { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
  366. { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
  367. { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
  368. { 0 }
  369. };
  370. static EbmlSyntax matroska_tracks[] = {
  371. { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
  372. { 0 }
  373. };
  374. static EbmlSyntax matroska_attachment[] = {
  375. { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
  376. { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
  377. { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
  378. { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
  379. { MATROSKA_ID_FILEDESC, EBML_NONE },
  380. { 0 }
  381. };
  382. static EbmlSyntax matroska_attachments[] = {
  383. { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
  384. { 0 }
  385. };
  386. static EbmlSyntax matroska_chapter_display[] = {
  387. { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
  388. { MATROSKA_ID_CHAPLANG, EBML_NONE },
  389. { 0 }
  390. };
  391. static EbmlSyntax matroska_chapter_entry[] = {
  392. { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
  393. { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
  394. { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
  395. { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
  396. { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
  397. { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
  398. { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
  399. { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
  400. { 0 }
  401. };
  402. static EbmlSyntax matroska_chapter[] = {
  403. { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
  404. { MATROSKA_ID_EDITIONUID, EBML_NONE },
  405. { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
  406. { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  407. { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
  408. { 0 }
  409. };
  410. static EbmlSyntax matroska_chapters[] = {
  411. { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
  412. { 0 }
  413. };
  414. static EbmlSyntax matroska_index_pos[] = {
  415. { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
  416. { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
  417. { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
  418. { 0 }
  419. };
  420. static EbmlSyntax matroska_index_entry[] = {
  421. { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
  422. { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
  423. { 0 }
  424. };
  425. static EbmlSyntax matroska_index[] = {
  426. { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
  427. { 0 }
  428. };
  429. static EbmlSyntax matroska_simpletag[] = {
  430. { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
  431. { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
  432. { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
  433. { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  434. { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  435. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
  436. { 0 }
  437. };
  438. static EbmlSyntax matroska_tagtargets[] = {
  439. { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
  440. { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
  441. { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
  442. { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
  443. { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
  444. { 0 }
  445. };
  446. static EbmlSyntax matroska_tag[] = {
  447. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
  448. { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
  449. { 0 }
  450. };
  451. static EbmlSyntax matroska_tags[] = {
  452. { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
  453. { 0 }
  454. };
  455. static EbmlSyntax matroska_seekhead_entry[] = {
  456. { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
  457. { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
  458. { 0 }
  459. };
  460. static EbmlSyntax matroska_seekhead[] = {
  461. { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
  462. { 0 }
  463. };
  464. static EbmlSyntax matroska_segment[] = {
  465. { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
  466. { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
  467. { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
  468. { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
  469. { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
  470. { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
  471. { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
  472. { MATROSKA_ID_CLUSTER, EBML_STOP },
  473. { 0 }
  474. };
  475. static EbmlSyntax matroska_segments[] = {
  476. { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
  477. { 0 }
  478. };
  479. static EbmlSyntax matroska_blockmore[] = {
  480. { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
  481. { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN, 0, offsetof(MatroskaBlock,additional) },
  482. { 0 }
  483. };
  484. static EbmlSyntax matroska_blockadditions[] = {
  485. { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n=matroska_blockmore} },
  486. { 0 }
  487. };
  488. static EbmlSyntax matroska_blockgroup[] = {
  489. { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  490. { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, {.n=matroska_blockadditions} },
  491. { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  492. { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
  493. { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
  494. { MATROSKA_ID_CODECSTATE, EBML_NONE },
  495. { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
  496. { 0 }
  497. };
  498. static EbmlSyntax matroska_cluster[] = {
  499. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  500. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  501. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  502. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  503. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  504. { 0 }
  505. };
  506. static EbmlSyntax matroska_clusters[] = {
  507. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
  508. { MATROSKA_ID_INFO, EBML_NONE },
  509. { MATROSKA_ID_CUES, EBML_NONE },
  510. { MATROSKA_ID_TAGS, EBML_NONE },
  511. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  512. { 0 }
  513. };
  514. static EbmlSyntax matroska_cluster_incremental_parsing[] = {
  515. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  516. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  517. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  518. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  519. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  520. { MATROSKA_ID_INFO, EBML_NONE },
  521. { MATROSKA_ID_CUES, EBML_NONE },
  522. { MATROSKA_ID_TAGS, EBML_NONE },
  523. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  524. { MATROSKA_ID_CLUSTER, EBML_STOP },
  525. { 0 }
  526. };
  527. static EbmlSyntax matroska_cluster_incremental[] = {
  528. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  529. { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
  530. { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
  531. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  532. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  533. { 0 }
  534. };
  535. static EbmlSyntax matroska_clusters_incremental[] = {
  536. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
  537. { MATROSKA_ID_INFO, EBML_NONE },
  538. { MATROSKA_ID_CUES, EBML_NONE },
  539. { MATROSKA_ID_TAGS, EBML_NONE },
  540. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  541. { 0 }
  542. };
  543. static const char *const matroska_doctypes[] = { "matroska", "webm" };
  544. static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
  545. {
  546. AVIOContext *pb = matroska->ctx->pb;
  547. uint32_t id;
  548. matroska->current_id = 0;
  549. matroska->num_levels = 0;
  550. /* seek to next position to resync from */
  551. if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
  552. goto eof;
  553. id = avio_rb32(pb);
  554. // try to find a toplevel element
  555. while (!url_feof(pb)) {
  556. if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
  557. id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
  558. id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
  559. id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS) {
  560. matroska->current_id = id;
  561. return 0;
  562. }
  563. id = (id << 8) | avio_r8(pb);
  564. }
  565. eof:
  566. matroska->done = 1;
  567. return AVERROR_EOF;
  568. }
  569. /*
  570. * Return: Whether we reached the end of a level in the hierarchy or not.
  571. */
  572. static int ebml_level_end(MatroskaDemuxContext *matroska)
  573. {
  574. AVIOContext *pb = matroska->ctx->pb;
  575. int64_t pos = avio_tell(pb);
  576. if (matroska->num_levels > 0) {
  577. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  578. if (pos - level->start >= level->length || matroska->current_id) {
  579. matroska->num_levels--;
  580. return 1;
  581. }
  582. }
  583. return 0;
  584. }
  585. /*
  586. * Read: an "EBML number", which is defined as a variable-length
  587. * array of bytes. The first byte indicates the length by giving a
  588. * number of 0-bits followed by a one. The position of the first
  589. * "one" bit inside the first byte indicates the length of this
  590. * number.
  591. * Returns: number of bytes read, < 0 on error
  592. */
  593. static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
  594. int max_size, uint64_t *number)
  595. {
  596. int read = 1, n = 1;
  597. uint64_t total = 0;
  598. /* The first byte tells us the length in bytes - avio_r8() can normally
  599. * return 0, but since that's not a valid first ebmlID byte, we can
  600. * use it safely here to catch EOS. */
  601. if (!(total = avio_r8(pb))) {
  602. /* we might encounter EOS here */
  603. if (!url_feof(pb)) {
  604. int64_t pos = avio_tell(pb);
  605. av_log(matroska->ctx, AV_LOG_ERROR,
  606. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  607. pos, pos);
  608. return pb->error ? pb->error : AVERROR(EIO);
  609. }
  610. return AVERROR_EOF;
  611. }
  612. /* get the length of the EBML number */
  613. read = 8 - ff_log2_tab[total];
  614. if (read > max_size) {
  615. int64_t pos = avio_tell(pb) - 1;
  616. av_log(matroska->ctx, AV_LOG_ERROR,
  617. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  618. (uint8_t) total, pos, pos);
  619. return AVERROR_INVALIDDATA;
  620. }
  621. /* read out length */
  622. total ^= 1 << ff_log2_tab[total];
  623. while (n++ < read)
  624. total = (total << 8) | avio_r8(pb);
  625. *number = total;
  626. return read;
  627. }
  628. /**
  629. * Read a EBML length value.
  630. * This needs special handling for the "unknown length" case which has multiple
  631. * encodings.
  632. */
  633. static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
  634. uint64_t *number)
  635. {
  636. int res = ebml_read_num(matroska, pb, 8, number);
  637. if (res > 0 && *number + 1 == 1ULL << (7 * res))
  638. *number = 0xffffffffffffffULL;
  639. return res;
  640. }
  641. /*
  642. * Read the next element as an unsigned int.
  643. * 0 is success, < 0 is failure.
  644. */
  645. static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
  646. {
  647. int n = 0;
  648. if (size > 8)
  649. return AVERROR_INVALIDDATA;
  650. /* big-endian ordering; build up number */
  651. *num = 0;
  652. while (n++ < size)
  653. *num = (*num << 8) | avio_r8(pb);
  654. return 0;
  655. }
  656. /*
  657. * Read the next element as a float.
  658. * 0 is success, < 0 is failure.
  659. */
  660. static int ebml_read_float(AVIOContext *pb, int size, double *num)
  661. {
  662. if (size == 0) {
  663. *num = 0;
  664. } else if (size == 4) {
  665. *num = av_int2float(avio_rb32(pb));
  666. } else if (size == 8){
  667. *num = av_int2double(avio_rb64(pb));
  668. } else
  669. return AVERROR_INVALIDDATA;
  670. return 0;
  671. }
  672. /*
  673. * Read the next element as an ASCII string.
  674. * 0 is success, < 0 is failure.
  675. */
  676. static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
  677. {
  678. char *res;
  679. /* EBML strings are usually not 0-terminated, so we allocate one
  680. * byte more, read the string and NULL-terminate it ourselves. */
  681. if (!(res = av_malloc(size + 1)))
  682. return AVERROR(ENOMEM);
  683. if (avio_read(pb, (uint8_t *) res, size) != size) {
  684. av_free(res);
  685. return AVERROR(EIO);
  686. }
  687. (res)[size] = '\0';
  688. av_free(*str);
  689. *str = res;
  690. return 0;
  691. }
  692. /*
  693. * Read the next element as binary data.
  694. * 0 is success, < 0 is failure.
  695. */
  696. static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
  697. {
  698. av_fast_padded_malloc(&bin->data, &bin->size, length);
  699. if (!bin->data)
  700. return AVERROR(ENOMEM);
  701. bin->size = length;
  702. bin->pos = avio_tell(pb);
  703. if (avio_read(pb, bin->data, length) != length) {
  704. av_freep(&bin->data);
  705. bin->size = 0;
  706. return AVERROR(EIO);
  707. }
  708. return 0;
  709. }
  710. /*
  711. * Read the next element, but only the header. The contents
  712. * are supposed to be sub-elements which can be read separately.
  713. * 0 is success, < 0 is failure.
  714. */
  715. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  716. {
  717. AVIOContext *pb = matroska->ctx->pb;
  718. MatroskaLevel *level;
  719. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  720. av_log(matroska->ctx, AV_LOG_ERROR,
  721. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  722. return AVERROR(ENOSYS);
  723. }
  724. level = &matroska->levels[matroska->num_levels++];
  725. level->start = avio_tell(pb);
  726. level->length = length;
  727. return 0;
  728. }
  729. /*
  730. * Read signed/unsigned "EBML" numbers.
  731. * Return: number of bytes processed, < 0 on error
  732. */
  733. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  734. uint8_t *data, uint32_t size, uint64_t *num)
  735. {
  736. AVIOContext pb;
  737. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  738. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  739. }
  740. /*
  741. * Same as above, but signed.
  742. */
  743. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  744. uint8_t *data, uint32_t size, int64_t *num)
  745. {
  746. uint64_t unum;
  747. int res;
  748. /* read as unsigned number first */
  749. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  750. return res;
  751. /* make signed (weird way) */
  752. *num = unum - ((1LL << (7*res - 1)) - 1);
  753. return res;
  754. }
  755. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  756. EbmlSyntax *syntax, void *data);
  757. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  758. uint32_t id, void *data)
  759. {
  760. int i;
  761. for (i=0; syntax[i].id; i++)
  762. if (id == syntax[i].id)
  763. break;
  764. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  765. matroska->num_levels > 0 &&
  766. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  767. return 0; // we reached the end of an unknown size cluster
  768. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
  769. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  770. if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
  771. return AVERROR_INVALIDDATA;
  772. }
  773. return ebml_parse_elem(matroska, &syntax[i], data);
  774. }
  775. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  776. void *data)
  777. {
  778. if (!matroska->current_id) {
  779. uint64_t id;
  780. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  781. if (res < 0)
  782. return res;
  783. matroska->current_id = id | 1 << 7*res;
  784. }
  785. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  786. }
  787. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  788. void *data)
  789. {
  790. int i, res = 0;
  791. for (i=0; syntax[i].id; i++)
  792. switch (syntax[i].type) {
  793. case EBML_UINT:
  794. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  795. break;
  796. case EBML_FLOAT:
  797. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  798. break;
  799. case EBML_STR:
  800. case EBML_UTF8:
  801. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  802. break;
  803. }
  804. while (!res && !ebml_level_end(matroska))
  805. res = ebml_parse(matroska, syntax, data);
  806. return res;
  807. }
  808. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  809. EbmlSyntax *syntax, void *data)
  810. {
  811. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  812. [EBML_UINT] = 8,
  813. [EBML_FLOAT] = 8,
  814. // max. 16 MB for strings
  815. [EBML_STR] = 0x1000000,
  816. [EBML_UTF8] = 0x1000000,
  817. // max. 256 MB for binary data
  818. [EBML_BIN] = 0x10000000,
  819. // no limits for anything else
  820. };
  821. AVIOContext *pb = matroska->ctx->pb;
  822. uint32_t id = syntax->id;
  823. uint64_t length;
  824. int res;
  825. void *newelem;
  826. data = (char *)data + syntax->data_offset;
  827. if (syntax->list_elem_size) {
  828. EbmlList *list = data;
  829. newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  830. if (!newelem)
  831. return AVERROR(ENOMEM);
  832. list->elem = newelem;
  833. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  834. memset(data, 0, syntax->list_elem_size);
  835. list->nb_elem++;
  836. }
  837. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  838. matroska->current_id = 0;
  839. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  840. return res;
  841. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  842. av_log(matroska->ctx, AV_LOG_ERROR,
  843. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  844. length, max_lengths[syntax->type], syntax->type);
  845. return AVERROR_INVALIDDATA;
  846. }
  847. }
  848. switch (syntax->type) {
  849. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  850. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  851. case EBML_STR:
  852. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  853. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  854. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  855. return res;
  856. if (id == MATROSKA_ID_SEGMENT)
  857. matroska->segment_start = avio_tell(matroska->ctx->pb);
  858. return ebml_parse_nest(matroska, syntax->def.n, data);
  859. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  860. case EBML_STOP: return 1;
  861. default:
  862. if(ffio_limit(pb, length) != length)
  863. return AVERROR(EIO);
  864. return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
  865. }
  866. if (res == AVERROR_INVALIDDATA)
  867. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  868. else if (res == AVERROR(EIO))
  869. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  870. return res;
  871. }
  872. static void ebml_free(EbmlSyntax *syntax, void *data)
  873. {
  874. int i, j;
  875. for (i=0; syntax[i].id; i++) {
  876. void *data_off = (char *)data + syntax[i].data_offset;
  877. switch (syntax[i].type) {
  878. case EBML_STR:
  879. case EBML_UTF8: av_freep(data_off); break;
  880. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  881. case EBML_NEST:
  882. if (syntax[i].list_elem_size) {
  883. EbmlList *list = data_off;
  884. char *ptr = list->elem;
  885. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  886. ebml_free(syntax[i].def.n, ptr);
  887. av_free(list->elem);
  888. } else
  889. ebml_free(syntax[i].def.n, data_off);
  890. default: break;
  891. }
  892. }
  893. }
  894. /*
  895. * Autodetecting...
  896. */
  897. static int matroska_probe(AVProbeData *p)
  898. {
  899. uint64_t total = 0;
  900. int len_mask = 0x80, size = 1, n = 1, i;
  901. /* EBML header? */
  902. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  903. return 0;
  904. /* length of header */
  905. total = p->buf[4];
  906. while (size <= 8 && !(total & len_mask)) {
  907. size++;
  908. len_mask >>= 1;
  909. }
  910. if (size > 8)
  911. return 0;
  912. total &= (len_mask - 1);
  913. while (n < size)
  914. total = (total << 8) | p->buf[4 + n++];
  915. /* Does the probe data contain the whole header? */
  916. if (p->buf_size < 4 + size + total)
  917. return 0;
  918. /* The header should contain a known document type. For now,
  919. * we don't parse the whole header but simply check for the
  920. * availability of that array of characters inside the header.
  921. * Not fully fool-proof, but good enough. */
  922. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  923. int probelen = strlen(matroska_doctypes[i]);
  924. if (total < probelen)
  925. continue;
  926. for (n = 4+size; n <= 4+size+total-probelen; n++)
  927. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  928. return AVPROBE_SCORE_MAX;
  929. }
  930. // probably valid EBML header but no recognized doctype
  931. return AVPROBE_SCORE_EXTENSION;
  932. }
  933. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  934. int num)
  935. {
  936. MatroskaTrack *tracks = matroska->tracks.elem;
  937. int i;
  938. for (i=0; i < matroska->tracks.nb_elem; i++)
  939. if (tracks[i].num == num)
  940. return &tracks[i];
  941. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  942. return NULL;
  943. }
  944. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  945. MatroskaTrack *track)
  946. {
  947. MatroskaTrackEncoding *encodings = track->encodings.elem;
  948. uint8_t* data = *buf;
  949. int isize = *buf_size;
  950. uint8_t* pkt_data = NULL;
  951. uint8_t av_unused *newpktdata;
  952. int pkt_size = isize;
  953. int result = 0;
  954. int olen;
  955. if (pkt_size >= 10000000U)
  956. return AVERROR_INVALIDDATA;
  957. switch (encodings[0].compression.algo) {
  958. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
  959. int header_size = encodings[0].compression.settings.size;
  960. uint8_t *header = encodings[0].compression.settings.data;
  961. if (header_size && !header) {
  962. av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
  963. return -1;
  964. }
  965. if (!header_size)
  966. return 0;
  967. pkt_size = isize + header_size;
  968. pkt_data = av_malloc(pkt_size);
  969. if (!pkt_data)
  970. return AVERROR(ENOMEM);
  971. memcpy(pkt_data, header, header_size);
  972. memcpy(pkt_data + header_size, data, isize);
  973. break;
  974. }
  975. #if CONFIG_LZO
  976. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  977. do {
  978. olen = pkt_size *= 3;
  979. newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
  980. if (!newpktdata) {
  981. result = AVERROR(ENOMEM);
  982. goto failed;
  983. }
  984. pkt_data = newpktdata;
  985. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  986. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  987. if (result) {
  988. result = AVERROR_INVALIDDATA;
  989. goto failed;
  990. }
  991. pkt_size -= olen;
  992. break;
  993. #endif
  994. #if CONFIG_ZLIB
  995. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  996. z_stream zstream = {0};
  997. if (inflateInit(&zstream) != Z_OK)
  998. return -1;
  999. zstream.next_in = data;
  1000. zstream.avail_in = isize;
  1001. do {
  1002. pkt_size *= 3;
  1003. newpktdata = av_realloc(pkt_data, pkt_size);
  1004. if (!newpktdata) {
  1005. inflateEnd(&zstream);
  1006. goto failed;
  1007. }
  1008. pkt_data = newpktdata;
  1009. zstream.avail_out = pkt_size - zstream.total_out;
  1010. zstream.next_out = pkt_data + zstream.total_out;
  1011. if (pkt_data) {
  1012. result = inflate(&zstream, Z_NO_FLUSH);
  1013. } else
  1014. result = Z_MEM_ERROR;
  1015. } while (result==Z_OK && pkt_size<10000000);
  1016. pkt_size = zstream.total_out;
  1017. inflateEnd(&zstream);
  1018. if (result != Z_STREAM_END) {
  1019. if (result == Z_MEM_ERROR)
  1020. result = AVERROR(ENOMEM);
  1021. else
  1022. result = AVERROR_INVALIDDATA;
  1023. goto failed;
  1024. }
  1025. break;
  1026. }
  1027. #endif
  1028. #if CONFIG_BZLIB
  1029. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  1030. bz_stream bzstream = {0};
  1031. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  1032. return -1;
  1033. bzstream.next_in = data;
  1034. bzstream.avail_in = isize;
  1035. do {
  1036. pkt_size *= 3;
  1037. newpktdata = av_realloc(pkt_data, pkt_size);
  1038. if (!newpktdata) {
  1039. BZ2_bzDecompressEnd(&bzstream);
  1040. goto failed;
  1041. }
  1042. pkt_data = newpktdata;
  1043. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  1044. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  1045. if (pkt_data) {
  1046. result = BZ2_bzDecompress(&bzstream);
  1047. } else
  1048. result = BZ_MEM_ERROR;
  1049. } while (result==BZ_OK && pkt_size<10000000);
  1050. pkt_size = bzstream.total_out_lo32;
  1051. BZ2_bzDecompressEnd(&bzstream);
  1052. if (result != BZ_STREAM_END) {
  1053. if (result == BZ_MEM_ERROR)
  1054. result = AVERROR(ENOMEM);
  1055. else
  1056. result = AVERROR_INVALIDDATA;
  1057. goto failed;
  1058. }
  1059. break;
  1060. }
  1061. #endif
  1062. default:
  1063. return AVERROR_INVALIDDATA;
  1064. }
  1065. *buf = pkt_data;
  1066. *buf_size = pkt_size;
  1067. return 0;
  1068. failed:
  1069. av_free(pkt_data);
  1070. return result;
  1071. }
  1072. #if FF_API_ASS_SSA
  1073. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  1074. AVPacket *pkt, uint64_t display_duration)
  1075. {
  1076. AVBufferRef *line;
  1077. char *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  1078. for (; *ptr!=',' && ptr<end-1; ptr++);
  1079. if (*ptr == ',')
  1080. ptr++;
  1081. layer = ptr;
  1082. for (; *ptr!=',' && ptr<end-1; ptr++);
  1083. if (*ptr == ',') {
  1084. int64_t end_pts = pkt->pts + display_duration;
  1085. int sc = matroska->time_scale * pkt->pts / 10000000;
  1086. int ec = matroska->time_scale * end_pts / 10000000;
  1087. int sh, sm, ss, eh, em, es, len;
  1088. sh = sc/360000; sc -= 360000*sh;
  1089. sm = sc/ 6000; sc -= 6000*sm;
  1090. ss = sc/ 100; sc -= 100*ss;
  1091. eh = ec/360000; ec -= 360000*eh;
  1092. em = ec/ 6000; ec -= 6000*em;
  1093. es = ec/ 100; ec -= 100*es;
  1094. *ptr++ = '\0';
  1095. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  1096. if (!(line = av_buffer_alloc(len)))
  1097. return;
  1098. snprintf(line->data, len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  1099. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  1100. av_buffer_unref(&pkt->buf);
  1101. pkt->buf = line;
  1102. pkt->data = line->data;
  1103. pkt->size = strlen(line->data);
  1104. }
  1105. }
  1106. static int matroska_merge_packets(AVPacket *out, AVPacket *in)
  1107. {
  1108. int ret = av_grow_packet(out, in->size);
  1109. if (ret < 0)
  1110. return ret;
  1111. memcpy(out->data + out->size - in->size, in->data, in->size);
  1112. av_free_packet(in);
  1113. av_free(in);
  1114. return 0;
  1115. }
  1116. #endif
  1117. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  1118. AVDictionary **metadata, char *prefix)
  1119. {
  1120. MatroskaTag *tags = list->elem;
  1121. char key[1024];
  1122. int i;
  1123. for (i=0; i < list->nb_elem; i++) {
  1124. const char *lang = tags[i].lang && strcmp(tags[i].lang, "und") ?
  1125. tags[i].lang : NULL;
  1126. if (!tags[i].name) {
  1127. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  1128. continue;
  1129. }
  1130. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  1131. else av_strlcpy(key, tags[i].name, sizeof(key));
  1132. if (tags[i].def || !lang) {
  1133. av_dict_set(metadata, key, tags[i].string, 0);
  1134. if (tags[i].sub.nb_elem)
  1135. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1136. }
  1137. if (lang) {
  1138. av_strlcat(key, "-", sizeof(key));
  1139. av_strlcat(key, lang, sizeof(key));
  1140. av_dict_set(metadata, key, tags[i].string, 0);
  1141. if (tags[i].sub.nb_elem)
  1142. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1143. }
  1144. }
  1145. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  1146. }
  1147. static void matroska_convert_tags(AVFormatContext *s)
  1148. {
  1149. MatroskaDemuxContext *matroska = s->priv_data;
  1150. MatroskaTags *tags = matroska->tags.elem;
  1151. int i, j;
  1152. for (i=0; i < matroska->tags.nb_elem; i++) {
  1153. if (tags[i].target.attachuid) {
  1154. MatroskaAttachement *attachment = matroska->attachments.elem;
  1155. for (j=0; j<matroska->attachments.nb_elem; j++)
  1156. if (attachment[j].uid == tags[i].target.attachuid
  1157. && attachment[j].stream)
  1158. matroska_convert_tag(s, &tags[i].tag,
  1159. &attachment[j].stream->metadata, NULL);
  1160. } else if (tags[i].target.chapteruid) {
  1161. MatroskaChapter *chapter = matroska->chapters.elem;
  1162. for (j=0; j<matroska->chapters.nb_elem; j++)
  1163. if (chapter[j].uid == tags[i].target.chapteruid
  1164. && chapter[j].chapter)
  1165. matroska_convert_tag(s, &tags[i].tag,
  1166. &chapter[j].chapter->metadata, NULL);
  1167. } else if (tags[i].target.trackuid) {
  1168. MatroskaTrack *track = matroska->tracks.elem;
  1169. for (j=0; j<matroska->tracks.nb_elem; j++)
  1170. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1171. matroska_convert_tag(s, &tags[i].tag,
  1172. &track[j].stream->metadata, NULL);
  1173. } else {
  1174. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1175. tags[i].target.type);
  1176. }
  1177. }
  1178. }
  1179. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
  1180. {
  1181. EbmlList *seekhead_list = &matroska->seekhead;
  1182. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1183. uint32_t level_up = matroska->level_up;
  1184. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1185. uint32_t saved_id = matroska->current_id;
  1186. MatroskaLevel level;
  1187. int64_t offset;
  1188. int ret = 0;
  1189. if (idx >= seekhead_list->nb_elem
  1190. || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
  1191. || seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1192. return 0;
  1193. /* seek */
  1194. offset = seekhead[idx].pos + matroska->segment_start;
  1195. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1196. /* We don't want to lose our seekhead level, so we add
  1197. * a dummy. This is a crude hack. */
  1198. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1199. av_log(matroska->ctx, AV_LOG_INFO,
  1200. "Max EBML element depth (%d) reached, "
  1201. "cannot parse further.\n", EBML_MAX_DEPTH);
  1202. ret = AVERROR_INVALIDDATA;
  1203. } else {
  1204. level.start = 0;
  1205. level.length = (uint64_t)-1;
  1206. matroska->levels[matroska->num_levels] = level;
  1207. matroska->num_levels++;
  1208. matroska->current_id = 0;
  1209. ret = ebml_parse(matroska, matroska_segment, matroska);
  1210. /* remove dummy level */
  1211. while (matroska->num_levels) {
  1212. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1213. if (length == (uint64_t)-1)
  1214. break;
  1215. }
  1216. }
  1217. }
  1218. /* seek back */
  1219. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1220. matroska->level_up = level_up;
  1221. matroska->current_id = saved_id;
  1222. return ret;
  1223. }
  1224. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1225. {
  1226. EbmlList *seekhead_list = &matroska->seekhead;
  1227. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1228. int i;
  1229. // we should not do any seeking in the streaming case
  1230. if (!matroska->ctx->pb->seekable ||
  1231. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1232. return;
  1233. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1234. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1235. if (seekhead[i].pos <= before_pos)
  1236. continue;
  1237. // defer cues parsing until we actually need cue data.
  1238. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1239. matroska->cues_parsing_deferred = 1;
  1240. continue;
  1241. }
  1242. if (matroska_parse_seekhead_entry(matroska, i) < 0) {
  1243. // mark index as broken
  1244. matroska->cues_parsing_deferred = -1;
  1245. break;
  1246. }
  1247. }
  1248. }
  1249. static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
  1250. EbmlList *index_list;
  1251. MatroskaIndex *index;
  1252. int index_scale = 1;
  1253. int i, j;
  1254. index_list = &matroska->index;
  1255. index = index_list->elem;
  1256. if (index_list->nb_elem
  1257. && index[0].time > 1E14/matroska->time_scale) {
  1258. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1259. index_scale = matroska->time_scale;
  1260. }
  1261. for (i = 0; i < index_list->nb_elem; i++) {
  1262. EbmlList *pos_list = &index[i].pos;
  1263. MatroskaIndexPos *pos = pos_list->elem;
  1264. for (j = 0; j < pos_list->nb_elem; j++) {
  1265. MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
  1266. if (track && track->stream)
  1267. av_add_index_entry(track->stream,
  1268. pos[j].pos + matroska->segment_start,
  1269. index[i].time/index_scale, 0, 0,
  1270. AVINDEX_KEYFRAME);
  1271. }
  1272. }
  1273. }
  1274. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1275. EbmlList *seekhead_list = &matroska->seekhead;
  1276. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1277. int i;
  1278. for (i = 0; i < seekhead_list->nb_elem; i++)
  1279. if (seekhead[i].id == MATROSKA_ID_CUES)
  1280. break;
  1281. av_assert1(i <= seekhead_list->nb_elem);
  1282. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1283. matroska->cues_parsing_deferred = -1;
  1284. matroska_add_index_entries(matroska);
  1285. }
  1286. static int matroska_aac_profile(char *codec_id)
  1287. {
  1288. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1289. int profile;
  1290. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1291. if (strstr(codec_id, aac_profiles[profile]))
  1292. break;
  1293. return profile + 1;
  1294. }
  1295. static int matroska_aac_sri(int samplerate)
  1296. {
  1297. int sri;
  1298. for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1299. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1300. break;
  1301. return sri;
  1302. }
  1303. static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
  1304. {
  1305. char buffer[32];
  1306. /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
  1307. time_t creation_time = date_utc / 1000000000 + 978307200;
  1308. struct tm *ptm = gmtime(&creation_time);
  1309. if (!ptm) return;
  1310. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
  1311. av_dict_set(metadata, "creation_time", buffer, 0);
  1312. }
  1313. static int matroska_read_header(AVFormatContext *s)
  1314. {
  1315. MatroskaDemuxContext *matroska = s->priv_data;
  1316. EbmlList *attachements_list = &matroska->attachments;
  1317. MatroskaAttachement *attachements;
  1318. EbmlList *chapters_list = &matroska->chapters;
  1319. MatroskaChapter *chapters;
  1320. MatroskaTrack *tracks;
  1321. uint64_t max_start = 0;
  1322. int64_t pos;
  1323. Ebml ebml = { 0 };
  1324. AVStream *st;
  1325. int i, j, k, res;
  1326. matroska->ctx = s;
  1327. /* First read the EBML header. */
  1328. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1329. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1330. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
  1331. av_log(matroska->ctx, AV_LOG_ERROR,
  1332. "EBML header using unsupported features\n"
  1333. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1334. ebml.version, ebml.doctype, ebml.doctype_version);
  1335. ebml_free(ebml_syntax, &ebml);
  1336. return AVERROR_PATCHWELCOME;
  1337. } else if (ebml.doctype_version == 3) {
  1338. av_log(matroska->ctx, AV_LOG_WARNING,
  1339. "EBML header using unsupported features\n"
  1340. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1341. ebml.version, ebml.doctype, ebml.doctype_version);
  1342. }
  1343. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1344. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1345. break;
  1346. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1347. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1348. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1349. ebml_free(ebml_syntax, &ebml);
  1350. return AVERROR_INVALIDDATA;
  1351. }
  1352. }
  1353. ebml_free(ebml_syntax, &ebml);
  1354. /* The next thing is a segment. */
  1355. pos = avio_tell(matroska->ctx->pb);
  1356. res = ebml_parse(matroska, matroska_segments, matroska);
  1357. // try resyncing until we find a EBML_STOP type element.
  1358. while (res != 1) {
  1359. res = matroska_resync(matroska, pos);
  1360. if (res < 0)
  1361. return res;
  1362. pos = avio_tell(matroska->ctx->pb);
  1363. res = ebml_parse(matroska, matroska_segment, matroska);
  1364. }
  1365. matroska_execute_seekhead(matroska);
  1366. if (!matroska->time_scale)
  1367. matroska->time_scale = 1000000;
  1368. if (matroska->duration)
  1369. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1370. * 1000 / AV_TIME_BASE;
  1371. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1372. if (matroska->date_utc.size == 8)
  1373. matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
  1374. tracks = matroska->tracks.elem;
  1375. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1376. MatroskaTrack *track = &tracks[i];
  1377. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1378. EbmlList *encodings_list = &track->encodings;
  1379. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1380. uint8_t *extradata = NULL;
  1381. int extradata_size = 0;
  1382. int extradata_offset = 0;
  1383. uint32_t fourcc = 0;
  1384. AVIOContext b;
  1385. char* key_id_base64 = NULL;
  1386. /* Apply some sanity checks. */
  1387. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1388. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1389. track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
  1390. track->type != MATROSKA_TRACK_TYPE_METADATA) {
  1391. av_log(matroska->ctx, AV_LOG_INFO,
  1392. "Unknown or unsupported track type %"PRIu64"\n",
  1393. track->type);
  1394. continue;
  1395. }
  1396. if (track->codec_id == NULL)
  1397. continue;
  1398. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1399. if (!track->default_duration && track->video.frame_rate > 0)
  1400. track->default_duration = 1000000000/track->video.frame_rate;
  1401. if (track->video.display_width == -1)
  1402. track->video.display_width = track->video.pixel_width;
  1403. if (track->video.display_height == -1)
  1404. track->video.display_height = track->video.pixel_height;
  1405. if (track->video.color_space.size == 4)
  1406. fourcc = AV_RL32(track->video.color_space.data);
  1407. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1408. if (!track->audio.out_samplerate)
  1409. track->audio.out_samplerate = track->audio.samplerate;
  1410. }
  1411. if (encodings_list->nb_elem > 1) {
  1412. av_log(matroska->ctx, AV_LOG_ERROR,
  1413. "Multiple combined encodings not supported");
  1414. } else if (encodings_list->nb_elem == 1) {
  1415. if (encodings[0].type) {
  1416. if (encodings[0].encryption.key_id.size > 0) {
  1417. /* Save the encryption key id to be stored later as a
  1418. metadata tag. */
  1419. const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
  1420. key_id_base64 = av_malloc(b64_size);
  1421. if (key_id_base64 == NULL)
  1422. return AVERROR(ENOMEM);
  1423. av_base64_encode(key_id_base64, b64_size,
  1424. encodings[0].encryption.key_id.data,
  1425. encodings[0].encryption.key_id.size);
  1426. } else {
  1427. encodings[0].scope = 0;
  1428. av_log(matroska->ctx, AV_LOG_ERROR,
  1429. "Unsupported encoding type");
  1430. }
  1431. } else if (
  1432. #if CONFIG_ZLIB
  1433. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1434. #endif
  1435. #if CONFIG_BZLIB
  1436. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1437. #endif
  1438. #if CONFIG_LZO
  1439. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
  1440. #endif
  1441. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
  1442. encodings[0].scope = 0;
  1443. av_log(matroska->ctx, AV_LOG_ERROR,
  1444. "Unsupported encoding type");
  1445. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1446. uint8_t *codec_priv = track->codec_priv.data;
  1447. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1448. &track->codec_priv.size,
  1449. track);
  1450. if (ret < 0) {
  1451. track->codec_priv.data = NULL;
  1452. track->codec_priv.size = 0;
  1453. av_log(matroska->ctx, AV_LOG_ERROR,
  1454. "Failed to decode codec private data\n");
  1455. }
  1456. if (codec_priv != track->codec_priv.data)
  1457. av_free(codec_priv);
  1458. }
  1459. }
  1460. for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
  1461. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1462. strlen(ff_mkv_codec_tags[j].str))){
  1463. codec_id= ff_mkv_codec_tags[j].id;
  1464. break;
  1465. }
  1466. }
  1467. st = track->stream = avformat_new_stream(s, NULL);
  1468. if (st == NULL) {
  1469. av_free(key_id_base64);
  1470. return AVERROR(ENOMEM);
  1471. }
  1472. if (key_id_base64) {
  1473. /* export encryption key id as base64 metadata tag */
  1474. av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
  1475. av_freep(&key_id_base64);
  1476. }
  1477. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1478. && track->codec_priv.size >= 40
  1479. && track->codec_priv.data != NULL) {
  1480. track->ms_compat = 1;
  1481. fourcc = AV_RL32(track->codec_priv.data + 16);
  1482. codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
  1483. extradata_offset = 40;
  1484. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1485. && track->codec_priv.size >= 14
  1486. && track->codec_priv.data != NULL) {
  1487. int ret;
  1488. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1489. 0, NULL, NULL, NULL, NULL);
  1490. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1491. if (ret < 0)
  1492. return ret;
  1493. codec_id = st->codec->codec_id;
  1494. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1495. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1496. && (track->codec_priv.size >= 86)
  1497. && (track->codec_priv.data != NULL)) {
  1498. fourcc = AV_RL32(track->codec_priv.data);
  1499. codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
  1500. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1501. switch (track->audio.bitdepth) {
  1502. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1503. case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
  1504. case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
  1505. }
  1506. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1507. switch (track->audio.bitdepth) {
  1508. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1509. case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
  1510. case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
  1511. }
  1512. } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1513. codec_id = AV_CODEC_ID_PCM_F64LE;
  1514. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1515. int profile = matroska_aac_profile(track->codec_id);
  1516. int sri = matroska_aac_sri(track->audio.samplerate);
  1517. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1518. if (extradata == NULL)
  1519. return AVERROR(ENOMEM);
  1520. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1521. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1522. if (strstr(track->codec_id, "SBR")) {
  1523. sri = matroska_aac_sri(track->audio.out_samplerate);
  1524. extradata[2] = 0x56;
  1525. extradata[3] = 0xE5;
  1526. extradata[4] = 0x80 | (sri<<3);
  1527. extradata_size = 5;
  1528. } else
  1529. extradata_size = 2;
  1530. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - FF_INPUT_BUFFER_PADDING_SIZE) {
  1531. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1532. Create the "atom size", "tag", and "tag version" fields the
  1533. decoder expects manually. */
  1534. extradata_size = 12 + track->codec_priv.size;
  1535. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1536. if (extradata == NULL)
  1537. return AVERROR(ENOMEM);
  1538. AV_WB32(extradata, extradata_size);
  1539. memcpy(&extradata[4], "alac", 4);
  1540. AV_WB32(&extradata[8], 0);
  1541. memcpy(&extradata[12], track->codec_priv.data,
  1542. track->codec_priv.size);
  1543. } else if (codec_id == AV_CODEC_ID_TTA) {
  1544. extradata_size = 30;
  1545. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1546. if (extradata == NULL)
  1547. return AVERROR(ENOMEM);
  1548. ffio_init_context(&b, extradata, extradata_size, 1,
  1549. NULL, NULL, NULL, NULL);
  1550. avio_write(&b, "TTA1", 4);
  1551. avio_wl16(&b, 1);
  1552. avio_wl16(&b, track->audio.channels);
  1553. avio_wl16(&b, track->audio.bitdepth);
  1554. if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
  1555. return AVERROR_INVALIDDATA;
  1556. avio_wl32(&b, track->audio.out_samplerate);
  1557. avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale), track->audio.out_samplerate, AV_TIME_BASE * 1000));
  1558. } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
  1559. codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
  1560. extradata_offset = 26;
  1561. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1562. track->audio.out_samplerate = 8000;
  1563. track->audio.channels = 1;
  1564. } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
  1565. codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
  1566. && track->codec_priv.data) {
  1567. int flavor;
  1568. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1569. 0, NULL, NULL, NULL, NULL);
  1570. avio_skip(&b, 22);
  1571. flavor = avio_rb16(&b);
  1572. track->audio.coded_framesize = avio_rb32(&b);
  1573. avio_skip(&b, 12);
  1574. track->audio.sub_packet_h = avio_rb16(&b);
  1575. track->audio.frame_size = avio_rb16(&b);
  1576. track->audio.sub_packet_size = avio_rb16(&b);
  1577. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1578. if (codec_id == AV_CODEC_ID_RA_288) {
  1579. st->codec->block_align = track->audio.coded_framesize;
  1580. track->codec_priv.size = 0;
  1581. } else {
  1582. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1583. static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1584. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1585. st->codec->bit_rate = sipr_bit_rate[flavor];
  1586. }
  1587. st->codec->block_align = track->audio.sub_packet_size;
  1588. extradata_offset = 78;
  1589. }
  1590. }
  1591. track->codec_priv.size -= extradata_offset;
  1592. if (codec_id == AV_CODEC_ID_NONE)
  1593. av_log(matroska->ctx, AV_LOG_INFO,
  1594. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1595. if (track->time_scale < 0.01)
  1596. track->time_scale = 1.0;
  1597. avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1598. st->codec->codec_id = codec_id;
  1599. st->start_time = 0;
  1600. if (strcmp(track->language, "und"))
  1601. av_dict_set(&st->metadata, "language", track->language, 0);
  1602. av_dict_set(&st->metadata, "title", track->name, 0);
  1603. if (track->flag_default)
  1604. st->disposition |= AV_DISPOSITION_DEFAULT;
  1605. if (track->flag_forced)
  1606. st->disposition |= AV_DISPOSITION_FORCED;
  1607. if (!st->codec->extradata) {
  1608. if(extradata){
  1609. st->codec->extradata = extradata;
  1610. st->codec->extradata_size = extradata_size;
  1611. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1612. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1613. FF_INPUT_BUFFER_PADDING_SIZE);
  1614. if(st->codec->extradata == NULL)
  1615. return AVERROR(ENOMEM);
  1616. st->codec->extradata_size = track->codec_priv.size;
  1617. memcpy(st->codec->extradata,
  1618. track->codec_priv.data + extradata_offset,
  1619. track->codec_priv.size);
  1620. }
  1621. }
  1622. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1623. MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
  1624. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1625. st->codec->codec_tag = fourcc;
  1626. st->codec->width = track->video.pixel_width;
  1627. st->codec->height = track->video.pixel_height;
  1628. av_reduce(&st->sample_aspect_ratio.num,
  1629. &st->sample_aspect_ratio.den,
  1630. st->codec->height * track->video.display_width,
  1631. st->codec-> width * track->video.display_height,
  1632. 255);
  1633. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1634. if (track->default_duration) {
  1635. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1636. 1000000000, track->default_duration, 30000);
  1637. #if FF_API_R_FRAME_RATE
  1638. st->r_frame_rate = st->avg_frame_rate;
  1639. #endif
  1640. }
  1641. /* export stereo mode flag as metadata tag */
  1642. if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
  1643. av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
  1644. /* export alpha mode flag as metadata tag */
  1645. if (track->video.alpha_mode)
  1646. av_dict_set(&st->metadata, "alpha_mode", "1", 0);
  1647. /* if we have virtual track, mark the real tracks */
  1648. for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
  1649. char buf[32];
  1650. if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
  1651. continue;
  1652. snprintf(buf, sizeof(buf), "%s_%d",
  1653. ff_matroska_video_stereo_plane[planes[j].type], i);
  1654. for (k=0; k < matroska->tracks.nb_elem; k++)
  1655. if (planes[j].uid == tracks[k].uid) {
  1656. av_dict_set(&s->streams[k]->metadata,
  1657. "stereo_mode", buf, 0);
  1658. break;
  1659. }
  1660. }
  1661. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1662. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1663. st->codec->sample_rate = track->audio.out_samplerate;
  1664. st->codec->channels = track->audio.channels;
  1665. st->codec->bits_per_coded_sample = track->audio.bitdepth;
  1666. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1667. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1668. } else if (codec_id == AV_CODEC_ID_WEBVTT) {
  1669. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1670. if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
  1671. st->disposition |= AV_DISPOSITION_CAPTIONS;
  1672. } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
  1673. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1674. } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
  1675. st->disposition |= AV_DISPOSITION_METADATA;
  1676. }
  1677. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1678. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1679. #if FF_API_ASS_SSA
  1680. if (st->codec->codec_id == AV_CODEC_ID_SSA ||
  1681. st->codec->codec_id == AV_CODEC_ID_ASS)
  1682. #else
  1683. if (st->codec->codec_id == AV_CODEC_ID_ASS)
  1684. #endif
  1685. matroska->contains_ssa = 1;
  1686. }
  1687. }
  1688. attachements = attachements_list->elem;
  1689. for (j=0; j<attachements_list->nb_elem; j++) {
  1690. if (!(attachements[j].filename && attachements[j].mime &&
  1691. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1692. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1693. } else {
  1694. AVStream *st = avformat_new_stream(s, NULL);
  1695. if (st == NULL)
  1696. break;
  1697. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1698. av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
  1699. st->codec->codec_id = AV_CODEC_ID_NONE;
  1700. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1701. st->codec->extradata = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);
  1702. if(st->codec->extradata == NULL)
  1703. break;
  1704. st->codec->extradata_size = attachements[j].bin.size;
  1705. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1706. for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1707. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1708. strlen(ff_mkv_mime_tags[i].str))) {
  1709. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1710. break;
  1711. }
  1712. }
  1713. attachements[j].stream = st;
  1714. }
  1715. }
  1716. chapters = chapters_list->elem;
  1717. for (i=0; i<chapters_list->nb_elem; i++)
  1718. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1719. && (max_start==0 || chapters[i].start > max_start)) {
  1720. chapters[i].chapter =
  1721. avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1722. chapters[i].start, chapters[i].end,
  1723. chapters[i].title);
  1724. av_dict_set(&chapters[i].chapter->metadata,
  1725. "title", chapters[i].title, 0);
  1726. max_start = chapters[i].start;
  1727. }
  1728. matroska_add_index_entries(matroska);
  1729. matroska_convert_tags(s);
  1730. return 0;
  1731. }
  1732. /*
  1733. * Put one packet in an application-supplied AVPacket struct.
  1734. * Returns 0 on success or -1 on failure.
  1735. */
  1736. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1737. AVPacket *pkt)
  1738. {
  1739. if (matroska->num_packets > 0) {
  1740. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1741. av_free(matroska->packets[0]);
  1742. if (matroska->num_packets > 1) {
  1743. void *newpackets;
  1744. memmove(&matroska->packets[0], &matroska->packets[1],
  1745. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1746. newpackets = av_realloc(matroska->packets,
  1747. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1748. if (newpackets)
  1749. matroska->packets = newpackets;
  1750. } else {
  1751. av_freep(&matroska->packets);
  1752. matroska->prev_pkt = NULL;
  1753. }
  1754. matroska->num_packets--;
  1755. return 0;
  1756. }
  1757. return -1;
  1758. }
  1759. /*
  1760. * Free all packets in our internal queue.
  1761. */
  1762. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1763. {
  1764. matroska->prev_pkt = NULL;
  1765. if (matroska->packets) {
  1766. int n;
  1767. for (n = 0; n < matroska->num_packets; n++) {
  1768. av_free_packet(matroska->packets[n]);
  1769. av_free(matroska->packets[n]);
  1770. }
  1771. av_freep(&matroska->packets);
  1772. matroska->num_packets = 0;
  1773. }
  1774. }
  1775. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1776. int* buf_size, int type,
  1777. uint32_t **lace_buf, int *laces)
  1778. {
  1779. int res = 0, n, size = *buf_size;
  1780. uint8_t *data = *buf;
  1781. uint32_t *lace_size;
  1782. if (!type) {
  1783. *laces = 1;
  1784. *lace_buf = av_mallocz(sizeof(int));
  1785. if (!*lace_buf)
  1786. return AVERROR(ENOMEM);
  1787. *lace_buf[0] = size;
  1788. return 0;
  1789. }
  1790. av_assert0(size > 0);
  1791. *laces = *data + 1;
  1792. data += 1;
  1793. size -= 1;
  1794. lace_size = av_mallocz(*laces * sizeof(int));
  1795. if (!lace_size)
  1796. return AVERROR(ENOMEM);
  1797. switch (type) {
  1798. case 0x1: /* Xiph lacing */ {
  1799. uint8_t temp;
  1800. uint32_t total = 0;
  1801. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1802. while (1) {
  1803. if (size <= total) {
  1804. res = AVERROR_INVALIDDATA;
  1805. break;
  1806. }
  1807. temp = *data;
  1808. total += temp;
  1809. lace_size[n] += temp;
  1810. data += 1;
  1811. size -= 1;
  1812. if (temp != 0xff)
  1813. break;
  1814. }
  1815. }
  1816. if (size <= total) {
  1817. res = AVERROR_INVALIDDATA;
  1818. break;
  1819. }
  1820. lace_size[n] = size - total;
  1821. break;
  1822. }
  1823. case 0x2: /* fixed-size lacing */
  1824. if (size % (*laces)) {
  1825. res = AVERROR_INVALIDDATA;
  1826. break;
  1827. }
  1828. for (n = 0; n < *laces; n++)
  1829. lace_size[n] = size / *laces;
  1830. break;
  1831. case 0x3: /* EBML lacing */ {
  1832. uint64_t num;
  1833. uint64_t total;
  1834. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1835. if (n < 0 || num > INT_MAX) {
  1836. av_log(matroska->ctx, AV_LOG_INFO,
  1837. "EBML block data error\n");
  1838. res = n<0 ? n : AVERROR_INVALIDDATA;
  1839. break;
  1840. }
  1841. data += n;
  1842. size -= n;
  1843. total = lace_size[0] = num;
  1844. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1845. int64_t snum;
  1846. int r;
  1847. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1848. if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
  1849. av_log(matroska->ctx, AV_LOG_INFO,
  1850. "EBML block data error\n");
  1851. res = r<0 ? r : AVERROR_INVALIDDATA;
  1852. break;
  1853. }
  1854. data += r;
  1855. size -= r;
  1856. lace_size[n] = lace_size[n - 1] + snum;
  1857. total += lace_size[n];
  1858. }
  1859. if (size <= total) {
  1860. res = AVERROR_INVALIDDATA;
  1861. break;
  1862. }
  1863. lace_size[*laces - 1] = size - total;
  1864. break;
  1865. }
  1866. }
  1867. *buf = data;
  1868. *lace_buf = lace_size;
  1869. *buf_size = size;
  1870. return res;
  1871. }
  1872. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1873. MatroskaTrack *track,
  1874. AVStream *st,
  1875. uint8_t *data, int size,
  1876. uint64_t timecode,
  1877. int64_t pos)
  1878. {
  1879. int a = st->codec->block_align;
  1880. int sps = track->audio.sub_packet_size;
  1881. int cfs = track->audio.coded_framesize;
  1882. int h = track->audio.sub_packet_h;
  1883. int y = track->audio.sub_packet_cnt;
  1884. int w = track->audio.frame_size;
  1885. int x;
  1886. if (!track->audio.pkt_cnt) {
  1887. if (track->audio.sub_packet_cnt == 0)
  1888. track->audio.buf_timecode = timecode;
  1889. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1890. if (size < cfs * h / 2) {
  1891. av_log(matroska->ctx, AV_LOG_ERROR,
  1892. "Corrupt int4 RM-style audio packet size\n");
  1893. return AVERROR_INVALIDDATA;
  1894. }
  1895. for (x=0; x<h/2; x++)
  1896. memcpy(track->audio.buf+x*2*w+y*cfs,
  1897. data+x*cfs, cfs);
  1898. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1899. if (size < w) {
  1900. av_log(matroska->ctx, AV_LOG_ERROR,
  1901. "Corrupt sipr RM-style audio packet size\n");
  1902. return AVERROR_INVALIDDATA;
  1903. }
  1904. memcpy(track->audio.buf + y*w, data, w);
  1905. } else {
  1906. if (size < sps * w / sps || h<=0) {
  1907. av_log(matroska->ctx, AV_LOG_ERROR,
  1908. "Corrupt generic RM-style audio packet size\n");
  1909. return AVERROR_INVALIDDATA;
  1910. }
  1911. for (x=0; x<w/sps; x++)
  1912. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1913. }
  1914. if (++track->audio.sub_packet_cnt >= h) {
  1915. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1916. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1917. track->audio.sub_packet_cnt = 0;
  1918. track->audio.pkt_cnt = h*w / a;
  1919. }
  1920. }
  1921. while (track->audio.pkt_cnt) {
  1922. AVPacket *pkt = NULL;
  1923. if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
  1924. av_free(pkt);
  1925. return AVERROR(ENOMEM);
  1926. }
  1927. memcpy(pkt->data, track->audio.buf
  1928. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1929. pkt->pts = track->audio.buf_timecode;
  1930. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1931. pkt->pos = pos;
  1932. pkt->stream_index = st->index;
  1933. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1934. }
  1935. return 0;
  1936. }
  1937. /* reconstruct full wavpack blocks from mangled matroska ones */
  1938. static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
  1939. uint8_t **pdst, int *size)
  1940. {
  1941. uint8_t *dst = NULL;
  1942. int dstlen = 0;
  1943. int srclen = *size;
  1944. uint32_t samples;
  1945. uint16_t ver;
  1946. int ret, offset = 0;
  1947. if (srclen < 12 || track->stream->codec->extradata_size < 2)
  1948. return AVERROR_INVALIDDATA;
  1949. ver = AV_RL16(track->stream->codec->extradata);
  1950. samples = AV_RL32(src);
  1951. src += 4;
  1952. srclen -= 4;
  1953. while (srclen >= 8) {
  1954. int multiblock;
  1955. uint32_t blocksize;
  1956. uint8_t *tmp;
  1957. uint32_t flags = AV_RL32(src);
  1958. uint32_t crc = AV_RL32(src + 4);
  1959. src += 8;
  1960. srclen -= 8;
  1961. multiblock = (flags & 0x1800) != 0x1800;
  1962. if (multiblock) {
  1963. if (srclen < 4) {
  1964. ret = AVERROR_INVALIDDATA;
  1965. goto fail;
  1966. }
  1967. blocksize = AV_RL32(src);
  1968. src += 4;
  1969. srclen -= 4;
  1970. } else
  1971. blocksize = srclen;
  1972. if (blocksize > srclen) {
  1973. ret = AVERROR_INVALIDDATA;
  1974. goto fail;
  1975. }
  1976. tmp = av_realloc(dst, dstlen + blocksize + 32);
  1977. if (!tmp) {
  1978. ret = AVERROR(ENOMEM);
  1979. goto fail;
  1980. }
  1981. dst = tmp;
  1982. dstlen += blocksize + 32;
  1983. AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
  1984. AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
  1985. AV_WL16(dst + offset + 8, ver); // version
  1986. AV_WL16(dst + offset + 10, 0); // track/index_no
  1987. AV_WL32(dst + offset + 12, 0); // total samples
  1988. AV_WL32(dst + offset + 16, 0); // block index
  1989. AV_WL32(dst + offset + 20, samples); // number of samples
  1990. AV_WL32(dst + offset + 24, flags); // flags
  1991. AV_WL32(dst + offset + 28, crc); // crc
  1992. memcpy (dst + offset + 32, src, blocksize); // block data
  1993. src += blocksize;
  1994. srclen -= blocksize;
  1995. offset += blocksize + 32;
  1996. }
  1997. *pdst = dst;
  1998. *size = dstlen;
  1999. return 0;
  2000. fail:
  2001. av_freep(&dst);
  2002. return ret;
  2003. }
  2004. static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
  2005. MatroskaTrack *track,
  2006. AVStream *st,
  2007. uint8_t *data, int data_len,
  2008. uint64_t timecode,
  2009. uint64_t duration,
  2010. int64_t pos)
  2011. {
  2012. AVPacket *pkt;
  2013. uint8_t *id, *settings, *text, *buf;
  2014. int id_len, settings_len, text_len;
  2015. uint8_t *p, *q;
  2016. int err;
  2017. if (data_len <= 0)
  2018. return AVERROR_INVALIDDATA;
  2019. p = data;
  2020. q = data + data_len;
  2021. id = p;
  2022. id_len = -1;
  2023. while (p < q) {
  2024. if (*p == '\r' || *p == '\n') {
  2025. id_len = p - id;
  2026. if (*p == '\r')
  2027. p++;
  2028. break;
  2029. }
  2030. p++;
  2031. }
  2032. if (p >= q || *p != '\n')
  2033. return AVERROR_INVALIDDATA;
  2034. p++;
  2035. settings = p;
  2036. settings_len = -1;
  2037. while (p < q) {
  2038. if (*p == '\r' || *p == '\n') {
  2039. settings_len = p - settings;
  2040. if (*p == '\r')
  2041. p++;
  2042. break;
  2043. }
  2044. p++;
  2045. }
  2046. if (p >= q || *p != '\n')
  2047. return AVERROR_INVALIDDATA;
  2048. p++;
  2049. text = p;
  2050. text_len = q - p;
  2051. while (text_len > 0) {
  2052. const int len = text_len - 1;
  2053. const uint8_t c = p[len];
  2054. if (c != '\r' && c != '\n')
  2055. break;
  2056. text_len = len;
  2057. }
  2058. if (text_len <= 0)
  2059. return AVERROR_INVALIDDATA;
  2060. pkt = av_mallocz(sizeof(*pkt));
  2061. err = av_new_packet(pkt, text_len);
  2062. if (err < 0) {
  2063. av_free(pkt);
  2064. return AVERROR(err);
  2065. }
  2066. memcpy(pkt->data, text, text_len);
  2067. if (id_len > 0) {
  2068. buf = av_packet_new_side_data(pkt,
  2069. AV_PKT_DATA_WEBVTT_IDENTIFIER,
  2070. id_len);
  2071. if (buf == NULL) {
  2072. av_free(pkt);
  2073. return AVERROR(ENOMEM);
  2074. }
  2075. memcpy(buf, id, id_len);
  2076. }
  2077. if (settings_len > 0) {
  2078. buf = av_packet_new_side_data(pkt,
  2079. AV_PKT_DATA_WEBVTT_SETTINGS,
  2080. settings_len);
  2081. if (buf == NULL) {
  2082. av_free(pkt);
  2083. return AVERROR(ENOMEM);
  2084. }
  2085. memcpy(buf, settings, settings_len);
  2086. }
  2087. // Do we need this for subtitles?
  2088. // pkt->flags = AV_PKT_FLAG_KEY;
  2089. pkt->stream_index = st->index;
  2090. pkt->pts = timecode;
  2091. // Do we need this for subtitles?
  2092. // pkt->dts = timecode;
  2093. pkt->duration = duration;
  2094. pkt->pos = pos;
  2095. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  2096. matroska->prev_pkt = pkt;
  2097. return 0;
  2098. }
  2099. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  2100. MatroskaTrack *track,
  2101. AVStream *st,
  2102. uint8_t *data, int pkt_size,
  2103. uint64_t timecode, uint64_t lace_duration,
  2104. int64_t pos, int is_keyframe,
  2105. uint8_t *additional, uint64_t additional_id, int additional_size)
  2106. {
  2107. MatroskaTrackEncoding *encodings = track->encodings.elem;
  2108. uint8_t *pkt_data = data;
  2109. int offset = 0, res;
  2110. AVPacket *pkt;
  2111. if (encodings && !encodings->type && encodings->scope & 1) {
  2112. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  2113. if (res < 0)
  2114. return res;
  2115. }
  2116. if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
  2117. uint8_t *wv_data;
  2118. res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
  2119. if (res < 0) {
  2120. av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
  2121. goto fail;
  2122. }
  2123. if (pkt_data != data)
  2124. av_freep(&pkt_data);
  2125. pkt_data = wv_data;
  2126. }
  2127. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  2128. offset = 8;
  2129. pkt = av_mallocz(sizeof(AVPacket));
  2130. /* XXX: prevent data copy... */
  2131. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  2132. av_free(pkt);
  2133. res = AVERROR(ENOMEM);
  2134. goto fail;
  2135. }
  2136. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  2137. uint8_t *buf = pkt->data;
  2138. bytestream_put_be32(&buf, pkt_size);
  2139. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  2140. }
  2141. memcpy(pkt->data + offset, pkt_data, pkt_size);
  2142. if (pkt_data != data)
  2143. av_freep(&pkt_data);
  2144. pkt->flags = is_keyframe;
  2145. pkt->stream_index = st->index;
  2146. if (additional_size > 0) {
  2147. uint8_t *side_data = av_packet_new_side_data(pkt,
  2148. AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
  2149. additional_size + 8);
  2150. if(side_data == NULL) {
  2151. av_free_packet(pkt);
  2152. av_free(pkt);
  2153. return AVERROR(ENOMEM);
  2154. }
  2155. AV_WB64(side_data, additional_id);
  2156. memcpy(side_data + 8, additional, additional_size);
  2157. }
  2158. if (track->ms_compat)
  2159. pkt->dts = timecode;
  2160. else
  2161. pkt->pts = timecode;
  2162. pkt->pos = pos;
  2163. if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
  2164. /*
  2165. * For backward compatibility.
  2166. * Historically, we have put subtitle duration
  2167. * in convergence_duration, on the off chance
  2168. * that the time_scale is less than 1us, which
  2169. * could result in a 32bit overflow on the
  2170. * normal duration field.
  2171. */
  2172. pkt->convergence_duration = lace_duration;
  2173. }
  2174. if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
  2175. lace_duration <= INT_MAX) {
  2176. /*
  2177. * For non subtitle tracks, just store the duration
  2178. * as normal.
  2179. *
  2180. * If it's a subtitle track and duration value does
  2181. * not overflow a uint32, then also store it normally.
  2182. */
  2183. pkt->duration = lace_duration;
  2184. }
  2185. #if FF_API_ASS_SSA
  2186. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  2187. matroska_fix_ass_packet(matroska, pkt, lace_duration);
  2188. if (matroska->prev_pkt &&
  2189. timecode != AV_NOPTS_VALUE &&
  2190. matroska->prev_pkt->pts == timecode &&
  2191. matroska->prev_pkt->stream_index == st->index &&
  2192. st->codec->codec_id == AV_CODEC_ID_SSA)
  2193. matroska_merge_packets(matroska->prev_pkt, pkt);
  2194. else {
  2195. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  2196. matroska->prev_pkt = pkt;
  2197. }
  2198. #else
  2199. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  2200. matroska->prev_pkt = pkt;
  2201. #endif
  2202. return 0;
  2203. fail:
  2204. if (pkt_data != data)
  2205. av_freep(&pkt_data);
  2206. return res;
  2207. }
  2208. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  2209. int size, int64_t pos, uint64_t cluster_time,
  2210. uint64_t block_duration, int is_keyframe,
  2211. uint8_t *additional, uint64_t additional_id, int additional_size,
  2212. int64_t cluster_pos)
  2213. {
  2214. uint64_t timecode = AV_NOPTS_VALUE;
  2215. MatroskaTrack *track;
  2216. int res = 0;
  2217. AVStream *st;
  2218. int16_t block_time;
  2219. uint32_t *lace_size = NULL;
  2220. int n, flags, laces = 0;
  2221. uint64_t num;
  2222. int trust_default_duration = 1;
  2223. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  2224. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  2225. return n;
  2226. }
  2227. data += n;
  2228. size -= n;
  2229. track = matroska_find_track_by_num(matroska, num);
  2230. if (!track || !track->stream) {
  2231. av_log(matroska->ctx, AV_LOG_INFO,
  2232. "Invalid stream %"PRIu64" or size %u\n", num, size);
  2233. return AVERROR_INVALIDDATA;
  2234. } else if (size <= 3)
  2235. return 0;
  2236. st = track->stream;
  2237. if (st->discard >= AVDISCARD_ALL)
  2238. return res;
  2239. av_assert1(block_duration != AV_NOPTS_VALUE);
  2240. block_time = sign_extend(AV_RB16(data), 16);
  2241. data += 2;
  2242. flags = *data++;
  2243. size -= 3;
  2244. if (is_keyframe == -1)
  2245. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  2246. if (cluster_time != (uint64_t)-1
  2247. && (block_time >= 0 || cluster_time >= -block_time)) {
  2248. timecode = cluster_time + block_time;
  2249. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  2250. && timecode < track->end_timecode)
  2251. is_keyframe = 0; /* overlapping subtitles are not key frame */
  2252. if (is_keyframe)
  2253. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  2254. }
  2255. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  2256. if (timecode < matroska->skip_to_timecode)
  2257. return res;
  2258. if (!st->skip_to_keyframe) {
  2259. av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
  2260. matroska->skip_to_keyframe = 0;
  2261. }
  2262. if (is_keyframe)
  2263. matroska->skip_to_keyframe = 0;
  2264. }
  2265. res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
  2266. &lace_size, &laces);
  2267. if (res)
  2268. goto end;
  2269. if (track->audio.samplerate == 8000) {
  2270. // If this is needed for more codecs, then add them here
  2271. if (st->codec->codec_id == AV_CODEC_ID_AC3) {
  2272. if(track->audio.samplerate != st->codec->sample_rate || !st->codec->frame_size)
  2273. trust_default_duration = 0;
  2274. }
  2275. }
  2276. if (!block_duration && trust_default_duration)
  2277. block_duration = track->default_duration * laces / matroska->time_scale;
  2278. if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
  2279. track->end_timecode =
  2280. FFMAX(track->end_timecode, timecode + block_duration);
  2281. for (n = 0; n < laces; n++) {
  2282. int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
  2283. if (lace_size[n] > size) {
  2284. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  2285. break;
  2286. }
  2287. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  2288. st->codec->codec_id == AV_CODEC_ID_COOK ||
  2289. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  2290. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  2291. st->codec->block_align && track->audio.sub_packet_size) {
  2292. res = matroska_parse_rm_audio(matroska, track, st, data,
  2293. lace_size[n],
  2294. timecode, pos);
  2295. if (res)
  2296. goto end;
  2297. } else if (st->codec->codec_id == AV_CODEC_ID_WEBVTT) {
  2298. res = matroska_parse_webvtt(matroska, track, st,
  2299. data, lace_size[n],
  2300. timecode, lace_duration,
  2301. pos);
  2302. if (res)
  2303. goto end;
  2304. } else {
  2305. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  2306. timecode, lace_duration,
  2307. pos, !n? is_keyframe : 0,
  2308. additional, additional_id, additional_size);
  2309. if (res)
  2310. goto end;
  2311. }
  2312. if (timecode != AV_NOPTS_VALUE)
  2313. timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
  2314. data += lace_size[n];
  2315. size -= lace_size[n];
  2316. }
  2317. end:
  2318. av_free(lace_size);
  2319. return res;
  2320. }
  2321. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  2322. {
  2323. EbmlList *blocks_list;
  2324. MatroskaBlock *blocks;
  2325. int i, res;
  2326. res = ebml_parse(matroska,
  2327. matroska_cluster_incremental_parsing,
  2328. &matroska->current_cluster);
  2329. if (res == 1) {
  2330. /* New Cluster */
  2331. if (matroska->current_cluster_pos)
  2332. ebml_level_end(matroska);
  2333. ebml_free(matroska_cluster, &matroska->current_cluster);
  2334. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2335. matroska->current_cluster_num_blocks = 0;
  2336. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2337. matroska->prev_pkt = NULL;
  2338. /* sizeof the ID which was already read */
  2339. if (matroska->current_id)
  2340. matroska->current_cluster_pos -= 4;
  2341. res = ebml_parse(matroska,
  2342. matroska_clusters_incremental,
  2343. &matroska->current_cluster);
  2344. /* Try parsing the block again. */
  2345. if (res == 1)
  2346. res = ebml_parse(matroska,
  2347. matroska_cluster_incremental_parsing,
  2348. &matroska->current_cluster);
  2349. }
  2350. if (!res &&
  2351. matroska->current_cluster_num_blocks <
  2352. matroska->current_cluster.blocks.nb_elem) {
  2353. blocks_list = &matroska->current_cluster.blocks;
  2354. blocks = blocks_list->elem;
  2355. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2356. i = blocks_list->nb_elem - 1;
  2357. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2358. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2359. uint8_t* additional = blocks[i].additional.size > 0 ?
  2360. blocks[i].additional.data : NULL;
  2361. if (!blocks[i].non_simple)
  2362. blocks[i].duration = 0;
  2363. res = matroska_parse_block(matroska,
  2364. blocks[i].bin.data, blocks[i].bin.size,
  2365. blocks[i].bin.pos,
  2366. matroska->current_cluster.timecode,
  2367. blocks[i].duration, is_keyframe,
  2368. additional, blocks[i].additional_id,
  2369. blocks[i].additional.size,
  2370. matroska->current_cluster_pos);
  2371. }
  2372. }
  2373. return res;
  2374. }
  2375. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2376. {
  2377. MatroskaCluster cluster = { 0 };
  2378. EbmlList *blocks_list;
  2379. MatroskaBlock *blocks;
  2380. int i, res;
  2381. int64_t pos;
  2382. if (!matroska->contains_ssa)
  2383. return matroska_parse_cluster_incremental(matroska);
  2384. pos = avio_tell(matroska->ctx->pb);
  2385. matroska->prev_pkt = NULL;
  2386. if (matroska->current_id)
  2387. pos -= 4; /* sizeof the ID which was already read */
  2388. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2389. blocks_list = &cluster.blocks;
  2390. blocks = blocks_list->elem;
  2391. for (i=0; i<blocks_list->nb_elem; i++)
  2392. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2393. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2394. res=matroska_parse_block(matroska,
  2395. blocks[i].bin.data, blocks[i].bin.size,
  2396. blocks[i].bin.pos, cluster.timecode,
  2397. blocks[i].duration, is_keyframe, NULL, 0, 0,
  2398. pos);
  2399. }
  2400. ebml_free(matroska_cluster, &cluster);
  2401. return res;
  2402. }
  2403. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2404. {
  2405. MatroskaDemuxContext *matroska = s->priv_data;
  2406. while (matroska_deliver_packet(matroska, pkt)) {
  2407. int64_t pos = avio_tell(matroska->ctx->pb);
  2408. if (matroska->done)
  2409. return AVERROR_EOF;
  2410. if (matroska_parse_cluster(matroska) < 0)
  2411. matroska_resync(matroska, pos);
  2412. }
  2413. return 0;
  2414. }
  2415. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2416. int64_t timestamp, int flags)
  2417. {
  2418. MatroskaDemuxContext *matroska = s->priv_data;
  2419. MatroskaTrack *tracks = matroska->tracks.elem;
  2420. AVStream *st = s->streams[stream_index];
  2421. int i, index, index_sub, index_min;
  2422. /* Parse the CUES now since we need the index data to seek. */
  2423. if (matroska->cues_parsing_deferred > 0) {
  2424. matroska->cues_parsing_deferred = 0;
  2425. matroska_parse_cues(matroska);
  2426. }
  2427. if (!st->nb_index_entries)
  2428. goto err;
  2429. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2430. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2431. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  2432. matroska->current_id = 0;
  2433. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2434. matroska_clear_queue(matroska);
  2435. if (matroska_parse_cluster(matroska) < 0)
  2436. break;
  2437. }
  2438. }
  2439. matroska_clear_queue(matroska);
  2440. if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
  2441. goto err;
  2442. index_min = index;
  2443. for (i=0; i < matroska->tracks.nb_elem; i++) {
  2444. tracks[i].audio.pkt_cnt = 0;
  2445. tracks[i].audio.sub_packet_cnt = 0;
  2446. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2447. tracks[i].end_timecode = 0;
  2448. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  2449. && tracks[i].stream->discard != AVDISCARD_ALL) {
  2450. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  2451. while(index_sub >= 0
  2452. && index_min >= 0
  2453. && tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos
  2454. && st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  2455. index_min--;
  2456. }
  2457. }
  2458. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2459. matroska->current_id = 0;
  2460. if (flags & AVSEEK_FLAG_ANY) {
  2461. st->skip_to_keyframe = 0;
  2462. matroska->skip_to_timecode = timestamp;
  2463. } else {
  2464. st->skip_to_keyframe = 1;
  2465. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2466. }
  2467. matroska->skip_to_keyframe = 1;
  2468. matroska->done = 0;
  2469. matroska->num_levels = 0;
  2470. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2471. return 0;
  2472. err:
  2473. // slightly hackish but allows proper fallback to
  2474. // the generic seeking code.
  2475. matroska_clear_queue(matroska);
  2476. matroska->current_id = 0;
  2477. st->skip_to_keyframe =
  2478. matroska->skip_to_keyframe = 0;
  2479. matroska->done = 0;
  2480. matroska->num_levels = 0;
  2481. return -1;
  2482. }
  2483. static int matroska_read_close(AVFormatContext *s)
  2484. {
  2485. MatroskaDemuxContext *matroska = s->priv_data;
  2486. MatroskaTrack *tracks = matroska->tracks.elem;
  2487. int n;
  2488. matroska_clear_queue(matroska);
  2489. for (n=0; n < matroska->tracks.nb_elem; n++)
  2490. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2491. av_free(tracks[n].audio.buf);
  2492. ebml_free(matroska_cluster, &matroska->current_cluster);
  2493. ebml_free(matroska_segment, matroska);
  2494. return 0;
  2495. }
  2496. AVInputFormat ff_matroska_demuxer = {
  2497. .name = "matroska,webm",
  2498. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2499. .priv_data_size = sizeof(MatroskaDemuxContext),
  2500. .read_probe = matroska_probe,
  2501. .read_header = matroska_read_header,
  2502. .read_packet = matroska_read_packet,
  2503. .read_close = matroska_read_close,
  2504. .read_seek = matroska_read_seek,
  2505. };