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.

2847 lines
99KB

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