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.

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