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.

2890 lines
101KB

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