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.

2908 lines
102KB

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