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.

2465 lines
86KB

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