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.

2837 lines
99KB

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