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.

2852 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. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1629. FF_INPUT_BUFFER_PADDING_SIZE);
  1630. if(st->codec->extradata == NULL)
  1631. return AVERROR(ENOMEM);
  1632. st->codec->extradata_size = track->codec_priv.size;
  1633. memcpy(st->codec->extradata,
  1634. track->codec_priv.data + extradata_offset,
  1635. track->codec_priv.size);
  1636. }
  1637. }
  1638. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1639. MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
  1640. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1641. st->codec->codec_tag = fourcc;
  1642. st->codec->width = track->video.pixel_width;
  1643. st->codec->height = track->video.pixel_height;
  1644. av_reduce(&st->sample_aspect_ratio.num,
  1645. &st->sample_aspect_ratio.den,
  1646. st->codec->height * track->video.display_width,
  1647. st->codec-> width * track->video.display_height,
  1648. 255);
  1649. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1650. if (track->default_duration) {
  1651. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1652. 1000000000, track->default_duration, 30000);
  1653. #if FF_API_R_FRAME_RATE
  1654. if (st->avg_frame_rate.num < st->avg_frame_rate.den * 1000L)
  1655. st->r_frame_rate = st->avg_frame_rate;
  1656. #endif
  1657. }
  1658. /* export stereo mode flag as metadata tag */
  1659. if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
  1660. av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
  1661. /* export alpha mode flag as metadata tag */
  1662. if (track->video.alpha_mode)
  1663. av_dict_set(&st->metadata, "alpha_mode", "1", 0);
  1664. /* if we have virtual track, mark the real tracks */
  1665. for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
  1666. char buf[32];
  1667. if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
  1668. continue;
  1669. snprintf(buf, sizeof(buf), "%s_%d",
  1670. ff_matroska_video_stereo_plane[planes[j].type], i);
  1671. for (k=0; k < matroska->tracks.nb_elem; k++)
  1672. if (planes[j].uid == tracks[k].uid) {
  1673. av_dict_set(&s->streams[k]->metadata,
  1674. "stereo_mode", buf, 0);
  1675. break;
  1676. }
  1677. }
  1678. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1679. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1680. st->codec->sample_rate = track->audio.out_samplerate;
  1681. st->codec->channels = track->audio.channels;
  1682. st->codec->bits_per_coded_sample = track->audio.bitdepth;
  1683. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1684. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1685. } else if (codec_id == AV_CODEC_ID_WEBVTT) {
  1686. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1687. if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
  1688. st->disposition |= AV_DISPOSITION_CAPTIONS;
  1689. } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
  1690. st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
  1691. } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
  1692. st->disposition |= AV_DISPOSITION_METADATA;
  1693. }
  1694. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1695. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1696. #if FF_API_ASS_SSA
  1697. if (st->codec->codec_id == AV_CODEC_ID_SSA ||
  1698. st->codec->codec_id == AV_CODEC_ID_ASS)
  1699. #else
  1700. if (st->codec->codec_id == AV_CODEC_ID_ASS)
  1701. #endif
  1702. matroska->contains_ssa = 1;
  1703. }
  1704. }
  1705. attachements = attachements_list->elem;
  1706. for (j=0; j<attachements_list->nb_elem; j++) {
  1707. if (!(attachements[j].filename && attachements[j].mime &&
  1708. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1709. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1710. } else {
  1711. AVStream *st = avformat_new_stream(s, NULL);
  1712. if (st == NULL)
  1713. break;
  1714. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1715. av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
  1716. st->codec->codec_id = AV_CODEC_ID_NONE;
  1717. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1718. st->codec->extradata = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);
  1719. if(st->codec->extradata == NULL)
  1720. break;
  1721. st->codec->extradata_size = attachements[j].bin.size;
  1722. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1723. for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1724. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1725. strlen(ff_mkv_mime_tags[i].str))) {
  1726. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1727. break;
  1728. }
  1729. }
  1730. attachements[j].stream = st;
  1731. }
  1732. }
  1733. chapters = chapters_list->elem;
  1734. for (i=0; i<chapters_list->nb_elem; i++)
  1735. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1736. && (max_start==0 || chapters[i].start > max_start)) {
  1737. chapters[i].chapter =
  1738. avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1739. chapters[i].start, chapters[i].end,
  1740. chapters[i].title);
  1741. av_dict_set(&chapters[i].chapter->metadata,
  1742. "title", chapters[i].title, 0);
  1743. max_start = chapters[i].start;
  1744. }
  1745. matroska_add_index_entries(matroska);
  1746. matroska_convert_tags(s);
  1747. return 0;
  1748. }
  1749. /*
  1750. * Put one packet in an application-supplied AVPacket struct.
  1751. * Returns 0 on success or -1 on failure.
  1752. */
  1753. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1754. AVPacket *pkt)
  1755. {
  1756. if (matroska->num_packets > 0) {
  1757. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1758. av_free(matroska->packets[0]);
  1759. if (matroska->num_packets > 1) {
  1760. void *newpackets;
  1761. memmove(&matroska->packets[0], &matroska->packets[1],
  1762. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1763. newpackets = av_realloc(matroska->packets,
  1764. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1765. if (newpackets)
  1766. matroska->packets = newpackets;
  1767. } else {
  1768. av_freep(&matroska->packets);
  1769. matroska->prev_pkt = NULL;
  1770. }
  1771. matroska->num_packets--;
  1772. return 0;
  1773. }
  1774. return -1;
  1775. }
  1776. /*
  1777. * Free all packets in our internal queue.
  1778. */
  1779. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1780. {
  1781. matroska->prev_pkt = NULL;
  1782. if (matroska->packets) {
  1783. int n;
  1784. for (n = 0; n < matroska->num_packets; n++) {
  1785. av_free_packet(matroska->packets[n]);
  1786. av_free(matroska->packets[n]);
  1787. }
  1788. av_freep(&matroska->packets);
  1789. matroska->num_packets = 0;
  1790. }
  1791. }
  1792. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1793. int* buf_size, int type,
  1794. uint32_t **lace_buf, int *laces)
  1795. {
  1796. int res = 0, n, size = *buf_size;
  1797. uint8_t *data = *buf;
  1798. uint32_t *lace_size;
  1799. if (!type) {
  1800. *laces = 1;
  1801. *lace_buf = av_mallocz(sizeof(int));
  1802. if (!*lace_buf)
  1803. return AVERROR(ENOMEM);
  1804. *lace_buf[0] = size;
  1805. return 0;
  1806. }
  1807. av_assert0(size > 0);
  1808. *laces = *data + 1;
  1809. data += 1;
  1810. size -= 1;
  1811. lace_size = av_mallocz(*laces * sizeof(int));
  1812. if (!lace_size)
  1813. return AVERROR(ENOMEM);
  1814. switch (type) {
  1815. case 0x1: /* Xiph lacing */ {
  1816. uint8_t temp;
  1817. uint32_t total = 0;
  1818. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1819. while (1) {
  1820. if (size <= total) {
  1821. res = AVERROR_INVALIDDATA;
  1822. break;
  1823. }
  1824. temp = *data;
  1825. total += temp;
  1826. lace_size[n] += temp;
  1827. data += 1;
  1828. size -= 1;
  1829. if (temp != 0xff)
  1830. break;
  1831. }
  1832. }
  1833. if (size <= total) {
  1834. res = AVERROR_INVALIDDATA;
  1835. break;
  1836. }
  1837. lace_size[n] = size - total;
  1838. break;
  1839. }
  1840. case 0x2: /* fixed-size lacing */
  1841. if (size % (*laces)) {
  1842. res = AVERROR_INVALIDDATA;
  1843. break;
  1844. }
  1845. for (n = 0; n < *laces; n++)
  1846. lace_size[n] = size / *laces;
  1847. break;
  1848. case 0x3: /* EBML lacing */ {
  1849. uint64_t num;
  1850. uint64_t total;
  1851. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1852. if (n < 0 || num > INT_MAX) {
  1853. av_log(matroska->ctx, AV_LOG_INFO,
  1854. "EBML block data error\n");
  1855. res = n<0 ? n : AVERROR_INVALIDDATA;
  1856. break;
  1857. }
  1858. data += n;
  1859. size -= n;
  1860. total = lace_size[0] = num;
  1861. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1862. int64_t snum;
  1863. int r;
  1864. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1865. if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
  1866. av_log(matroska->ctx, AV_LOG_INFO,
  1867. "EBML block data error\n");
  1868. res = r<0 ? r : AVERROR_INVALIDDATA;
  1869. break;
  1870. }
  1871. data += r;
  1872. size -= r;
  1873. lace_size[n] = lace_size[n - 1] + snum;
  1874. total += lace_size[n];
  1875. }
  1876. if (size <= total) {
  1877. res = AVERROR_INVALIDDATA;
  1878. break;
  1879. }
  1880. lace_size[*laces - 1] = size - total;
  1881. break;
  1882. }
  1883. }
  1884. *buf = data;
  1885. *lace_buf = lace_size;
  1886. *buf_size = size;
  1887. return res;
  1888. }
  1889. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1890. MatroskaTrack *track,
  1891. AVStream *st,
  1892. uint8_t *data, int size,
  1893. uint64_t timecode,
  1894. int64_t pos)
  1895. {
  1896. int a = st->codec->block_align;
  1897. int sps = track->audio.sub_packet_size;
  1898. int cfs = track->audio.coded_framesize;
  1899. int h = track->audio.sub_packet_h;
  1900. int y = track->audio.sub_packet_cnt;
  1901. int w = track->audio.frame_size;
  1902. int x;
  1903. if (!track->audio.pkt_cnt) {
  1904. if (track->audio.sub_packet_cnt == 0)
  1905. track->audio.buf_timecode = timecode;
  1906. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1907. if (size < cfs * h / 2) {
  1908. av_log(matroska->ctx, AV_LOG_ERROR,
  1909. "Corrupt int4 RM-style audio packet size\n");
  1910. return AVERROR_INVALIDDATA;
  1911. }
  1912. for (x=0; x<h/2; x++)
  1913. memcpy(track->audio.buf+x*2*w+y*cfs,
  1914. data+x*cfs, cfs);
  1915. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1916. if (size < w) {
  1917. av_log(matroska->ctx, AV_LOG_ERROR,
  1918. "Corrupt sipr RM-style audio packet size\n");
  1919. return AVERROR_INVALIDDATA;
  1920. }
  1921. memcpy(track->audio.buf + y*w, data, w);
  1922. } else {
  1923. if (size < sps * w / sps || h<=0) {
  1924. av_log(matroska->ctx, AV_LOG_ERROR,
  1925. "Corrupt generic RM-style audio packet size\n");
  1926. return AVERROR_INVALIDDATA;
  1927. }
  1928. for (x=0; x<w/sps; x++)
  1929. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1930. }
  1931. if (++track->audio.sub_packet_cnt >= h) {
  1932. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1933. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1934. track->audio.sub_packet_cnt = 0;
  1935. track->audio.pkt_cnt = h*w / a;
  1936. }
  1937. }
  1938. while (track->audio.pkt_cnt) {
  1939. AVPacket *pkt = NULL;
  1940. if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
  1941. av_free(pkt);
  1942. return AVERROR(ENOMEM);
  1943. }
  1944. memcpy(pkt->data, track->audio.buf
  1945. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1946. pkt->pts = track->audio.buf_timecode;
  1947. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1948. pkt->pos = pos;
  1949. pkt->stream_index = st->index;
  1950. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1951. }
  1952. return 0;
  1953. }
  1954. /* reconstruct full wavpack blocks from mangled matroska ones */
  1955. static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
  1956. uint8_t **pdst, int *size)
  1957. {
  1958. uint8_t *dst = NULL;
  1959. int dstlen = 0;
  1960. int srclen = *size;
  1961. uint32_t samples;
  1962. uint16_t ver;
  1963. int ret, offset = 0;
  1964. if (srclen < 12 || track->stream->codec->extradata_size < 2)
  1965. return AVERROR_INVALIDDATA;
  1966. ver = AV_RL16(track->stream->codec->extradata);
  1967. samples = AV_RL32(src);
  1968. src += 4;
  1969. srclen -= 4;
  1970. while (srclen >= 8) {
  1971. int multiblock;
  1972. uint32_t blocksize;
  1973. uint8_t *tmp;
  1974. uint32_t flags = AV_RL32(src);
  1975. uint32_t crc = AV_RL32(src + 4);
  1976. src += 8;
  1977. srclen -= 8;
  1978. multiblock = (flags & 0x1800) != 0x1800;
  1979. if (multiblock) {
  1980. if (srclen < 4) {
  1981. ret = AVERROR_INVALIDDATA;
  1982. goto fail;
  1983. }
  1984. blocksize = AV_RL32(src);
  1985. src += 4;
  1986. srclen -= 4;
  1987. } else
  1988. blocksize = srclen;
  1989. if (blocksize > srclen) {
  1990. ret = AVERROR_INVALIDDATA;
  1991. goto fail;
  1992. }
  1993. tmp = av_realloc(dst, dstlen + blocksize + 32);
  1994. if (!tmp) {
  1995. ret = AVERROR(ENOMEM);
  1996. goto fail;
  1997. }
  1998. dst = tmp;
  1999. dstlen += blocksize + 32;
  2000. AV_WL32(dst + offset, MKTAG('w', 'v', 'p', 'k')); // tag
  2001. AV_WL32(dst + offset + 4, blocksize + 24); // blocksize - 8
  2002. AV_WL16(dst + offset + 8, ver); // version
  2003. AV_WL16(dst + offset + 10, 0); // track/index_no
  2004. AV_WL32(dst + offset + 12, 0); // total samples
  2005. AV_WL32(dst + offset + 16, 0); // block index
  2006. AV_WL32(dst + offset + 20, samples); // number of samples
  2007. AV_WL32(dst + offset + 24, flags); // flags
  2008. AV_WL32(dst + offset + 28, crc); // crc
  2009. memcpy (dst + offset + 32, src, blocksize); // block data
  2010. src += blocksize;
  2011. srclen -= blocksize;
  2012. offset += blocksize + 32;
  2013. }
  2014. *pdst = dst;
  2015. *size = dstlen;
  2016. return 0;
  2017. fail:
  2018. av_freep(&dst);
  2019. return ret;
  2020. }
  2021. static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
  2022. MatroskaTrack *track,
  2023. AVStream *st,
  2024. uint8_t *data, int data_len,
  2025. uint64_t timecode,
  2026. uint64_t duration,
  2027. int64_t pos)
  2028. {
  2029. AVPacket *pkt;
  2030. uint8_t *id, *settings, *text, *buf;
  2031. int id_len, settings_len, text_len;
  2032. uint8_t *p, *q;
  2033. int err;
  2034. if (data_len <= 0)
  2035. return AVERROR_INVALIDDATA;
  2036. p = data;
  2037. q = data + data_len;
  2038. id = p;
  2039. id_len = -1;
  2040. while (p < q) {
  2041. if (*p == '\r' || *p == '\n') {
  2042. id_len = p - id;
  2043. if (*p == '\r')
  2044. p++;
  2045. break;
  2046. }
  2047. p++;
  2048. }
  2049. if (p >= q || *p != '\n')
  2050. return AVERROR_INVALIDDATA;
  2051. p++;
  2052. settings = p;
  2053. settings_len = -1;
  2054. while (p < q) {
  2055. if (*p == '\r' || *p == '\n') {
  2056. settings_len = p - settings;
  2057. if (*p == '\r')
  2058. p++;
  2059. break;
  2060. }
  2061. p++;
  2062. }
  2063. if (p >= q || *p != '\n')
  2064. return AVERROR_INVALIDDATA;
  2065. p++;
  2066. text = p;
  2067. text_len = q - p;
  2068. while (text_len > 0) {
  2069. const int len = text_len - 1;
  2070. const uint8_t c = p[len];
  2071. if (c != '\r' && c != '\n')
  2072. break;
  2073. text_len = len;
  2074. }
  2075. if (text_len <= 0)
  2076. return AVERROR_INVALIDDATA;
  2077. pkt = av_mallocz(sizeof(*pkt));
  2078. err = av_new_packet(pkt, text_len);
  2079. if (err < 0) {
  2080. av_free(pkt);
  2081. return AVERROR(err);
  2082. }
  2083. memcpy(pkt->data, text, text_len);
  2084. if (id_len > 0) {
  2085. buf = av_packet_new_side_data(pkt,
  2086. AV_PKT_DATA_WEBVTT_IDENTIFIER,
  2087. id_len);
  2088. if (buf == NULL) {
  2089. av_free(pkt);
  2090. return AVERROR(ENOMEM);
  2091. }
  2092. memcpy(buf, id, id_len);
  2093. }
  2094. if (settings_len > 0) {
  2095. buf = av_packet_new_side_data(pkt,
  2096. AV_PKT_DATA_WEBVTT_SETTINGS,
  2097. settings_len);
  2098. if (buf == NULL) {
  2099. av_free(pkt);
  2100. return AVERROR(ENOMEM);
  2101. }
  2102. memcpy(buf, settings, settings_len);
  2103. }
  2104. // Do we need this for subtitles?
  2105. // pkt->flags = AV_PKT_FLAG_KEY;
  2106. pkt->stream_index = st->index;
  2107. pkt->pts = timecode;
  2108. // Do we need this for subtitles?
  2109. // pkt->dts = timecode;
  2110. pkt->duration = duration;
  2111. pkt->pos = pos;
  2112. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  2113. matroska->prev_pkt = pkt;
  2114. return 0;
  2115. }
  2116. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  2117. MatroskaTrack *track,
  2118. AVStream *st,
  2119. uint8_t *data, int pkt_size,
  2120. uint64_t timecode, uint64_t lace_duration,
  2121. int64_t pos, int is_keyframe,
  2122. uint8_t *additional, uint64_t additional_id, int additional_size,
  2123. uint64_t discard_padding)
  2124. {
  2125. MatroskaTrackEncoding *encodings = track->encodings.elem;
  2126. uint8_t *pkt_data = data;
  2127. int offset = 0, res;
  2128. AVPacket *pkt;
  2129. if (encodings && !encodings->type && encodings->scope & 1) {
  2130. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  2131. if (res < 0)
  2132. return res;
  2133. }
  2134. if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
  2135. uint8_t *wv_data;
  2136. res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
  2137. if (res < 0) {
  2138. av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
  2139. goto fail;
  2140. }
  2141. if (pkt_data != data)
  2142. av_freep(&pkt_data);
  2143. pkt_data = wv_data;
  2144. }
  2145. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  2146. offset = 8;
  2147. pkt = av_mallocz(sizeof(AVPacket));
  2148. /* XXX: prevent data copy... */
  2149. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  2150. av_free(pkt);
  2151. res = AVERROR(ENOMEM);
  2152. goto fail;
  2153. }
  2154. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  2155. uint8_t *buf = pkt->data;
  2156. bytestream_put_be32(&buf, pkt_size);
  2157. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  2158. }
  2159. memcpy(pkt->data + offset, pkt_data, pkt_size);
  2160. if (pkt_data != data)
  2161. av_freep(&pkt_data);
  2162. pkt->flags = is_keyframe;
  2163. pkt->stream_index = st->index;
  2164. if (additional_size > 0) {
  2165. uint8_t *side_data = av_packet_new_side_data(pkt,
  2166. AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
  2167. additional_size + 8);
  2168. if(side_data == NULL) {
  2169. av_free_packet(pkt);
  2170. av_free(pkt);
  2171. return AVERROR(ENOMEM);
  2172. }
  2173. AV_WB64(side_data, additional_id);
  2174. memcpy(side_data + 8, additional, additional_size);
  2175. }
  2176. if (discard_padding) {
  2177. uint8_t *side_data = av_packet_new_side_data(pkt,
  2178. AV_PKT_DATA_SKIP_SAMPLES,
  2179. 10);
  2180. if(side_data == NULL) {
  2181. av_free_packet(pkt);
  2182. av_free(pkt);
  2183. return AVERROR(ENOMEM);
  2184. }
  2185. AV_WL32(side_data, 0);
  2186. AV_WL32(side_data + 4, av_rescale_q(discard_padding,
  2187. (AVRational){1, 1000000000},
  2188. (AVRational){1, st->codec->sample_rate}));
  2189. }
  2190. if (track->ms_compat)
  2191. pkt->dts = timecode;
  2192. else
  2193. pkt->pts = timecode;
  2194. pkt->pos = pos;
  2195. if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
  2196. /*
  2197. * For backward compatibility.
  2198. * Historically, we have put subtitle duration
  2199. * in convergence_duration, on the off chance
  2200. * that the time_scale is less than 1us, which
  2201. * could result in a 32bit overflow on the
  2202. * normal duration field.
  2203. */
  2204. pkt->convergence_duration = lace_duration;
  2205. }
  2206. if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
  2207. lace_duration <= INT_MAX) {
  2208. /*
  2209. * For non subtitle tracks, just store the duration
  2210. * as normal.
  2211. *
  2212. * If it's a subtitle track and duration value does
  2213. * not overflow a uint32, then also store it normally.
  2214. */
  2215. pkt->duration = lace_duration;
  2216. }
  2217. #if FF_API_ASS_SSA
  2218. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  2219. matroska_fix_ass_packet(matroska, pkt, lace_duration);
  2220. if (matroska->prev_pkt &&
  2221. timecode != AV_NOPTS_VALUE &&
  2222. matroska->prev_pkt->pts == timecode &&
  2223. matroska->prev_pkt->stream_index == st->index &&
  2224. st->codec->codec_id == AV_CODEC_ID_SSA)
  2225. matroska_merge_packets(matroska->prev_pkt, pkt);
  2226. else {
  2227. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  2228. matroska->prev_pkt = pkt;
  2229. }
  2230. #else
  2231. dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
  2232. matroska->prev_pkt = pkt;
  2233. #endif
  2234. return 0;
  2235. fail:
  2236. if (pkt_data != data)
  2237. av_freep(&pkt_data);
  2238. return res;
  2239. }
  2240. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  2241. int size, int64_t pos, uint64_t cluster_time,
  2242. uint64_t block_duration, int is_keyframe,
  2243. uint8_t *additional, uint64_t additional_id, int additional_size,
  2244. int64_t cluster_pos, uint64_t discard_padding)
  2245. {
  2246. uint64_t timecode = AV_NOPTS_VALUE;
  2247. MatroskaTrack *track;
  2248. int res = 0;
  2249. AVStream *st;
  2250. int16_t block_time;
  2251. uint32_t *lace_size = NULL;
  2252. int n, flags, laces = 0;
  2253. uint64_t num;
  2254. int trust_default_duration = 1;
  2255. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  2256. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  2257. return n;
  2258. }
  2259. data += n;
  2260. size -= n;
  2261. track = matroska_find_track_by_num(matroska, num);
  2262. if (!track || !track->stream) {
  2263. av_log(matroska->ctx, AV_LOG_INFO,
  2264. "Invalid stream %"PRIu64" or size %u\n", num, size);
  2265. return AVERROR_INVALIDDATA;
  2266. } else if (size <= 3)
  2267. return 0;
  2268. st = track->stream;
  2269. if (st->discard >= AVDISCARD_ALL)
  2270. return res;
  2271. av_assert1(block_duration != AV_NOPTS_VALUE);
  2272. block_time = sign_extend(AV_RB16(data), 16);
  2273. data += 2;
  2274. flags = *data++;
  2275. size -= 3;
  2276. if (is_keyframe == -1)
  2277. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  2278. if (cluster_time != (uint64_t)-1
  2279. && (block_time >= 0 || cluster_time >= -block_time)) {
  2280. timecode = cluster_time + block_time;
  2281. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  2282. && timecode < track->end_timecode)
  2283. is_keyframe = 0; /* overlapping subtitles are not key frame */
  2284. if (is_keyframe)
  2285. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  2286. }
  2287. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  2288. if (timecode < matroska->skip_to_timecode)
  2289. return res;
  2290. if (is_keyframe)
  2291. matroska->skip_to_keyframe = 0;
  2292. else if (!st->skip_to_keyframe) {
  2293. av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
  2294. matroska->skip_to_keyframe = 0;
  2295. }
  2296. }
  2297. res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
  2298. &lace_size, &laces);
  2299. if (res)
  2300. goto end;
  2301. if (track->audio.samplerate == 8000) {
  2302. // If this is needed for more codecs, then add them here
  2303. if (st->codec->codec_id == AV_CODEC_ID_AC3) {
  2304. if(track->audio.samplerate != st->codec->sample_rate || !st->codec->frame_size)
  2305. trust_default_duration = 0;
  2306. }
  2307. }
  2308. if (!block_duration && trust_default_duration)
  2309. block_duration = track->default_duration * laces / matroska->time_scale;
  2310. if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
  2311. track->end_timecode =
  2312. FFMAX(track->end_timecode, timecode + block_duration);
  2313. for (n = 0; n < laces; n++) {
  2314. int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
  2315. if (lace_size[n] > size) {
  2316. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  2317. break;
  2318. }
  2319. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  2320. st->codec->codec_id == AV_CODEC_ID_COOK ||
  2321. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  2322. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  2323. st->codec->block_align && track->audio.sub_packet_size) {
  2324. res = matroska_parse_rm_audio(matroska, track, st, data,
  2325. lace_size[n],
  2326. timecode, pos);
  2327. if (res)
  2328. goto end;
  2329. } else if (st->codec->codec_id == AV_CODEC_ID_WEBVTT) {
  2330. res = matroska_parse_webvtt(matroska, track, st,
  2331. data, lace_size[n],
  2332. timecode, lace_duration,
  2333. pos);
  2334. if (res)
  2335. goto end;
  2336. } else {
  2337. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  2338. timecode, lace_duration,
  2339. pos, !n? is_keyframe : 0,
  2340. additional, additional_id, additional_size,
  2341. discard_padding);
  2342. if (res)
  2343. goto end;
  2344. }
  2345. if (timecode != AV_NOPTS_VALUE)
  2346. timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
  2347. data += lace_size[n];
  2348. size -= lace_size[n];
  2349. }
  2350. end:
  2351. av_free(lace_size);
  2352. return res;
  2353. }
  2354. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  2355. {
  2356. EbmlList *blocks_list;
  2357. MatroskaBlock *blocks;
  2358. int i, res;
  2359. res = ebml_parse(matroska,
  2360. matroska_cluster_incremental_parsing,
  2361. &matroska->current_cluster);
  2362. if (res == 1) {
  2363. /* New Cluster */
  2364. if (matroska->current_cluster_pos)
  2365. ebml_level_end(matroska);
  2366. ebml_free(matroska_cluster, &matroska->current_cluster);
  2367. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2368. matroska->current_cluster_num_blocks = 0;
  2369. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2370. matroska->prev_pkt = NULL;
  2371. /* sizeof the ID which was already read */
  2372. if (matroska->current_id)
  2373. matroska->current_cluster_pos -= 4;
  2374. res = ebml_parse(matroska,
  2375. matroska_clusters_incremental,
  2376. &matroska->current_cluster);
  2377. /* Try parsing the block again. */
  2378. if (res == 1)
  2379. res = ebml_parse(matroska,
  2380. matroska_cluster_incremental_parsing,
  2381. &matroska->current_cluster);
  2382. }
  2383. if (!res &&
  2384. matroska->current_cluster_num_blocks <
  2385. matroska->current_cluster.blocks.nb_elem) {
  2386. blocks_list = &matroska->current_cluster.blocks;
  2387. blocks = blocks_list->elem;
  2388. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2389. i = blocks_list->nb_elem - 1;
  2390. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2391. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2392. uint8_t* additional = blocks[i].additional.size > 0 ?
  2393. blocks[i].additional.data : NULL;
  2394. if (!blocks[i].non_simple)
  2395. blocks[i].duration = 0;
  2396. res = matroska_parse_block(matroska,
  2397. blocks[i].bin.data, blocks[i].bin.size,
  2398. blocks[i].bin.pos,
  2399. matroska->current_cluster.timecode,
  2400. blocks[i].duration, is_keyframe,
  2401. additional, blocks[i].additional_id,
  2402. blocks[i].additional.size,
  2403. matroska->current_cluster_pos,
  2404. blocks[i].discard_padding);
  2405. }
  2406. }
  2407. return res;
  2408. }
  2409. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2410. {
  2411. MatroskaCluster cluster = { 0 };
  2412. EbmlList *blocks_list;
  2413. MatroskaBlock *blocks;
  2414. int i, res;
  2415. int64_t pos;
  2416. if (!matroska->contains_ssa)
  2417. return matroska_parse_cluster_incremental(matroska);
  2418. pos = avio_tell(matroska->ctx->pb);
  2419. matroska->prev_pkt = NULL;
  2420. if (matroska->current_id)
  2421. pos -= 4; /* sizeof the ID which was already read */
  2422. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2423. blocks_list = &cluster.blocks;
  2424. blocks = blocks_list->elem;
  2425. for (i=0; i<blocks_list->nb_elem; i++)
  2426. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2427. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2428. res=matroska_parse_block(matroska,
  2429. blocks[i].bin.data, blocks[i].bin.size,
  2430. blocks[i].bin.pos, cluster.timecode,
  2431. blocks[i].duration, is_keyframe, NULL, 0, 0,
  2432. pos, blocks[i].discard_padding);
  2433. }
  2434. ebml_free(matroska_cluster, &cluster);
  2435. return res;
  2436. }
  2437. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2438. {
  2439. MatroskaDemuxContext *matroska = s->priv_data;
  2440. while (matroska_deliver_packet(matroska, pkt)) {
  2441. int64_t pos = avio_tell(matroska->ctx->pb);
  2442. if (matroska->done)
  2443. return AVERROR_EOF;
  2444. if (matroska_parse_cluster(matroska) < 0)
  2445. matroska_resync(matroska, pos);
  2446. }
  2447. return 0;
  2448. }
  2449. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2450. int64_t timestamp, int flags)
  2451. {
  2452. MatroskaDemuxContext *matroska = s->priv_data;
  2453. MatroskaTrack *tracks = matroska->tracks.elem;
  2454. AVStream *st = s->streams[stream_index];
  2455. int i, index, index_sub, index_min;
  2456. /* Parse the CUES now since we need the index data to seek. */
  2457. if (matroska->cues_parsing_deferred > 0) {
  2458. matroska->cues_parsing_deferred = 0;
  2459. matroska_parse_cues(matroska);
  2460. }
  2461. if (!st->nb_index_entries)
  2462. goto err;
  2463. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2464. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2465. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  2466. matroska->current_id = 0;
  2467. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2468. matroska_clear_queue(matroska);
  2469. if (matroska_parse_cluster(matroska) < 0)
  2470. break;
  2471. }
  2472. }
  2473. matroska_clear_queue(matroska);
  2474. if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
  2475. goto err;
  2476. index_min = index;
  2477. for (i=0; i < matroska->tracks.nb_elem; i++) {
  2478. tracks[i].audio.pkt_cnt = 0;
  2479. tracks[i].audio.sub_packet_cnt = 0;
  2480. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2481. tracks[i].end_timecode = 0;
  2482. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  2483. && tracks[i].stream->discard != AVDISCARD_ALL) {
  2484. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  2485. while(index_sub >= 0
  2486. && index_min >= 0
  2487. && tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos
  2488. && st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  2489. index_min--;
  2490. }
  2491. }
  2492. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2493. matroska->current_id = 0;
  2494. if (flags & AVSEEK_FLAG_ANY) {
  2495. st->skip_to_keyframe = 0;
  2496. matroska->skip_to_timecode = timestamp;
  2497. } else {
  2498. st->skip_to_keyframe = 1;
  2499. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2500. }
  2501. matroska->skip_to_keyframe = 1;
  2502. matroska->done = 0;
  2503. matroska->num_levels = 0;
  2504. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2505. return 0;
  2506. err:
  2507. // slightly hackish but allows proper fallback to
  2508. // the generic seeking code.
  2509. matroska_clear_queue(matroska);
  2510. matroska->current_id = 0;
  2511. st->skip_to_keyframe =
  2512. matroska->skip_to_keyframe = 0;
  2513. matroska->done = 0;
  2514. matroska->num_levels = 0;
  2515. return -1;
  2516. }
  2517. static int matroska_read_close(AVFormatContext *s)
  2518. {
  2519. MatroskaDemuxContext *matroska = s->priv_data;
  2520. MatroskaTrack *tracks = matroska->tracks.elem;
  2521. int n;
  2522. matroska_clear_queue(matroska);
  2523. for (n=0; n < matroska->tracks.nb_elem; n++)
  2524. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2525. av_free(tracks[n].audio.buf);
  2526. ebml_free(matroska_cluster, &matroska->current_cluster);
  2527. ebml_free(matroska_segment, matroska);
  2528. return 0;
  2529. }
  2530. AVInputFormat ff_matroska_demuxer = {
  2531. .name = "matroska,webm",
  2532. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2533. .priv_data_size = sizeof(MatroskaDemuxContext),
  2534. .read_probe = matroska_probe,
  2535. .read_header = matroska_read_header,
  2536. .read_packet = matroska_read_packet,
  2537. .read_close = matroska_read_close,
  2538. .read_seek = matroska_read_seek,
  2539. };