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.

2672 lines
94KB

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