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.

2816 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")) ? tags[i].lang : NULL;
  1125. if (!tags[i].name) {
  1126. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  1127. continue;
  1128. }
  1129. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  1130. else av_strlcpy(key, tags[i].name, sizeof(key));
  1131. if (tags[i].def || !lang) {
  1132. av_dict_set(metadata, key, tags[i].string, 0);
  1133. if (tags[i].sub.nb_elem)
  1134. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1135. }
  1136. if (lang) {
  1137. av_strlcat(key, "-", sizeof(key));
  1138. av_strlcat(key, lang, sizeof(key));
  1139. av_dict_set(metadata, key, tags[i].string, 0);
  1140. if (tags[i].sub.nb_elem)
  1141. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1142. }
  1143. }
  1144. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  1145. }
  1146. static void matroska_convert_tags(AVFormatContext *s)
  1147. {
  1148. MatroskaDemuxContext *matroska = s->priv_data;
  1149. MatroskaTags *tags = matroska->tags.elem;
  1150. int i, j;
  1151. for (i=0; i < matroska->tags.nb_elem; i++) {
  1152. if (tags[i].target.attachuid) {
  1153. MatroskaAttachement *attachment = matroska->attachments.elem;
  1154. for (j=0; j<matroska->attachments.nb_elem; j++)
  1155. if (attachment[j].uid == tags[i].target.attachuid
  1156. && attachment[j].stream)
  1157. matroska_convert_tag(s, &tags[i].tag,
  1158. &attachment[j].stream->metadata, NULL);
  1159. } else if (tags[i].target.chapteruid) {
  1160. MatroskaChapter *chapter = matroska->chapters.elem;
  1161. for (j=0; j<matroska->chapters.nb_elem; j++)
  1162. if (chapter[j].uid == tags[i].target.chapteruid
  1163. && chapter[j].chapter)
  1164. matroska_convert_tag(s, &tags[i].tag,
  1165. &chapter[j].chapter->metadata, NULL);
  1166. } else if (tags[i].target.trackuid) {
  1167. MatroskaTrack *track = matroska->tracks.elem;
  1168. for (j=0; j<matroska->tracks.nb_elem; j++)
  1169. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1170. matroska_convert_tag(s, &tags[i].tag,
  1171. &track[j].stream->metadata, NULL);
  1172. } else {
  1173. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1174. tags[i].target.type);
  1175. }
  1176. }
  1177. }
  1178. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
  1179. {
  1180. EbmlList *seekhead_list = &matroska->seekhead;
  1181. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1182. uint32_t level_up = matroska->level_up;
  1183. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1184. uint32_t saved_id = matroska->current_id;
  1185. MatroskaLevel level;
  1186. int64_t offset;
  1187. int ret = 0;
  1188. if (idx >= seekhead_list->nb_elem
  1189. || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
  1190. || seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1191. return 0;
  1192. /* seek */
  1193. offset = seekhead[idx].pos + matroska->segment_start;
  1194. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1195. /* We don't want to lose our seekhead level, so we add
  1196. * a dummy. This is a crude hack. */
  1197. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1198. av_log(matroska->ctx, AV_LOG_INFO,
  1199. "Max EBML element depth (%d) reached, "
  1200. "cannot parse further.\n", EBML_MAX_DEPTH);
  1201. ret = AVERROR_INVALIDDATA;
  1202. } else {
  1203. level.start = 0;
  1204. level.length = (uint64_t)-1;
  1205. matroska->levels[matroska->num_levels] = level;
  1206. matroska->num_levels++;
  1207. matroska->current_id = 0;
  1208. ret = ebml_parse(matroska, matroska_segment, matroska);
  1209. /* remove dummy level */
  1210. while (matroska->num_levels) {
  1211. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1212. if (length == (uint64_t)-1)
  1213. break;
  1214. }
  1215. }
  1216. }
  1217. /* seek back */
  1218. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1219. matroska->level_up = level_up;
  1220. matroska->current_id = saved_id;
  1221. return ret;
  1222. }
  1223. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1224. {
  1225. EbmlList *seekhead_list = &matroska->seekhead;
  1226. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1227. int i;
  1228. // we should not do any seeking in the streaming case
  1229. if (!matroska->ctx->pb->seekable ||
  1230. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1231. return;
  1232. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1233. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1234. if (seekhead[i].pos <= before_pos)
  1235. continue;
  1236. // defer cues parsing until we actually need cue data.
  1237. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1238. matroska->cues_parsing_deferred = 1;
  1239. continue;
  1240. }
  1241. if (matroska_parse_seekhead_entry(matroska, i) < 0) {
  1242. // mark index as broken
  1243. matroska->cues_parsing_deferred = -1;
  1244. break;
  1245. }
  1246. }
  1247. }
  1248. static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
  1249. EbmlList *index_list;
  1250. MatroskaIndex *index;
  1251. int index_scale = 1;
  1252. int i, j;
  1253. index_list = &matroska->index;
  1254. index = index_list->elem;
  1255. if (index_list->nb_elem
  1256. && index[0].time > 1E14/matroska->time_scale) {
  1257. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1258. index_scale = matroska->time_scale;
  1259. }
  1260. for (i = 0; i < index_list->nb_elem; i++) {
  1261. EbmlList *pos_list = &index[i].pos;
  1262. MatroskaIndexPos *pos = pos_list->elem;
  1263. for (j = 0; j < pos_list->nb_elem; j++) {
  1264. MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
  1265. if (track && track->stream)
  1266. av_add_index_entry(track->stream,
  1267. pos[j].pos + matroska->segment_start,
  1268. index[i].time/index_scale, 0, 0,
  1269. AVINDEX_KEYFRAME);
  1270. }
  1271. }
  1272. }
  1273. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1274. EbmlList *seekhead_list = &matroska->seekhead;
  1275. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1276. int i;
  1277. for (i = 0; i < seekhead_list->nb_elem; i++)
  1278. if (seekhead[i].id == MATROSKA_ID_CUES)
  1279. break;
  1280. av_assert1(i <= seekhead_list->nb_elem);
  1281. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1282. matroska->cues_parsing_deferred = -1;
  1283. matroska_add_index_entries(matroska);
  1284. }
  1285. static int matroska_aac_profile(char *codec_id)
  1286. {
  1287. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1288. int profile;
  1289. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1290. if (strstr(codec_id, aac_profiles[profile]))
  1291. break;
  1292. return profile + 1;
  1293. }
  1294. static int matroska_aac_sri(int samplerate)
  1295. {
  1296. int sri;
  1297. for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1298. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1299. break;
  1300. return sri;
  1301. }
  1302. static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
  1303. {
  1304. char buffer[32];
  1305. /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
  1306. time_t creation_time = date_utc / 1000000000 + 978307200;
  1307. struct tm *ptm = gmtime(&creation_time);
  1308. if (!ptm) return;
  1309. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
  1310. av_dict_set(metadata, "creation_time", buffer, 0);
  1311. }
  1312. static int matroska_read_header(AVFormatContext *s)
  1313. {
  1314. MatroskaDemuxContext *matroska = s->priv_data;
  1315. EbmlList *attachements_list = &matroska->attachments;
  1316. MatroskaAttachement *attachements;
  1317. EbmlList *chapters_list = &matroska->chapters;
  1318. MatroskaChapter *chapters;
  1319. MatroskaTrack *tracks;
  1320. uint64_t max_start = 0;
  1321. int64_t pos;
  1322. Ebml ebml = { 0 };
  1323. AVStream *st;
  1324. int i, j, k, res;
  1325. matroska->ctx = s;
  1326. /* First read the EBML header. */
  1327. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1328. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1329. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
  1330. av_log(matroska->ctx, AV_LOG_ERROR,
  1331. "EBML header using unsupported features\n"
  1332. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1333. ebml.version, ebml.doctype, ebml.doctype_version);
  1334. ebml_free(ebml_syntax, &ebml);
  1335. return AVERROR_PATCHWELCOME;
  1336. } else if (ebml.doctype_version == 3) {
  1337. av_log(matroska->ctx, AV_LOG_WARNING,
  1338. "EBML header using unsupported features\n"
  1339. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1340. ebml.version, ebml.doctype, ebml.doctype_version);
  1341. }
  1342. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1343. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1344. break;
  1345. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1346. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1347. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1348. ebml_free(ebml_syntax, &ebml);
  1349. return AVERROR_INVALIDDATA;
  1350. }
  1351. }
  1352. ebml_free(ebml_syntax, &ebml);
  1353. /* The next thing is a segment. */
  1354. pos = avio_tell(matroska->ctx->pb);
  1355. res = ebml_parse(matroska, matroska_segments, matroska);
  1356. // try resyncing until we find a EBML_STOP type element.
  1357. while (res != 1) {
  1358. res = matroska_resync(matroska, pos);
  1359. if (res < 0)
  1360. return res;
  1361. pos = avio_tell(matroska->ctx->pb);
  1362. res = ebml_parse(matroska, matroska_segment, matroska);
  1363. }
  1364. matroska_execute_seekhead(matroska);
  1365. if (!matroska->time_scale)
  1366. matroska->time_scale = 1000000;
  1367. if (matroska->duration)
  1368. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1369. * 1000 / AV_TIME_BASE;
  1370. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1371. if (matroska->date_utc.size == 8)
  1372. matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
  1373. tracks = matroska->tracks.elem;
  1374. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1375. MatroskaTrack *track = &tracks[i];
  1376. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1377. EbmlList *encodings_list = &track->encodings;
  1378. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1379. uint8_t *extradata = NULL;
  1380. int extradata_size = 0;
  1381. int extradata_offset = 0;
  1382. uint32_t fourcc = 0;
  1383. AVIOContext b;
  1384. char* key_id_base64 = NULL;
  1385. /* Apply some sanity checks. */
  1386. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1387. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1388. track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
  1389. track->type != MATROSKA_TRACK_TYPE_METADATA) {
  1390. av_log(matroska->ctx, AV_LOG_INFO,
  1391. "Unknown or unsupported track type %"PRIu64"\n",
  1392. track->type);
  1393. continue;
  1394. }
  1395. if (track->codec_id == NULL)
  1396. continue;
  1397. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1398. if (!track->default_duration && track->video.frame_rate > 0)
  1399. track->default_duration = 1000000000/track->video.frame_rate;
  1400. if (track->video.display_width == -1)
  1401. track->video.display_width = track->video.pixel_width;
  1402. if (track->video.display_height == -1)
  1403. track->video.display_height = track->video.pixel_height;
  1404. if (track->video.color_space.size == 4)
  1405. fourcc = AV_RL32(track->video.color_space.data);
  1406. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1407. if (!track->audio.out_samplerate)
  1408. track->audio.out_samplerate = track->audio.samplerate;
  1409. }
  1410. if (encodings_list->nb_elem > 1) {
  1411. av_log(matroska->ctx, AV_LOG_ERROR,
  1412. "Multiple combined encodings not supported");
  1413. } else if (encodings_list->nb_elem == 1) {
  1414. if (encodings[0].type) {
  1415. if (encodings[0].encryption.key_id.size > 0) {
  1416. /* Save the encryption key id to be stored later as a
  1417. metadata tag. */
  1418. const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
  1419. key_id_base64 = av_malloc(b64_size);
  1420. if (key_id_base64 == NULL)
  1421. return AVERROR(ENOMEM);
  1422. av_base64_encode(key_id_base64, b64_size,
  1423. encodings[0].encryption.key_id.data,
  1424. encodings[0].encryption.key_id.size);
  1425. } else {
  1426. encodings[0].scope = 0;
  1427. av_log(matroska->ctx, AV_LOG_ERROR,
  1428. "Unsupported encoding type");
  1429. }
  1430. } else if (
  1431. #if CONFIG_ZLIB
  1432. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1433. #endif
  1434. #if CONFIG_BZLIB
  1435. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1436. #endif
  1437. #if CONFIG_LZO
  1438. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
  1439. #endif
  1440. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
  1441. encodings[0].scope = 0;
  1442. av_log(matroska->ctx, AV_LOG_ERROR,
  1443. "Unsupported encoding type");
  1444. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1445. uint8_t *codec_priv = track->codec_priv.data;
  1446. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1447. &track->codec_priv.size,
  1448. track);
  1449. if (ret < 0) {
  1450. track->codec_priv.data = NULL;
  1451. track->codec_priv.size = 0;
  1452. av_log(matroska->ctx, AV_LOG_ERROR,
  1453. "Failed to decode codec private data\n");
  1454. }
  1455. if (codec_priv != track->codec_priv.data)
  1456. av_free(codec_priv);
  1457. }
  1458. }
  1459. for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
  1460. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1461. strlen(ff_mkv_codec_tags[j].str))){
  1462. codec_id= ff_mkv_codec_tags[j].id;
  1463. break;
  1464. }
  1465. }
  1466. st = track->stream = avformat_new_stream(s, NULL);
  1467. if (st == NULL) {
  1468. av_free(key_id_base64);
  1469. return AVERROR(ENOMEM);
  1470. }
  1471. if (key_id_base64) {
  1472. /* export encryption key id as base64 metadata tag */
  1473. av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
  1474. av_freep(&key_id_base64);
  1475. }
  1476. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1477. && track->codec_priv.size >= 40
  1478. && track->codec_priv.data != NULL) {
  1479. track->ms_compat = 1;
  1480. fourcc = AV_RL32(track->codec_priv.data + 16);
  1481. codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
  1482. extradata_offset = 40;
  1483. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1484. && track->codec_priv.size >= 14
  1485. && track->codec_priv.data != NULL) {
  1486. int ret;
  1487. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1488. 0, NULL, NULL, NULL, NULL);
  1489. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1490. if (ret < 0)
  1491. return ret;
  1492. codec_id = st->codec->codec_id;
  1493. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1494. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1495. && (track->codec_priv.size >= 86)
  1496. && (track->codec_priv.data != NULL)) {
  1497. fourcc = AV_RL32(track->codec_priv.data);
  1498. codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
  1499. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1500. switch (track->audio.bitdepth) {
  1501. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1502. case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
  1503. case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
  1504. }
  1505. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1506. switch (track->audio.bitdepth) {
  1507. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1508. case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
  1509. case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
  1510. }
  1511. } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1512. codec_id = AV_CODEC_ID_PCM_F64LE;
  1513. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1514. int profile = matroska_aac_profile(track->codec_id);
  1515. int sri = matroska_aac_sri(track->audio.samplerate);
  1516. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1517. if (extradata == NULL)
  1518. return AVERROR(ENOMEM);
  1519. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1520. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1521. if (strstr(track->codec_id, "SBR")) {
  1522. sri = matroska_aac_sri(track->audio.out_samplerate);
  1523. extradata[2] = 0x56;
  1524. extradata[3] = 0xE5;
  1525. extradata[4] = 0x80 | (sri<<3);
  1526. extradata_size = 5;
  1527. } else
  1528. extradata_size = 2;
  1529. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - FF_INPUT_BUFFER_PADDING_SIZE) {
  1530. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1531. Create the "atom size", "tag", and "tag version" fields the
  1532. decoder expects manually. */
  1533. extradata_size = 12 + track->codec_priv.size;
  1534. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1535. if (extradata == NULL)
  1536. return AVERROR(ENOMEM);
  1537. AV_WB32(extradata, extradata_size);
  1538. memcpy(&extradata[4], "alac", 4);
  1539. AV_WB32(&extradata[8], 0);
  1540. memcpy(&extradata[12], track->codec_priv.data,
  1541. track->codec_priv.size);
  1542. } else if (codec_id == AV_CODEC_ID_TTA) {
  1543. extradata_size = 30;
  1544. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1545. if (extradata == NULL)
  1546. return AVERROR(ENOMEM);
  1547. ffio_init_context(&b, extradata, extradata_size, 1,
  1548. NULL, NULL, NULL, NULL);
  1549. avio_write(&b, "TTA1", 4);
  1550. avio_wl16(&b, 1);
  1551. avio_wl16(&b, track->audio.channels);
  1552. avio_wl16(&b, track->audio.bitdepth);
  1553. if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
  1554. return AVERROR_INVALIDDATA;
  1555. avio_wl32(&b, track->audio.out_samplerate);
  1556. avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale), track->audio.out_samplerate, AV_TIME_BASE * 1000));
  1557. } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
  1558. codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
  1559. extradata_offset = 26;
  1560. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1561. track->audio.out_samplerate = 8000;
  1562. track->audio.channels = 1;
  1563. } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
  1564. codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
  1565. && track->codec_priv.data) {
  1566. int flavor;
  1567. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1568. 0, NULL, NULL, NULL, NULL);
  1569. avio_skip(&b, 22);
  1570. flavor = avio_rb16(&b);
  1571. track->audio.coded_framesize = avio_rb32(&b);
  1572. avio_skip(&b, 12);
  1573. track->audio.sub_packet_h = avio_rb16(&b);
  1574. track->audio.frame_size = avio_rb16(&b);
  1575. track->audio.sub_packet_size = avio_rb16(&b);
  1576. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1577. if (codec_id == AV_CODEC_ID_RA_288) {
  1578. st->codec->block_align = track->audio.coded_framesize;
  1579. track->codec_priv.size = 0;
  1580. } else {
  1581. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1582. static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1583. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1584. st->codec->bit_rate = sipr_bit_rate[flavor];
  1585. }
  1586. st->codec->block_align = track->audio.sub_packet_size;
  1587. extradata_offset = 78;
  1588. }
  1589. }
  1590. track->codec_priv.size -= extradata_offset;
  1591. if (codec_id == AV_CODEC_ID_NONE)
  1592. av_log(matroska->ctx, AV_LOG_INFO,
  1593. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1594. if (track->time_scale < 0.01)
  1595. track->time_scale = 1.0;
  1596. avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1597. st->codec->codec_id = codec_id;
  1598. st->start_time = 0;
  1599. if (strcmp(track->language, "und"))
  1600. av_dict_set(&st->metadata, "language", track->language, 0);
  1601. av_dict_set(&st->metadata, "title", track->name, 0);
  1602. if (track->flag_default)
  1603. st->disposition |= AV_DISPOSITION_DEFAULT;
  1604. if (track->flag_forced)
  1605. st->disposition |= AV_DISPOSITION_FORCED;
  1606. if (!st->codec->extradata) {
  1607. if(extradata){
  1608. st->codec->extradata = extradata;
  1609. st->codec->extradata_size = extradata_size;
  1610. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1611. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1612. FF_INPUT_BUFFER_PADDING_SIZE);
  1613. if(st->codec->extradata == NULL)
  1614. return AVERROR(ENOMEM);
  1615. st->codec->extradata_size = track->codec_priv.size;
  1616. memcpy(st->codec->extradata,
  1617. track->codec_priv.data + extradata_offset,
  1618. track->codec_priv.size);
  1619. }
  1620. }
  1621. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1622. MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
  1623. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1624. st->codec->codec_tag = fourcc;
  1625. st->codec->width = track->video.pixel_width;
  1626. st->codec->height = track->video.pixel_height;
  1627. av_reduce(&st->sample_aspect_ratio.num,
  1628. &st->sample_aspect_ratio.den,
  1629. st->codec->height * track->video.display_width,
  1630. st->codec-> width * track->video.display_height,
  1631. 255);
  1632. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1633. if (track->default_duration) {
  1634. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1635. 1000000000, track->default_duration, 30000);
  1636. #if FF_API_R_FRAME_RATE
  1637. st->r_frame_rate = st->avg_frame_rate;
  1638. #endif
  1639. }
  1640. /* export stereo mode flag as metadata tag */
  1641. if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
  1642. av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
  1643. /* export alpha mode flag as metadata tag */
  1644. if (track->video.alpha_mode)
  1645. av_dict_set(&st->metadata, "alpha_mode", "1", 0);
  1646. /* if we have virtual track, mark the real tracks */
  1647. for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
  1648. char buf[32];
  1649. if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
  1650. continue;
  1651. snprintf(buf, sizeof(buf), "%s_%d",
  1652. ff_matroska_video_stereo_plane[planes[j].type], i);
  1653. for (k=0; k < matroska->tracks.nb_elem; k++)
  1654. if (planes[j].uid == tracks[k].uid) {
  1655. av_dict_set(&s->streams[k]->metadata,
  1656. "stereo_mode", buf, 0);
  1657. break;
  1658. }
  1659. }
  1660. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1661. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1662. st->codec->sample_rate = track->audio.out_samplerate;
  1663. st->codec->channels = track->audio.channels;
  1664. st->codec->bits_per_coded_sample = track->audio.bitdepth;
  1665. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1666. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1667. } else if (codec_id == AV_CODEC_ID_WEBVTT) {
  1668. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1669. if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
  1670. st->disposition |= AV_DISPOSITION_CAPTIONS;
  1671. } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
  1672. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1673. } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
  1674. st->disposition |= AV_DISPOSITION_METADATA;
  1675. }
  1676. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1677. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1678. #if FF_API_ASS_SSA
  1679. if (st->codec->codec_id == AV_CODEC_ID_SSA ||
  1680. st->codec->codec_id == AV_CODEC_ID_ASS)
  1681. #else
  1682. if (st->codec->codec_id == AV_CODEC_ID_ASS)
  1683. #endif
  1684. matroska->contains_ssa = 1;
  1685. }
  1686. }
  1687. attachements = attachements_list->elem;
  1688. for (j=0; j<attachements_list->nb_elem; j++) {
  1689. if (!(attachements[j].filename && attachements[j].mime &&
  1690. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1691. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1692. } else {
  1693. AVStream *st = avformat_new_stream(s, NULL);
  1694. if (st == NULL)
  1695. break;
  1696. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1697. av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
  1698. st->codec->codec_id = AV_CODEC_ID_NONE;
  1699. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1700. st->codec->extradata = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);
  1701. if(st->codec->extradata == NULL)
  1702. break;
  1703. st->codec->extradata_size = attachements[j].bin.size;
  1704. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1705. for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1706. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1707. strlen(ff_mkv_mime_tags[i].str))) {
  1708. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1709. break;
  1710. }
  1711. }
  1712. attachements[j].stream = st;
  1713. }
  1714. }
  1715. chapters = chapters_list->elem;
  1716. for (i=0; i<chapters_list->nb_elem; i++)
  1717. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1718. && (max_start==0 || chapters[i].start > max_start)) {
  1719. chapters[i].chapter =
  1720. avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1721. chapters[i].start, chapters[i].end,
  1722. chapters[i].title);
  1723. av_dict_set(&chapters[i].chapter->metadata,
  1724. "title", chapters[i].title, 0);
  1725. max_start = chapters[i].start;
  1726. }
  1727. matroska_add_index_entries(matroska);
  1728. matroska_convert_tags(s);
  1729. return 0;
  1730. }
  1731. /*
  1732. * Put one packet in an application-supplied AVPacket struct.
  1733. * Returns 0 on success or -1 on failure.
  1734. */
  1735. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1736. AVPacket *pkt)
  1737. {
  1738. if (matroska->num_packets > 0) {
  1739. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1740. av_free(matroska->packets[0]);
  1741. if (matroska->num_packets > 1) {
  1742. void *newpackets;
  1743. memmove(&matroska->packets[0], &matroska->packets[1],
  1744. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1745. newpackets = av_realloc(matroska->packets,
  1746. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1747. if (newpackets)
  1748. matroska->packets = newpackets;
  1749. } else {
  1750. av_freep(&matroska->packets);
  1751. matroska->prev_pkt = NULL;
  1752. }
  1753. matroska->num_packets--;
  1754. return 0;
  1755. }
  1756. return -1;
  1757. }
  1758. /*
  1759. * Free all packets in our internal queue.
  1760. */
  1761. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1762. {
  1763. matroska->prev_pkt = NULL;
  1764. if (matroska->packets) {
  1765. int n;
  1766. for (n = 0; n < matroska->num_packets; n++) {
  1767. av_free_packet(matroska->packets[n]);
  1768. av_free(matroska->packets[n]);
  1769. }
  1770. av_freep(&matroska->packets);
  1771. matroska->num_packets = 0;
  1772. }
  1773. }
  1774. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1775. int* buf_size, int type,
  1776. uint32_t **lace_buf, int *laces)
  1777. {
  1778. int res = 0, n, size = *buf_size;
  1779. uint8_t *data = *buf;
  1780. uint32_t *lace_size;
  1781. if (!type) {
  1782. *laces = 1;
  1783. *lace_buf = av_mallocz(sizeof(int));
  1784. if (!*lace_buf)
  1785. return AVERROR(ENOMEM);
  1786. *lace_buf[0] = size;
  1787. return 0;
  1788. }
  1789. av_assert0(size > 0);
  1790. *laces = *data + 1;
  1791. data += 1;
  1792. size -= 1;
  1793. lace_size = av_mallocz(*laces * sizeof(int));
  1794. if (!lace_size)
  1795. return AVERROR(ENOMEM);
  1796. switch (type) {
  1797. case 0x1: /* Xiph lacing */ {
  1798. uint8_t temp;
  1799. uint32_t total = 0;
  1800. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1801. while (1) {
  1802. if (size <= total) {
  1803. res = AVERROR_INVALIDDATA;
  1804. break;
  1805. }
  1806. temp = *data;
  1807. total += temp;
  1808. lace_size[n] += temp;
  1809. data += 1;
  1810. size -= 1;
  1811. if (temp != 0xff)
  1812. break;
  1813. }
  1814. }
  1815. if (size <= total) {
  1816. res = AVERROR_INVALIDDATA;
  1817. break;
  1818. }
  1819. lace_size[n] = size - total;
  1820. break;
  1821. }
  1822. case 0x2: /* fixed-size lacing */
  1823. if (size % (*laces)) {
  1824. res = AVERROR_INVALIDDATA;
  1825. break;
  1826. }
  1827. for (n = 0; n < *laces; n++)
  1828. lace_size[n] = size / *laces;
  1829. break;
  1830. case 0x3: /* EBML lacing */ {
  1831. uint64_t num;
  1832. uint64_t total;
  1833. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1834. if (n < 0 || num > INT_MAX) {
  1835. av_log(matroska->ctx, AV_LOG_INFO,
  1836. "EBML block data error\n");
  1837. res = n<0 ? n : AVERROR_INVALIDDATA;
  1838. break;
  1839. }
  1840. data += n;
  1841. size -= n;
  1842. total = lace_size[0] = num;
  1843. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1844. int64_t snum;
  1845. int r;
  1846. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1847. if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
  1848. av_log(matroska->ctx, AV_LOG_INFO,
  1849. "EBML block data error\n");
  1850. res = r<0 ? r : AVERROR_INVALIDDATA;
  1851. break;
  1852. }
  1853. data += r;
  1854. size -= r;
  1855. lace_size[n] = lace_size[n - 1] + snum;
  1856. total += lace_size[n];
  1857. }
  1858. if (size <= total) {
  1859. res = AVERROR_INVALIDDATA;
  1860. break;
  1861. }
  1862. lace_size[*laces - 1] = size - total;
  1863. break;
  1864. }
  1865. }
  1866. *buf = data;
  1867. *lace_buf = lace_size;
  1868. *buf_size = size;
  1869. return res;
  1870. }
  1871. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1872. MatroskaTrack *track,
  1873. AVStream *st,
  1874. uint8_t *data, int size,
  1875. uint64_t timecode,
  1876. int64_t pos)
  1877. {
  1878. int a = st->codec->block_align;
  1879. int sps = track->audio.sub_packet_size;
  1880. int cfs = track->audio.coded_framesize;
  1881. int h = track->audio.sub_packet_h;
  1882. int y = track->audio.sub_packet_cnt;
  1883. int w = track->audio.frame_size;
  1884. int x;
  1885. if (!track->audio.pkt_cnt) {
  1886. if (track->audio.sub_packet_cnt == 0)
  1887. track->audio.buf_timecode = timecode;
  1888. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1889. if (size < cfs * h / 2) {
  1890. av_log(matroska->ctx, AV_LOG_ERROR,
  1891. "Corrupt int4 RM-style audio packet size\n");
  1892. return AVERROR_INVALIDDATA;
  1893. }
  1894. for (x=0; x<h/2; x++)
  1895. memcpy(track->audio.buf+x*2*w+y*cfs,
  1896. data+x*cfs, cfs);
  1897. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1898. if (size < w) {
  1899. av_log(matroska->ctx, AV_LOG_ERROR,
  1900. "Corrupt sipr RM-style audio packet size\n");
  1901. return AVERROR_INVALIDDATA;
  1902. }
  1903. memcpy(track->audio.buf + y*w, data, w);
  1904. } else {
  1905. if (size < sps * w / sps || h<=0) {
  1906. av_log(matroska->ctx, AV_LOG_ERROR,
  1907. "Corrupt generic RM-style audio packet size\n");
  1908. return AVERROR_INVALIDDATA;
  1909. }
  1910. for (x=0; x<w/sps; x++)
  1911. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1912. }
  1913. if (++track->audio.sub_packet_cnt >= h) {
  1914. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1915. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1916. track->audio.sub_packet_cnt = 0;
  1917. track->audio.pkt_cnt = h*w / a;
  1918. }
  1919. }
  1920. while (track->audio.pkt_cnt) {
  1921. AVPacket *pkt = NULL;
  1922. if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
  1923. av_free(pkt);
  1924. return AVERROR(ENOMEM);
  1925. }
  1926. memcpy(pkt->data, track->audio.buf
  1927. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1928. pkt->pts = track->audio.buf_timecode;
  1929. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1930. pkt->pos = pos;
  1931. pkt->stream_index = st->index;
  1932. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1933. }
  1934. return 0;
  1935. }
  1936. /* reconstruct full wavpack blocks from mangled matroska ones */
  1937. static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
  1938. uint8_t **pdst, int *size)
  1939. {
  1940. uint8_t *dst = NULL;
  1941. int dstlen = 0;
  1942. int srclen = *size;
  1943. uint32_t samples;
  1944. uint16_t ver;
  1945. int ret, offset = 0;
  1946. if (srclen < 12 || track->stream->codec->extradata_size < 2)
  1947. return AVERROR_INVALIDDATA;
  1948. ver = AV_RL16(track->stream->codec->extradata);
  1949. samples = AV_RL32(src);
  1950. src += 4;
  1951. srclen -= 4;
  1952. while (srclen >= 8) {
  1953. int multiblock;
  1954. uint32_t blocksize;
  1955. uint8_t *tmp;
  1956. uint32_t flags = AV_RL32(src);
  1957. uint32_t crc = AV_RL32(src + 4);
  1958. src += 8;
  1959. srclen -= 8;
  1960. multiblock = (flags & 0x1800) != 0x1800;
  1961. if (multiblock) {
  1962. if (srclen < 4) {
  1963. ret = AVERROR_INVALIDDATA;
  1964. goto fail;
  1965. }
  1966. blocksize = AV_RL32(src);
  1967. src += 4;
  1968. srclen -= 4;
  1969. } else
  1970. blocksize = srclen;
  1971. if (blocksize > srclen) {
  1972. ret = AVERROR_INVALIDDATA;
  1973. goto fail;
  1974. }
  1975. tmp = av_realloc(dst, dstlen + blocksize + 32);
  1976. if (!tmp) {
  1977. ret = AVERROR(ENOMEM);
  1978. goto fail;
  1979. }
  1980. dst = tmp;
  1981. dstlen += blocksize + 32;
  1982. AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
  1983. AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
  1984. AV_WL16(dst + offset + 8, ver); // version
  1985. AV_WL16(dst + offset + 10, 0); // track/index_no
  1986. AV_WL32(dst + offset + 12, 0); // total samples
  1987. AV_WL32(dst + offset + 16, 0); // block index
  1988. AV_WL32(dst + offset + 20, samples); // number of samples
  1989. AV_WL32(dst + offset + 24, flags); // flags
  1990. AV_WL32(dst + offset + 28, crc); // crc
  1991. memcpy (dst + offset + 32, src, blocksize); // block data
  1992. src += blocksize;
  1993. srclen -= blocksize;
  1994. offset += blocksize + 32;
  1995. }
  1996. *pdst = dst;
  1997. *size = dstlen;
  1998. return 0;
  1999. fail:
  2000. av_freep(&dst);
  2001. return ret;
  2002. }
  2003. static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
  2004. MatroskaTrack *track,
  2005. AVStream *st,
  2006. uint8_t *data, int data_len,
  2007. uint64_t timecode,
  2008. uint64_t duration,
  2009. int64_t pos)
  2010. {
  2011. AVPacket *pkt;
  2012. uint8_t *id, *settings, *text, *buf;
  2013. int id_len, settings_len, text_len;
  2014. uint8_t *p, *q;
  2015. int err;
  2016. if (data_len <= 0)
  2017. return AVERROR_INVALIDDATA;
  2018. p = data;
  2019. q = data + data_len;
  2020. id = p;
  2021. id_len = -1;
  2022. while (p < q) {
  2023. if (*p == '\r' || *p == '\n') {
  2024. id_len = p - id;
  2025. if (*p == '\r')
  2026. p++;
  2027. break;
  2028. }
  2029. p++;
  2030. }
  2031. if (p >= q || *p != '\n')
  2032. return AVERROR_INVALIDDATA;
  2033. p++;
  2034. settings = p;
  2035. settings_len = -1;
  2036. while (p < q) {
  2037. if (*p == '\r' || *p == '\n') {
  2038. settings_len = p - settings;
  2039. if (*p == '\r')
  2040. p++;
  2041. break;
  2042. }
  2043. p++;
  2044. }
  2045. if (p >= q || *p != '\n')
  2046. return AVERROR_INVALIDDATA;
  2047. p++;
  2048. text = p;
  2049. text_len = q - p;
  2050. while (text_len > 0) {
  2051. const int len = text_len - 1;
  2052. const uint8_t c = p[len];
  2053. if (c != '\r' && c != '\n')
  2054. break;
  2055. text_len = len;
  2056. }
  2057. if (text_len <= 0)
  2058. return AVERROR_INVALIDDATA;
  2059. pkt = av_mallocz(sizeof(*pkt));
  2060. err = av_new_packet(pkt, text_len);
  2061. if (err < 0) {
  2062. av_free(pkt);
  2063. return AVERROR(err);
  2064. }
  2065. memcpy(pkt->data, text, text_len);
  2066. if (id_len > 0) {
  2067. buf = av_packet_new_side_data(pkt,
  2068. AV_PKT_DATA_WEBVTT_IDENTIFIER,
  2069. id_len);
  2070. if (buf == NULL) {
  2071. av_free(pkt);
  2072. return AVERROR(ENOMEM);
  2073. }
  2074. memcpy(buf, id, id_len);
  2075. }
  2076. if (settings_len > 0) {
  2077. buf = av_packet_new_side_data(pkt,
  2078. AV_PKT_DATA_WEBVTT_SETTINGS,
  2079. settings_len);
  2080. if (buf == NULL) {
  2081. av_free(pkt);
  2082. return AVERROR(ENOMEM);
  2083. }
  2084. memcpy(buf, settings, settings_len);
  2085. }
  2086. // Do we need this for subtitles?
  2087. // pkt->flags = AV_PKT_FLAG_KEY;
  2088. pkt->stream_index = st->index;
  2089. pkt->pts = timecode;
  2090. // Do we need this for subtitles?
  2091. // pkt->dts = timecode;
  2092. pkt->duration = duration;
  2093. pkt->pos = pos;
  2094. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  2095. matroska->prev_pkt = pkt;
  2096. return 0;
  2097. }
  2098. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  2099. MatroskaTrack *track,
  2100. AVStream *st,
  2101. uint8_t *data, int pkt_size,
  2102. uint64_t timecode, uint64_t lace_duration,
  2103. int64_t pos, int is_keyframe,
  2104. uint8_t *additional, uint64_t additional_id, int additional_size)
  2105. {
  2106. MatroskaTrackEncoding *encodings = track->encodings.elem;
  2107. uint8_t *pkt_data = data;
  2108. int offset = 0, res;
  2109. AVPacket *pkt;
  2110. if (encodings && !encodings->type && encodings->scope & 1) {
  2111. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  2112. if (res < 0)
  2113. return res;
  2114. }
  2115. if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
  2116. uint8_t *wv_data;
  2117. res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
  2118. if (res < 0) {
  2119. av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
  2120. goto fail;
  2121. }
  2122. if (pkt_data != data)
  2123. av_freep(&pkt_data);
  2124. pkt_data = wv_data;
  2125. }
  2126. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  2127. offset = 8;
  2128. pkt = av_mallocz(sizeof(AVPacket));
  2129. /* XXX: prevent data copy... */
  2130. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  2131. av_free(pkt);
  2132. res = AVERROR(ENOMEM);
  2133. goto fail;
  2134. }
  2135. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  2136. uint8_t *buf = pkt->data;
  2137. bytestream_put_be32(&buf, pkt_size);
  2138. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  2139. }
  2140. memcpy(pkt->data + offset, pkt_data, pkt_size);
  2141. if (pkt_data != data)
  2142. av_freep(&pkt_data);
  2143. pkt->flags = is_keyframe;
  2144. pkt->stream_index = st->index;
  2145. if (additional_size > 0) {
  2146. uint8_t *side_data = av_packet_new_side_data(pkt,
  2147. AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
  2148. additional_size + 8);
  2149. if(side_data == NULL) {
  2150. av_free_packet(pkt);
  2151. av_free(pkt);
  2152. return AVERROR(ENOMEM);
  2153. }
  2154. AV_WB64(side_data, additional_id);
  2155. memcpy(side_data + 8, additional, additional_size);
  2156. }
  2157. if (track->ms_compat)
  2158. pkt->dts = timecode;
  2159. else
  2160. pkt->pts = timecode;
  2161. pkt->pos = pos;
  2162. if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
  2163. /*
  2164. * For backward compatibility.
  2165. * Historically, we have put subtitle duration
  2166. * in convergence_duration, on the off chance
  2167. * that the time_scale is less than 1us, which
  2168. * could result in a 32bit overflow on the
  2169. * normal duration field.
  2170. */
  2171. pkt->convergence_duration = lace_duration;
  2172. }
  2173. if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
  2174. lace_duration <= INT_MAX) {
  2175. /*
  2176. * For non subtitle tracks, just store the duration
  2177. * as normal.
  2178. *
  2179. * If it's a subtitle track and duration value does
  2180. * not overflow a uint32, then also store it normally.
  2181. */
  2182. pkt->duration = lace_duration;
  2183. }
  2184. #if FF_API_ASS_SSA
  2185. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  2186. matroska_fix_ass_packet(matroska, pkt, lace_duration);
  2187. if (matroska->prev_pkt &&
  2188. timecode != AV_NOPTS_VALUE &&
  2189. matroska->prev_pkt->pts == timecode &&
  2190. matroska->prev_pkt->stream_index == st->index &&
  2191. st->codec->codec_id == AV_CODEC_ID_SSA)
  2192. matroska_merge_packets(matroska->prev_pkt, pkt);
  2193. else {
  2194. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  2195. matroska->prev_pkt = pkt;
  2196. }
  2197. #else
  2198. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  2199. matroska->prev_pkt = pkt;
  2200. #endif
  2201. return 0;
  2202. fail:
  2203. if (pkt_data != data)
  2204. av_freep(&pkt_data);
  2205. return res;
  2206. }
  2207. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  2208. int size, int64_t pos, uint64_t cluster_time,
  2209. uint64_t block_duration, int is_keyframe,
  2210. uint8_t *additional, uint64_t additional_id, int additional_size,
  2211. int64_t cluster_pos)
  2212. {
  2213. uint64_t timecode = AV_NOPTS_VALUE;
  2214. MatroskaTrack *track;
  2215. int res = 0;
  2216. AVStream *st;
  2217. int16_t block_time;
  2218. uint32_t *lace_size = NULL;
  2219. int n, flags, laces = 0;
  2220. uint64_t num;
  2221. int trust_default_duration = 1;
  2222. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  2223. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  2224. return n;
  2225. }
  2226. data += n;
  2227. size -= n;
  2228. track = matroska_find_track_by_num(matroska, num);
  2229. if (!track || !track->stream) {
  2230. av_log(matroska->ctx, AV_LOG_INFO,
  2231. "Invalid stream %"PRIu64" or size %u\n", num, size);
  2232. return AVERROR_INVALIDDATA;
  2233. } else if (size <= 3)
  2234. return 0;
  2235. st = track->stream;
  2236. if (st->discard >= AVDISCARD_ALL)
  2237. return res;
  2238. av_assert1(block_duration != AV_NOPTS_VALUE);
  2239. block_time = sign_extend(AV_RB16(data), 16);
  2240. data += 2;
  2241. flags = *data++;
  2242. size -= 3;
  2243. if (is_keyframe == -1)
  2244. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  2245. if (cluster_time != (uint64_t)-1
  2246. && (block_time >= 0 || cluster_time >= -block_time)) {
  2247. timecode = cluster_time + block_time;
  2248. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  2249. && timecode < track->end_timecode)
  2250. is_keyframe = 0; /* overlapping subtitles are not key frame */
  2251. if (is_keyframe)
  2252. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  2253. }
  2254. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  2255. if (timecode < matroska->skip_to_timecode)
  2256. return res;
  2257. if (!st->skip_to_keyframe) {
  2258. av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
  2259. matroska->skip_to_keyframe = 0;
  2260. }
  2261. if (is_keyframe)
  2262. matroska->skip_to_keyframe = 0;
  2263. }
  2264. res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
  2265. &lace_size, &laces);
  2266. if (res)
  2267. goto end;
  2268. if (track->audio.samplerate == 8000) {
  2269. // If this is needed for more codecs, then add them here
  2270. if (st->codec->codec_id == AV_CODEC_ID_AC3) {
  2271. if(track->audio.samplerate != st->codec->sample_rate || !st->codec->frame_size)
  2272. trust_default_duration = 0;
  2273. }
  2274. }
  2275. if (!block_duration && trust_default_duration)
  2276. block_duration = track->default_duration * laces / matroska->time_scale;
  2277. if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
  2278. track->end_timecode =
  2279. FFMAX(track->end_timecode, timecode + block_duration);
  2280. for (n = 0; n < laces; n++) {
  2281. int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
  2282. if (lace_size[n] > size) {
  2283. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  2284. break;
  2285. }
  2286. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  2287. st->codec->codec_id == AV_CODEC_ID_COOK ||
  2288. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  2289. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  2290. st->codec->block_align && track->audio.sub_packet_size) {
  2291. res = matroska_parse_rm_audio(matroska, track, st, data,
  2292. lace_size[n],
  2293. timecode, pos);
  2294. if (res)
  2295. goto end;
  2296. } else if (st->codec->codec_id == AV_CODEC_ID_WEBVTT) {
  2297. res = matroska_parse_webvtt(matroska, track, st,
  2298. data, lace_size[n],
  2299. timecode, lace_duration,
  2300. pos);
  2301. if (res)
  2302. goto end;
  2303. } else {
  2304. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  2305. timecode, lace_duration,
  2306. pos, !n? is_keyframe : 0,
  2307. additional, additional_id, additional_size);
  2308. if (res)
  2309. goto end;
  2310. }
  2311. if (timecode != AV_NOPTS_VALUE)
  2312. timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
  2313. data += lace_size[n];
  2314. size -= lace_size[n];
  2315. }
  2316. end:
  2317. av_free(lace_size);
  2318. return res;
  2319. }
  2320. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  2321. {
  2322. EbmlList *blocks_list;
  2323. MatroskaBlock *blocks;
  2324. int i, res;
  2325. res = ebml_parse(matroska,
  2326. matroska_cluster_incremental_parsing,
  2327. &matroska->current_cluster);
  2328. if (res == 1) {
  2329. /* New Cluster */
  2330. if (matroska->current_cluster_pos)
  2331. ebml_level_end(matroska);
  2332. ebml_free(matroska_cluster, &matroska->current_cluster);
  2333. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2334. matroska->current_cluster_num_blocks = 0;
  2335. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2336. matroska->prev_pkt = NULL;
  2337. /* sizeof the ID which was already read */
  2338. if (matroska->current_id)
  2339. matroska->current_cluster_pos -= 4;
  2340. res = ebml_parse(matroska,
  2341. matroska_clusters_incremental,
  2342. &matroska->current_cluster);
  2343. /* Try parsing the block again. */
  2344. if (res == 1)
  2345. res = ebml_parse(matroska,
  2346. matroska_cluster_incremental_parsing,
  2347. &matroska->current_cluster);
  2348. }
  2349. if (!res &&
  2350. matroska->current_cluster_num_blocks <
  2351. matroska->current_cluster.blocks.nb_elem) {
  2352. blocks_list = &matroska->current_cluster.blocks;
  2353. blocks = blocks_list->elem;
  2354. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2355. i = blocks_list->nb_elem - 1;
  2356. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2357. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2358. uint8_t* additional = blocks[i].additional.size > 0 ?
  2359. blocks[i].additional.data : NULL;
  2360. if (!blocks[i].non_simple)
  2361. blocks[i].duration = 0;
  2362. res = matroska_parse_block(matroska,
  2363. blocks[i].bin.data, blocks[i].bin.size,
  2364. blocks[i].bin.pos,
  2365. matroska->current_cluster.timecode,
  2366. blocks[i].duration, is_keyframe,
  2367. additional, blocks[i].additional_id,
  2368. blocks[i].additional.size,
  2369. matroska->current_cluster_pos);
  2370. }
  2371. }
  2372. return res;
  2373. }
  2374. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2375. {
  2376. MatroskaCluster cluster = { 0 };
  2377. EbmlList *blocks_list;
  2378. MatroskaBlock *blocks;
  2379. int i, res;
  2380. int64_t pos;
  2381. if (!matroska->contains_ssa)
  2382. return matroska_parse_cluster_incremental(matroska);
  2383. pos = avio_tell(matroska->ctx->pb);
  2384. matroska->prev_pkt = NULL;
  2385. if (matroska->current_id)
  2386. pos -= 4; /* sizeof the ID which was already read */
  2387. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2388. blocks_list = &cluster.blocks;
  2389. blocks = blocks_list->elem;
  2390. for (i=0; i<blocks_list->nb_elem; i++)
  2391. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2392. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2393. res=matroska_parse_block(matroska,
  2394. blocks[i].bin.data, blocks[i].bin.size,
  2395. blocks[i].bin.pos, cluster.timecode,
  2396. blocks[i].duration, is_keyframe, NULL, 0, 0,
  2397. pos);
  2398. }
  2399. ebml_free(matroska_cluster, &cluster);
  2400. return res;
  2401. }
  2402. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2403. {
  2404. MatroskaDemuxContext *matroska = s->priv_data;
  2405. while (matroska_deliver_packet(matroska, pkt)) {
  2406. int64_t pos = avio_tell(matroska->ctx->pb);
  2407. if (matroska->done)
  2408. return AVERROR_EOF;
  2409. if (matroska_parse_cluster(matroska) < 0)
  2410. matroska_resync(matroska, pos);
  2411. }
  2412. return 0;
  2413. }
  2414. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2415. int64_t timestamp, int flags)
  2416. {
  2417. MatroskaDemuxContext *matroska = s->priv_data;
  2418. MatroskaTrack *tracks = matroska->tracks.elem;
  2419. AVStream *st = s->streams[stream_index];
  2420. int i, index, index_sub, index_min;
  2421. /* Parse the CUES now since we need the index data to seek. */
  2422. if (matroska->cues_parsing_deferred > 0) {
  2423. matroska->cues_parsing_deferred = 0;
  2424. matroska_parse_cues(matroska);
  2425. }
  2426. if (!st->nb_index_entries)
  2427. goto err;
  2428. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2429. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2430. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  2431. matroska->current_id = 0;
  2432. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2433. matroska_clear_queue(matroska);
  2434. if (matroska_parse_cluster(matroska) < 0)
  2435. break;
  2436. }
  2437. }
  2438. matroska_clear_queue(matroska);
  2439. if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
  2440. goto err;
  2441. index_min = index;
  2442. for (i=0; i < matroska->tracks.nb_elem; i++) {
  2443. tracks[i].audio.pkt_cnt = 0;
  2444. tracks[i].audio.sub_packet_cnt = 0;
  2445. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2446. tracks[i].end_timecode = 0;
  2447. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  2448. && tracks[i].stream->discard != AVDISCARD_ALL) {
  2449. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  2450. while(index_sub >= 0
  2451. && index_min >= 0
  2452. && tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos
  2453. && st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  2454. index_min--;
  2455. }
  2456. }
  2457. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2458. matroska->current_id = 0;
  2459. if (flags & AVSEEK_FLAG_ANY) {
  2460. st->skip_to_keyframe = 0;
  2461. matroska->skip_to_timecode = timestamp;
  2462. } else {
  2463. st->skip_to_keyframe = 1;
  2464. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2465. }
  2466. matroska->skip_to_keyframe = 1;
  2467. matroska->done = 0;
  2468. matroska->num_levels = 0;
  2469. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2470. return 0;
  2471. err:
  2472. // slightly hackish but allows proper fallback to
  2473. // the generic seeking code.
  2474. matroska_clear_queue(matroska);
  2475. matroska->current_id = 0;
  2476. st->skip_to_keyframe =
  2477. matroska->skip_to_keyframe = 0;
  2478. matroska->done = 0;
  2479. matroska->num_levels = 0;
  2480. return -1;
  2481. }
  2482. static int matroska_read_close(AVFormatContext *s)
  2483. {
  2484. MatroskaDemuxContext *matroska = s->priv_data;
  2485. MatroskaTrack *tracks = matroska->tracks.elem;
  2486. int n;
  2487. matroska_clear_queue(matroska);
  2488. for (n=0; n < matroska->tracks.nb_elem; n++)
  2489. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2490. av_free(tracks[n].audio.buf);
  2491. ebml_free(matroska_cluster, &matroska->current_cluster);
  2492. ebml_free(matroska_segment, matroska);
  2493. return 0;
  2494. }
  2495. AVInputFormat ff_matroska_demuxer = {
  2496. .name = "matroska,webm",
  2497. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2498. .priv_data_size = sizeof(MatroskaDemuxContext),
  2499. .read_probe = matroska_probe,
  2500. .read_header = matroska_read_header,
  2501. .read_packet = matroska_read_packet,
  2502. .read_close = matroska_read_close,
  2503. .read_seek = matroska_read_seek,
  2504. };