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.

2863 lines
100KB

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