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.

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