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.

2466 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. bin->size = 0;
  674. return AVERROR(EIO);
  675. }
  676. return 0;
  677. }
  678. /*
  679. * Read the next element, but only the header. The contents
  680. * are supposed to be sub-elements which can be read separately.
  681. * 0 is success, < 0 is failure.
  682. */
  683. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  684. {
  685. AVIOContext *pb = matroska->ctx->pb;
  686. MatroskaLevel *level;
  687. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  688. av_log(matroska->ctx, AV_LOG_ERROR,
  689. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  690. return AVERROR(ENOSYS);
  691. }
  692. level = &matroska->levels[matroska->num_levels++];
  693. level->start = avio_tell(pb);
  694. level->length = length;
  695. return 0;
  696. }
  697. /*
  698. * Read signed/unsigned "EBML" numbers.
  699. * Return: number of bytes processed, < 0 on error
  700. */
  701. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  702. uint8_t *data, uint32_t size, uint64_t *num)
  703. {
  704. AVIOContext pb;
  705. ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  706. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  707. }
  708. /*
  709. * Same as above, but signed.
  710. */
  711. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  712. uint8_t *data, uint32_t size, int64_t *num)
  713. {
  714. uint64_t unum;
  715. int res;
  716. /* read as unsigned number first */
  717. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  718. return res;
  719. /* make signed (weird way) */
  720. *num = unum - ((1LL << (7*res - 1)) - 1);
  721. return res;
  722. }
  723. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  724. EbmlSyntax *syntax, void *data);
  725. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  726. uint32_t id, void *data)
  727. {
  728. int i;
  729. for (i=0; syntax[i].id; i++)
  730. if (id == syntax[i].id)
  731. break;
  732. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  733. matroska->num_levels > 0 &&
  734. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  735. return 0; // we reached the end of an unknown size cluster
  736. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
  737. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  738. if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
  739. return AVERROR_INVALIDDATA;
  740. }
  741. return ebml_parse_elem(matroska, &syntax[i], data);
  742. }
  743. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  744. void *data)
  745. {
  746. if (!matroska->current_id) {
  747. uint64_t id;
  748. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  749. if (res < 0)
  750. return res;
  751. matroska->current_id = id | 1 << 7*res;
  752. }
  753. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  754. }
  755. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  756. void *data)
  757. {
  758. int i, res = 0;
  759. for (i=0; syntax[i].id; i++)
  760. switch (syntax[i].type) {
  761. case EBML_UINT:
  762. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  763. break;
  764. case EBML_FLOAT:
  765. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  766. break;
  767. case EBML_STR:
  768. case EBML_UTF8:
  769. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  770. break;
  771. }
  772. while (!res && !ebml_level_end(matroska))
  773. res = ebml_parse(matroska, syntax, data);
  774. return res;
  775. }
  776. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  777. EbmlSyntax *syntax, void *data)
  778. {
  779. static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
  780. [EBML_UINT] = 8,
  781. [EBML_FLOAT] = 8,
  782. // max. 16 MB for strings
  783. [EBML_STR] = 0x1000000,
  784. [EBML_UTF8] = 0x1000000,
  785. // max. 256 MB for binary data
  786. [EBML_BIN] = 0x10000000,
  787. // no limits for anything else
  788. };
  789. AVIOContext *pb = matroska->ctx->pb;
  790. uint32_t id = syntax->id;
  791. uint64_t length;
  792. int res;
  793. void *newelem;
  794. data = (char *)data + syntax->data_offset;
  795. if (syntax->list_elem_size) {
  796. EbmlList *list = data;
  797. newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  798. if (!newelem)
  799. return AVERROR(ENOMEM);
  800. list->elem = newelem;
  801. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  802. memset(data, 0, syntax->list_elem_size);
  803. list->nb_elem++;
  804. }
  805. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  806. matroska->current_id = 0;
  807. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  808. return res;
  809. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  810. av_log(matroska->ctx, AV_LOG_ERROR,
  811. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  812. length, max_lengths[syntax->type], syntax->type);
  813. return AVERROR_INVALIDDATA;
  814. }
  815. }
  816. switch (syntax->type) {
  817. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  818. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  819. case EBML_STR:
  820. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  821. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  822. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  823. return res;
  824. if (id == MATROSKA_ID_SEGMENT)
  825. matroska->segment_start = avio_tell(matroska->ctx->pb);
  826. return ebml_parse_nest(matroska, syntax->def.n, data);
  827. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  828. case EBML_STOP: return 1;
  829. default:
  830. if(ffio_limit(pb, length) != length)
  831. return AVERROR(EIO);
  832. return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
  833. }
  834. if (res == AVERROR_INVALIDDATA)
  835. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  836. else if (res == AVERROR(EIO))
  837. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  838. return res;
  839. }
  840. static void ebml_free(EbmlSyntax *syntax, void *data)
  841. {
  842. int i, j;
  843. for (i=0; syntax[i].id; i++) {
  844. void *data_off = (char *)data + syntax[i].data_offset;
  845. switch (syntax[i].type) {
  846. case EBML_STR:
  847. case EBML_UTF8: av_freep(data_off); break;
  848. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  849. case EBML_NEST:
  850. if (syntax[i].list_elem_size) {
  851. EbmlList *list = data_off;
  852. char *ptr = list->elem;
  853. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  854. ebml_free(syntax[i].def.n, ptr);
  855. av_free(list->elem);
  856. } else
  857. ebml_free(syntax[i].def.n, data_off);
  858. default: break;
  859. }
  860. }
  861. }
  862. /*
  863. * Autodetecting...
  864. */
  865. static int matroska_probe(AVProbeData *p)
  866. {
  867. uint64_t total = 0;
  868. int len_mask = 0x80, size = 1, n = 1, i;
  869. /* EBML header? */
  870. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  871. return 0;
  872. /* length of header */
  873. total = p->buf[4];
  874. while (size <= 8 && !(total & len_mask)) {
  875. size++;
  876. len_mask >>= 1;
  877. }
  878. if (size > 8)
  879. return 0;
  880. total &= (len_mask - 1);
  881. while (n < size)
  882. total = (total << 8) | p->buf[4 + n++];
  883. /* Does the probe data contain the whole header? */
  884. if (p->buf_size < 4 + size + total)
  885. return 0;
  886. /* The header should contain a known document type. For now,
  887. * we don't parse the whole header but simply check for the
  888. * availability of that array of characters inside the header.
  889. * Not fully fool-proof, but good enough. */
  890. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  891. int probelen = strlen(matroska_doctypes[i]);
  892. if (total < probelen)
  893. continue;
  894. for (n = 4+size; n <= 4+size+total-probelen; n++)
  895. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  896. return AVPROBE_SCORE_MAX;
  897. }
  898. // probably valid EBML header but no recognized doctype
  899. return AVPROBE_SCORE_MAX/2;
  900. }
  901. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  902. int num)
  903. {
  904. MatroskaTrack *tracks = matroska->tracks.elem;
  905. int i;
  906. for (i=0; i < matroska->tracks.nb_elem; i++)
  907. if (tracks[i].num == num)
  908. return &tracks[i];
  909. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  910. return NULL;
  911. }
  912. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  913. MatroskaTrack *track)
  914. {
  915. MatroskaTrackEncoding *encodings = track->encodings.elem;
  916. uint8_t* data = *buf;
  917. int isize = *buf_size;
  918. uint8_t* pkt_data = NULL;
  919. uint8_t av_unused *newpktdata;
  920. int pkt_size = isize;
  921. int result = 0;
  922. int olen;
  923. if (pkt_size >= 10000000U)
  924. return AVERROR_INVALIDDATA;
  925. switch (encodings[0].compression.algo) {
  926. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
  927. int header_size = encodings[0].compression.settings.size;
  928. uint8_t *header = encodings[0].compression.settings.data;
  929. if (header_size && !header) {
  930. av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
  931. return -1;
  932. }
  933. if (!header_size)
  934. return 0;
  935. pkt_size = isize + header_size;
  936. pkt_data = av_malloc(pkt_size);
  937. if (!pkt_data)
  938. return AVERROR(ENOMEM);
  939. memcpy(pkt_data, header, header_size);
  940. memcpy(pkt_data + header_size, data, isize);
  941. break;
  942. }
  943. #if CONFIG_LZO
  944. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  945. do {
  946. olen = pkt_size *= 3;
  947. newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
  948. if (!newpktdata) {
  949. result = AVERROR(ENOMEM);
  950. goto failed;
  951. }
  952. pkt_data = newpktdata;
  953. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  954. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  955. if (result) {
  956. result = AVERROR_INVALIDDATA;
  957. goto failed;
  958. }
  959. pkt_size -= olen;
  960. break;
  961. #endif
  962. #if CONFIG_ZLIB
  963. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  964. z_stream zstream = {0};
  965. if (inflateInit(&zstream) != Z_OK)
  966. return -1;
  967. zstream.next_in = data;
  968. zstream.avail_in = isize;
  969. do {
  970. pkt_size *= 3;
  971. newpktdata = av_realloc(pkt_data, pkt_size);
  972. if (!newpktdata) {
  973. inflateEnd(&zstream);
  974. goto failed;
  975. }
  976. pkt_data = newpktdata;
  977. zstream.avail_out = pkt_size - zstream.total_out;
  978. zstream.next_out = pkt_data + zstream.total_out;
  979. if (pkt_data) {
  980. result = inflate(&zstream, Z_NO_FLUSH);
  981. } else
  982. result = Z_MEM_ERROR;
  983. } while (result==Z_OK && pkt_size<10000000);
  984. pkt_size = zstream.total_out;
  985. inflateEnd(&zstream);
  986. if (result != Z_STREAM_END) {
  987. if (result == Z_MEM_ERROR)
  988. result = AVERROR(ENOMEM);
  989. else
  990. result = AVERROR_INVALIDDATA;
  991. goto failed;
  992. }
  993. break;
  994. }
  995. #endif
  996. #if CONFIG_BZLIB
  997. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  998. bz_stream bzstream = {0};
  999. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  1000. return -1;
  1001. bzstream.next_in = data;
  1002. bzstream.avail_in = isize;
  1003. do {
  1004. pkt_size *= 3;
  1005. newpktdata = av_realloc(pkt_data, pkt_size);
  1006. if (!newpktdata) {
  1007. BZ2_bzDecompressEnd(&bzstream);
  1008. goto failed;
  1009. }
  1010. pkt_data = newpktdata;
  1011. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  1012. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  1013. if (pkt_data) {
  1014. result = BZ2_bzDecompress(&bzstream);
  1015. } else
  1016. result = BZ_MEM_ERROR;
  1017. } while (result==BZ_OK && pkt_size<10000000);
  1018. pkt_size = bzstream.total_out_lo32;
  1019. BZ2_bzDecompressEnd(&bzstream);
  1020. if (result != BZ_STREAM_END) {
  1021. if (result == BZ_MEM_ERROR)
  1022. result = AVERROR(ENOMEM);
  1023. else
  1024. result = AVERROR_INVALIDDATA;
  1025. goto failed;
  1026. }
  1027. break;
  1028. }
  1029. #endif
  1030. default:
  1031. return AVERROR_INVALIDDATA;
  1032. }
  1033. *buf = pkt_data;
  1034. *buf_size = pkt_size;
  1035. return 0;
  1036. failed:
  1037. av_free(pkt_data);
  1038. return result;
  1039. }
  1040. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  1041. AVPacket *pkt, uint64_t display_duration)
  1042. {
  1043. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  1044. for (; *ptr!=',' && ptr<end-1; ptr++);
  1045. if (*ptr == ',')
  1046. ptr++;
  1047. layer = ptr;
  1048. for (; *ptr!=',' && ptr<end-1; ptr++);
  1049. if (*ptr == ',') {
  1050. int64_t end_pts = pkt->pts + display_duration;
  1051. int sc = matroska->time_scale * pkt->pts / 10000000;
  1052. int ec = matroska->time_scale * end_pts / 10000000;
  1053. int sh, sm, ss, eh, em, es, len;
  1054. sh = sc/360000; sc -= 360000*sh;
  1055. sm = sc/ 6000; sc -= 6000*sm;
  1056. ss = sc/ 100; sc -= 100*ss;
  1057. eh = ec/360000; ec -= 360000*eh;
  1058. em = ec/ 6000; ec -= 6000*em;
  1059. es = ec/ 100; ec -= 100*es;
  1060. *ptr++ = '\0';
  1061. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  1062. if (!(line = av_malloc(len)))
  1063. return;
  1064. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  1065. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  1066. av_free(pkt->data);
  1067. pkt->data = line;
  1068. pkt->size = strlen(line);
  1069. }
  1070. }
  1071. static int matroska_merge_packets(AVPacket *out, AVPacket *in)
  1072. {
  1073. int ret = av_grow_packet(out, in->size);
  1074. if (ret < 0)
  1075. return ret;
  1076. memcpy(out->data + out->size - in->size, in->data, in->size);
  1077. av_free_packet(in);
  1078. av_free(in);
  1079. return 0;
  1080. }
  1081. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  1082. AVDictionary **metadata, char *prefix)
  1083. {
  1084. MatroskaTag *tags = list->elem;
  1085. char key[1024];
  1086. int i;
  1087. for (i=0; i < list->nb_elem; i++) {
  1088. const char *lang= (tags[i].lang && strcmp(tags[i].lang, "und")) ? tags[i].lang : NULL;
  1089. if (!tags[i].name) {
  1090. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  1091. continue;
  1092. }
  1093. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  1094. else av_strlcpy(key, tags[i].name, sizeof(key));
  1095. if (tags[i].def || !lang) {
  1096. av_dict_set(metadata, key, tags[i].string, 0);
  1097. if (tags[i].sub.nb_elem)
  1098. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1099. }
  1100. if (lang) {
  1101. av_strlcat(key, "-", sizeof(key));
  1102. av_strlcat(key, lang, sizeof(key));
  1103. av_dict_set(metadata, key, tags[i].string, 0);
  1104. if (tags[i].sub.nb_elem)
  1105. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  1106. }
  1107. }
  1108. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  1109. }
  1110. static void matroska_convert_tags(AVFormatContext *s)
  1111. {
  1112. MatroskaDemuxContext *matroska = s->priv_data;
  1113. MatroskaTags *tags = matroska->tags.elem;
  1114. int i, j;
  1115. for (i=0; i < matroska->tags.nb_elem; i++) {
  1116. if (tags[i].target.attachuid) {
  1117. MatroskaAttachement *attachment = matroska->attachments.elem;
  1118. for (j=0; j<matroska->attachments.nb_elem; j++)
  1119. if (attachment[j].uid == tags[i].target.attachuid
  1120. && attachment[j].stream)
  1121. matroska_convert_tag(s, &tags[i].tag,
  1122. &attachment[j].stream->metadata, NULL);
  1123. } else if (tags[i].target.chapteruid) {
  1124. MatroskaChapter *chapter = matroska->chapters.elem;
  1125. for (j=0; j<matroska->chapters.nb_elem; j++)
  1126. if (chapter[j].uid == tags[i].target.chapteruid
  1127. && chapter[j].chapter)
  1128. matroska_convert_tag(s, &tags[i].tag,
  1129. &chapter[j].chapter->metadata, NULL);
  1130. } else if (tags[i].target.trackuid) {
  1131. MatroskaTrack *track = matroska->tracks.elem;
  1132. for (j=0; j<matroska->tracks.nb_elem; j++)
  1133. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1134. matroska_convert_tag(s, &tags[i].tag,
  1135. &track[j].stream->metadata, NULL);
  1136. } else {
  1137. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1138. tags[i].target.type);
  1139. }
  1140. }
  1141. }
  1142. static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
  1143. {
  1144. EbmlList *seekhead_list = &matroska->seekhead;
  1145. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1146. uint32_t level_up = matroska->level_up;
  1147. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1148. uint32_t saved_id = matroska->current_id;
  1149. MatroskaLevel level;
  1150. int64_t offset;
  1151. int ret = 0;
  1152. if (idx >= seekhead_list->nb_elem
  1153. || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
  1154. || seekhead[idx].id == MATROSKA_ID_CLUSTER)
  1155. return 0;
  1156. /* seek */
  1157. offset = seekhead[idx].pos + matroska->segment_start;
  1158. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
  1159. /* We don't want to lose our seekhead level, so we add
  1160. * a dummy. This is a crude hack. */
  1161. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1162. av_log(matroska->ctx, AV_LOG_INFO,
  1163. "Max EBML element depth (%d) reached, "
  1164. "cannot parse further.\n", EBML_MAX_DEPTH);
  1165. ret = AVERROR_INVALIDDATA;
  1166. } else {
  1167. level.start = 0;
  1168. level.length = (uint64_t)-1;
  1169. matroska->levels[matroska->num_levels] = level;
  1170. matroska->num_levels++;
  1171. matroska->current_id = 0;
  1172. ret = ebml_parse(matroska, matroska_segment, matroska);
  1173. /* remove dummy level */
  1174. while (matroska->num_levels) {
  1175. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1176. if (length == (uint64_t)-1)
  1177. break;
  1178. }
  1179. }
  1180. }
  1181. /* seek back */
  1182. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1183. matroska->level_up = level_up;
  1184. matroska->current_id = saved_id;
  1185. return ret;
  1186. }
  1187. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1188. {
  1189. EbmlList *seekhead_list = &matroska->seekhead;
  1190. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1191. int i;
  1192. // we should not do any seeking in the streaming case
  1193. if (!matroska->ctx->pb->seekable ||
  1194. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1195. return;
  1196. for (i = 0; i < seekhead_list->nb_elem; i++) {
  1197. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1198. if (seekhead[i].pos <= before_pos)
  1199. continue;
  1200. // defer cues parsing until we actually need cue data.
  1201. if (seekhead[i].id == MATROSKA_ID_CUES) {
  1202. matroska->cues_parsing_deferred = 1;
  1203. continue;
  1204. }
  1205. if (matroska_parse_seekhead_entry(matroska, i) < 0) {
  1206. // mark index as broken
  1207. matroska->cues_parsing_deferred = -1;
  1208. break;
  1209. }
  1210. }
  1211. }
  1212. static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
  1213. EbmlList *index_list;
  1214. MatroskaIndex *index;
  1215. int index_scale = 1;
  1216. int i, j;
  1217. index_list = &matroska->index;
  1218. index = index_list->elem;
  1219. if (index_list->nb_elem
  1220. && index[0].time > 1E14/matroska->time_scale) {
  1221. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1222. index_scale = matroska->time_scale;
  1223. }
  1224. for (i = 0; i < index_list->nb_elem; i++) {
  1225. EbmlList *pos_list = &index[i].pos;
  1226. MatroskaIndexPos *pos = pos_list->elem;
  1227. for (j = 0; j < pos_list->nb_elem; j++) {
  1228. MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
  1229. if (track && track->stream)
  1230. av_add_index_entry(track->stream,
  1231. pos[j].pos + matroska->segment_start,
  1232. index[i].time/index_scale, 0, 0,
  1233. AVINDEX_KEYFRAME);
  1234. }
  1235. }
  1236. }
  1237. static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
  1238. EbmlList *seekhead_list = &matroska->seekhead;
  1239. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1240. int i;
  1241. for (i = 0; i < seekhead_list->nb_elem; i++)
  1242. if (seekhead[i].id == MATROSKA_ID_CUES)
  1243. break;
  1244. assert(i <= seekhead_list->nb_elem);
  1245. if (matroska_parse_seekhead_entry(matroska, i) < 0)
  1246. matroska->cues_parsing_deferred = -1;
  1247. matroska_add_index_entries(matroska);
  1248. }
  1249. static int matroska_aac_profile(char *codec_id)
  1250. {
  1251. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1252. int profile;
  1253. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1254. if (strstr(codec_id, aac_profiles[profile]))
  1255. break;
  1256. return profile + 1;
  1257. }
  1258. static int matroska_aac_sri(int samplerate)
  1259. {
  1260. int sri;
  1261. for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
  1262. if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
  1263. break;
  1264. return sri;
  1265. }
  1266. static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
  1267. {
  1268. char buffer[32];
  1269. /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
  1270. time_t creation_time = date_utc / 1000000000 + 978307200;
  1271. struct tm *ptm = gmtime(&creation_time);
  1272. if (!ptm) return;
  1273. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
  1274. av_dict_set(metadata, "creation_time", buffer, 0);
  1275. }
  1276. static int matroska_read_header(AVFormatContext *s)
  1277. {
  1278. MatroskaDemuxContext *matroska = s->priv_data;
  1279. EbmlList *attachements_list = &matroska->attachments;
  1280. MatroskaAttachement *attachements;
  1281. EbmlList *chapters_list = &matroska->chapters;
  1282. MatroskaChapter *chapters;
  1283. MatroskaTrack *tracks;
  1284. uint64_t max_start = 0;
  1285. int64_t pos;
  1286. Ebml ebml = { 0 };
  1287. AVStream *st;
  1288. int i, j, k, res;
  1289. matroska->ctx = s;
  1290. /* First read the EBML header. */
  1291. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1292. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1293. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
  1294. av_log(matroska->ctx, AV_LOG_ERROR,
  1295. "EBML header using unsupported features\n"
  1296. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1297. ebml.version, ebml.doctype, ebml.doctype_version);
  1298. ebml_free(ebml_syntax, &ebml);
  1299. return AVERROR_PATCHWELCOME;
  1300. } else if (ebml.doctype_version == 3) {
  1301. av_log(matroska->ctx, AV_LOG_WARNING,
  1302. "EBML header using unsupported features\n"
  1303. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1304. ebml.version, ebml.doctype, ebml.doctype_version);
  1305. }
  1306. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1307. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1308. break;
  1309. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1310. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1311. if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
  1312. ebml_free(ebml_syntax, &ebml);
  1313. return AVERROR_INVALIDDATA;
  1314. }
  1315. }
  1316. ebml_free(ebml_syntax, &ebml);
  1317. /* The next thing is a segment. */
  1318. pos = avio_tell(matroska->ctx->pb);
  1319. res = ebml_parse(matroska, matroska_segments, matroska);
  1320. // try resyncing until we find a EBML_STOP type element.
  1321. while (res != 1) {
  1322. res = matroska_resync(matroska, pos);
  1323. if (res < 0)
  1324. return res;
  1325. pos = avio_tell(matroska->ctx->pb);
  1326. res = ebml_parse(matroska, matroska_segment, matroska);
  1327. }
  1328. matroska_execute_seekhead(matroska);
  1329. if (!matroska->time_scale)
  1330. matroska->time_scale = 1000000;
  1331. if (matroska->duration)
  1332. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1333. * 1000 / AV_TIME_BASE;
  1334. av_dict_set(&s->metadata, "title", matroska->title, 0);
  1335. if (matroska->date_utc.size == 8)
  1336. matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
  1337. tracks = matroska->tracks.elem;
  1338. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1339. MatroskaTrack *track = &tracks[i];
  1340. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  1341. EbmlList *encodings_list = &track->encodings;
  1342. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1343. uint8_t *extradata = NULL;
  1344. int extradata_size = 0;
  1345. int extradata_offset = 0;
  1346. uint32_t fourcc = 0;
  1347. AVIOContext b;
  1348. /* Apply some sanity checks. */
  1349. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1350. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1351. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1352. av_log(matroska->ctx, AV_LOG_INFO,
  1353. "Unknown or unsupported track type %"PRIu64"\n",
  1354. track->type);
  1355. continue;
  1356. }
  1357. if (track->codec_id == NULL)
  1358. continue;
  1359. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1360. if (!track->default_duration && track->video.frame_rate > 0)
  1361. track->default_duration = 1000000000/track->video.frame_rate;
  1362. if (!track->video.display_width)
  1363. track->video.display_width = track->video.pixel_width;
  1364. if (!track->video.display_height)
  1365. track->video.display_height = track->video.pixel_height;
  1366. if (track->video.color_space.size == 4)
  1367. fourcc = AV_RL32(track->video.color_space.data);
  1368. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1369. if (!track->audio.out_samplerate)
  1370. track->audio.out_samplerate = track->audio.samplerate;
  1371. }
  1372. if (encodings_list->nb_elem > 1) {
  1373. av_log(matroska->ctx, AV_LOG_ERROR,
  1374. "Multiple combined encodings not supported");
  1375. } else if (encodings_list->nb_elem == 1) {
  1376. if (encodings[0].type ||
  1377. (
  1378. #if CONFIG_ZLIB
  1379. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1380. #endif
  1381. #if CONFIG_BZLIB
  1382. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1383. #endif
  1384. #if CONFIG_LZO
  1385. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
  1386. #endif
  1387. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
  1388. encodings[0].scope = 0;
  1389. av_log(matroska->ctx, AV_LOG_ERROR,
  1390. "Unsupported encoding type");
  1391. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1392. uint8_t *codec_priv = track->codec_priv.data;
  1393. int ret = matroska_decode_buffer(&track->codec_priv.data,
  1394. &track->codec_priv.size,
  1395. track);
  1396. if (ret < 0) {
  1397. track->codec_priv.data = NULL;
  1398. track->codec_priv.size = 0;
  1399. av_log(matroska->ctx, AV_LOG_ERROR,
  1400. "Failed to decode codec private data\n");
  1401. }
  1402. if (codec_priv != track->codec_priv.data)
  1403. av_free(codec_priv);
  1404. }
  1405. }
  1406. for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
  1407. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1408. strlen(ff_mkv_codec_tags[j].str))){
  1409. codec_id= ff_mkv_codec_tags[j].id;
  1410. break;
  1411. }
  1412. }
  1413. st = track->stream = avformat_new_stream(s, NULL);
  1414. if (st == NULL)
  1415. return AVERROR(ENOMEM);
  1416. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1417. && track->codec_priv.size >= 40
  1418. && track->codec_priv.data != NULL) {
  1419. track->ms_compat = 1;
  1420. fourcc = AV_RL32(track->codec_priv.data + 16);
  1421. codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
  1422. extradata_offset = 40;
  1423. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1424. && track->codec_priv.size >= 14
  1425. && track->codec_priv.data != NULL) {
  1426. int ret;
  1427. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1428. AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
  1429. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1430. if (ret < 0)
  1431. return ret;
  1432. codec_id = st->codec->codec_id;
  1433. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1434. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1435. && (track->codec_priv.size >= 86)
  1436. && (track->codec_priv.data != NULL)) {
  1437. fourcc = AV_RL32(track->codec_priv.data);
  1438. codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
  1439. } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX-12) {
  1440. /* Only ALAC's magic cookie is stored in Matroska's track headers.
  1441. Create the "atom size", "tag", and "tag version" fields the
  1442. decoder expects manually. */
  1443. extradata_size = 12 + track->codec_priv.size;
  1444. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1445. if (extradata == NULL)
  1446. return AVERROR(ENOMEM);
  1447. AV_WB32(extradata, extradata_size);
  1448. memcpy(&extradata[4], "alac", 4);
  1449. AV_WB32(&extradata[8], 0);
  1450. memcpy(&extradata[12], track->codec_priv.data, track->codec_priv.size);
  1451. } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
  1452. switch (track->audio.bitdepth) {
  1453. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1454. case 24: codec_id = AV_CODEC_ID_PCM_S24BE; break;
  1455. case 32: codec_id = AV_CODEC_ID_PCM_S32BE; break;
  1456. }
  1457. } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
  1458. switch (track->audio.bitdepth) {
  1459. case 8: codec_id = AV_CODEC_ID_PCM_U8; break;
  1460. case 24: codec_id = AV_CODEC_ID_PCM_S24LE; break;
  1461. case 32: codec_id = AV_CODEC_ID_PCM_S32LE; break;
  1462. }
  1463. } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1464. codec_id = AV_CODEC_ID_PCM_F64LE;
  1465. } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
  1466. int profile = matroska_aac_profile(track->codec_id);
  1467. int sri = matroska_aac_sri(track->audio.samplerate);
  1468. extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
  1469. if (extradata == NULL)
  1470. return AVERROR(ENOMEM);
  1471. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1472. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1473. if (strstr(track->codec_id, "SBR")) {
  1474. sri = matroska_aac_sri(track->audio.out_samplerate);
  1475. extradata[2] = 0x56;
  1476. extradata[3] = 0xE5;
  1477. extradata[4] = 0x80 | (sri<<3);
  1478. extradata_size = 5;
  1479. } else
  1480. extradata_size = 2;
  1481. } else if (codec_id == AV_CODEC_ID_TTA) {
  1482. extradata_size = 30;
  1483. extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1484. if (extradata == NULL)
  1485. return AVERROR(ENOMEM);
  1486. ffio_init_context(&b, extradata, extradata_size, 1,
  1487. NULL, NULL, NULL, NULL);
  1488. avio_write(&b, "TTA1", 4);
  1489. avio_wl16(&b, 1);
  1490. avio_wl16(&b, track->audio.channels);
  1491. avio_wl16(&b, track->audio.bitdepth);
  1492. avio_wl32(&b, track->audio.out_samplerate);
  1493. avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1494. } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
  1495. codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
  1496. extradata_offset = 26;
  1497. } else if (codec_id == AV_CODEC_ID_RA_144) {
  1498. track->audio.out_samplerate = 8000;
  1499. track->audio.channels = 1;
  1500. } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
  1501. codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
  1502. && track->codec_priv.data) {
  1503. int flavor;
  1504. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1505. 0, NULL, NULL, NULL, NULL);
  1506. avio_skip(&b, 22);
  1507. flavor = avio_rb16(&b);
  1508. track->audio.coded_framesize = avio_rb32(&b);
  1509. avio_skip(&b, 12);
  1510. track->audio.sub_packet_h = avio_rb16(&b);
  1511. track->audio.frame_size = avio_rb16(&b);
  1512. track->audio.sub_packet_size = avio_rb16(&b);
  1513. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1514. if (codec_id == AV_CODEC_ID_RA_288) {
  1515. st->codec->block_align = track->audio.coded_framesize;
  1516. track->codec_priv.size = 0;
  1517. } else {
  1518. if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
  1519. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1520. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1521. st->codec->bit_rate = sipr_bit_rate[flavor];
  1522. }
  1523. st->codec->block_align = track->audio.sub_packet_size;
  1524. extradata_offset = 78;
  1525. }
  1526. }
  1527. track->codec_priv.size -= extradata_offset;
  1528. if (codec_id == AV_CODEC_ID_NONE)
  1529. av_log(matroska->ctx, AV_LOG_INFO,
  1530. "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
  1531. if (track->time_scale < 0.01)
  1532. track->time_scale = 1.0;
  1533. avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1534. st->codec->codec_id = codec_id;
  1535. st->start_time = 0;
  1536. if (strcmp(track->language, "und"))
  1537. av_dict_set(&st->metadata, "language", track->language, 0);
  1538. av_dict_set(&st->metadata, "title", track->name, 0);
  1539. if (track->flag_default)
  1540. st->disposition |= AV_DISPOSITION_DEFAULT;
  1541. if (track->flag_forced)
  1542. st->disposition |= AV_DISPOSITION_FORCED;
  1543. if (!st->codec->extradata) {
  1544. if(extradata){
  1545. st->codec->extradata = extradata;
  1546. st->codec->extradata_size = extradata_size;
  1547. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1548. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1549. FF_INPUT_BUFFER_PADDING_SIZE);
  1550. if(st->codec->extradata == NULL)
  1551. return AVERROR(ENOMEM);
  1552. st->codec->extradata_size = track->codec_priv.size;
  1553. memcpy(st->codec->extradata,
  1554. track->codec_priv.data + extradata_offset,
  1555. track->codec_priv.size);
  1556. }
  1557. }
  1558. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1559. MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
  1560. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1561. st->codec->codec_tag = fourcc;
  1562. st->codec->width = track->video.pixel_width;
  1563. st->codec->height = track->video.pixel_height;
  1564. av_reduce(&st->sample_aspect_ratio.num,
  1565. &st->sample_aspect_ratio.den,
  1566. st->codec->height * track->video.display_width,
  1567. st->codec-> width * track->video.display_height,
  1568. 255);
  1569. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1570. if (track->default_duration) {
  1571. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1572. 1000000000, track->default_duration, 30000);
  1573. #if FF_API_R_FRAME_RATE
  1574. st->r_frame_rate = st->avg_frame_rate;
  1575. #endif
  1576. }
  1577. /* export stereo mode flag as metadata tag */
  1578. if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
  1579. av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
  1580. /* if we have virtual track, mark the real tracks */
  1581. for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
  1582. char buf[32];
  1583. if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
  1584. continue;
  1585. snprintf(buf, sizeof(buf), "%s_%d",
  1586. ff_matroska_video_stereo_plane[planes[j].type], i);
  1587. for (k=0; k < matroska->tracks.nb_elem; k++)
  1588. if (planes[j].uid == tracks[k].uid) {
  1589. av_dict_set(&s->streams[k]->metadata,
  1590. "stereo_mode", buf, 0);
  1591. break;
  1592. }
  1593. }
  1594. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1595. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1596. st->codec->sample_rate = track->audio.out_samplerate;
  1597. st->codec->channels = track->audio.channels;
  1598. if (st->codec->codec_id != AV_CODEC_ID_AAC)
  1599. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1600. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1601. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1602. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1603. matroska->contains_ssa = 1;
  1604. }
  1605. }
  1606. attachements = attachements_list->elem;
  1607. for (j=0; j<attachements_list->nb_elem; j++) {
  1608. if (!(attachements[j].filename && attachements[j].mime &&
  1609. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1610. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1611. } else {
  1612. AVStream *st = avformat_new_stream(s, NULL);
  1613. if (st == NULL)
  1614. break;
  1615. av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
  1616. av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
  1617. st->codec->codec_id = AV_CODEC_ID_NONE;
  1618. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1619. st->codec->extradata = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);
  1620. if(st->codec->extradata == NULL)
  1621. break;
  1622. st->codec->extradata_size = attachements[j].bin.size;
  1623. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1624. for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
  1625. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1626. strlen(ff_mkv_mime_tags[i].str))) {
  1627. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1628. break;
  1629. }
  1630. }
  1631. attachements[j].stream = st;
  1632. }
  1633. }
  1634. chapters = chapters_list->elem;
  1635. for (i=0; i<chapters_list->nb_elem; i++)
  1636. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1637. && (max_start==0 || chapters[i].start > max_start)) {
  1638. chapters[i].chapter =
  1639. avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1640. chapters[i].start, chapters[i].end,
  1641. chapters[i].title);
  1642. av_dict_set(&chapters[i].chapter->metadata,
  1643. "title", chapters[i].title, 0);
  1644. max_start = chapters[i].start;
  1645. }
  1646. matroska_add_index_entries(matroska);
  1647. matroska_convert_tags(s);
  1648. return 0;
  1649. }
  1650. /*
  1651. * Put one packet in an application-supplied AVPacket struct.
  1652. * Returns 0 on success or -1 on failure.
  1653. */
  1654. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1655. AVPacket *pkt)
  1656. {
  1657. if (matroska->num_packets > 0) {
  1658. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1659. av_free(matroska->packets[0]);
  1660. if (matroska->num_packets > 1) {
  1661. void *newpackets;
  1662. memmove(&matroska->packets[0], &matroska->packets[1],
  1663. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1664. newpackets = av_realloc(matroska->packets,
  1665. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1666. if (newpackets)
  1667. matroska->packets = newpackets;
  1668. } else {
  1669. av_freep(&matroska->packets);
  1670. matroska->prev_pkt = NULL;
  1671. }
  1672. matroska->num_packets--;
  1673. return 0;
  1674. }
  1675. return -1;
  1676. }
  1677. /*
  1678. * Free all packets in our internal queue.
  1679. */
  1680. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1681. {
  1682. if (matroska->packets) {
  1683. int n;
  1684. for (n = 0; n < matroska->num_packets; n++) {
  1685. av_free_packet(matroska->packets[n]);
  1686. av_free(matroska->packets[n]);
  1687. }
  1688. av_freep(&matroska->packets);
  1689. matroska->num_packets = 0;
  1690. }
  1691. }
  1692. static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
  1693. int size, int type,
  1694. uint32_t **lace_buf, int *laces)
  1695. {
  1696. int res = 0, n;
  1697. uint8_t *data = *buf;
  1698. uint32_t *lace_size;
  1699. if (!type) {
  1700. *laces = 1;
  1701. *lace_buf = av_mallocz(sizeof(int));
  1702. if (!*lace_buf)
  1703. return AVERROR(ENOMEM);
  1704. *lace_buf[0] = size;
  1705. return 0;
  1706. }
  1707. av_assert0(size > 0);
  1708. *laces = *data + 1;
  1709. data += 1;
  1710. size -= 1;
  1711. lace_size = av_mallocz(*laces * sizeof(int));
  1712. if (!lace_size)
  1713. return AVERROR(ENOMEM);
  1714. switch (type) {
  1715. case 0x1: /* Xiph lacing */ {
  1716. uint8_t temp;
  1717. uint32_t total = 0;
  1718. for (n = 0; res == 0 && n < *laces - 1; n++) {
  1719. while (1) {
  1720. if (size == 0) {
  1721. res = AVERROR_EOF;
  1722. break;
  1723. }
  1724. temp = *data;
  1725. lace_size[n] += temp;
  1726. data += 1;
  1727. size -= 1;
  1728. if (temp != 0xff)
  1729. break;
  1730. }
  1731. total += lace_size[n];
  1732. }
  1733. if (size <= total) {
  1734. res = AVERROR_INVALIDDATA;
  1735. break;
  1736. }
  1737. lace_size[n] = size - total;
  1738. break;
  1739. }
  1740. case 0x2: /* fixed-size lacing */
  1741. if (size % (*laces)) {
  1742. res = AVERROR_INVALIDDATA;
  1743. break;
  1744. }
  1745. for (n = 0; n < *laces; n++)
  1746. lace_size[n] = size / *laces;
  1747. break;
  1748. case 0x3: /* EBML lacing */ {
  1749. uint64_t num;
  1750. uint32_t total;
  1751. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1752. if (n < 0) {
  1753. av_log(matroska->ctx, AV_LOG_INFO,
  1754. "EBML block data error\n");
  1755. res = n;
  1756. break;
  1757. }
  1758. data += n;
  1759. size -= n;
  1760. total = lace_size[0] = num;
  1761. for (n = 1; res == 0 && n < *laces - 1; n++) {
  1762. int64_t snum;
  1763. int r;
  1764. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1765. if (r < 0) {
  1766. av_log(matroska->ctx, AV_LOG_INFO,
  1767. "EBML block data error\n");
  1768. res = r;
  1769. break;
  1770. }
  1771. data += r;
  1772. size -= r;
  1773. lace_size[n] = lace_size[n - 1] + snum;
  1774. total += lace_size[n];
  1775. }
  1776. if (size <= total) {
  1777. res = AVERROR_INVALIDDATA;
  1778. break;
  1779. }
  1780. lace_size[*laces - 1] = size - total;
  1781. break;
  1782. }
  1783. }
  1784. *buf = data;
  1785. *lace_buf = lace_size;
  1786. return res;
  1787. }
  1788. static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
  1789. MatroskaTrack *track,
  1790. AVStream *st,
  1791. uint8_t *data, int size,
  1792. uint64_t timecode,
  1793. int64_t pos)
  1794. {
  1795. int a = st->codec->block_align;
  1796. int sps = track->audio.sub_packet_size;
  1797. int cfs = track->audio.coded_framesize;
  1798. int h = track->audio.sub_packet_h;
  1799. int y = track->audio.sub_packet_cnt;
  1800. int w = track->audio.frame_size;
  1801. int x;
  1802. if (!track->audio.pkt_cnt) {
  1803. if (track->audio.sub_packet_cnt == 0)
  1804. track->audio.buf_timecode = timecode;
  1805. if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
  1806. if (size < cfs * h / 2) {
  1807. av_log(matroska->ctx, AV_LOG_ERROR,
  1808. "Corrupt int4 RM-style audio packet size\n");
  1809. return AVERROR_INVALIDDATA;
  1810. }
  1811. for (x=0; x<h/2; x++)
  1812. memcpy(track->audio.buf+x*2*w+y*cfs,
  1813. data+x*cfs, cfs);
  1814. } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
  1815. if (size < w) {
  1816. av_log(matroska->ctx, AV_LOG_ERROR,
  1817. "Corrupt sipr RM-style audio packet size\n");
  1818. return AVERROR_INVALIDDATA;
  1819. }
  1820. memcpy(track->audio.buf + y*w, data, w);
  1821. } else {
  1822. if (size < sps * w / sps || h<=0) {
  1823. av_log(matroska->ctx, AV_LOG_ERROR,
  1824. "Corrupt generic RM-style audio packet size\n");
  1825. return AVERROR_INVALIDDATA;
  1826. }
  1827. for (x=0; x<w/sps; x++)
  1828. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1829. }
  1830. if (++track->audio.sub_packet_cnt >= h) {
  1831. if (st->codec->codec_id == AV_CODEC_ID_SIPR)
  1832. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1833. track->audio.sub_packet_cnt = 0;
  1834. track->audio.pkt_cnt = h*w / a;
  1835. }
  1836. }
  1837. while (track->audio.pkt_cnt) {
  1838. AVPacket *pkt = NULL;
  1839. if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
  1840. av_free(pkt);
  1841. return AVERROR(ENOMEM);
  1842. }
  1843. memcpy(pkt->data, track->audio.buf
  1844. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1845. pkt->pts = track->audio.buf_timecode;
  1846. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1847. pkt->pos = pos;
  1848. pkt->stream_index = st->index;
  1849. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1850. }
  1851. return 0;
  1852. }
  1853. static int matroska_parse_frame(MatroskaDemuxContext *matroska,
  1854. MatroskaTrack *track,
  1855. AVStream *st,
  1856. uint8_t *data, int pkt_size,
  1857. uint64_t timecode, uint64_t lace_duration,
  1858. int64_t pos, int is_keyframe)
  1859. {
  1860. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1861. uint8_t *pkt_data = data;
  1862. int offset = 0, res;
  1863. AVPacket *pkt;
  1864. if (encodings && encodings->scope & 1) {
  1865. res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
  1866. if (res < 0)
  1867. return res;
  1868. }
  1869. if (st->codec->codec_id == AV_CODEC_ID_PRORES)
  1870. offset = 8;
  1871. pkt = av_mallocz(sizeof(AVPacket));
  1872. /* XXX: prevent data copy... */
  1873. if (av_new_packet(pkt, pkt_size + offset) < 0) {
  1874. av_free(pkt);
  1875. return AVERROR(ENOMEM);
  1876. }
  1877. if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
  1878. uint8_t *buf = pkt->data;
  1879. bytestream_put_be32(&buf, pkt_size);
  1880. bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
  1881. }
  1882. memcpy(pkt->data + offset, pkt_data, pkt_size);
  1883. if (pkt_data != data)
  1884. av_free(pkt_data);
  1885. pkt->flags = is_keyframe;
  1886. pkt->stream_index = st->index;
  1887. if (track->ms_compat)
  1888. pkt->dts = timecode;
  1889. else
  1890. pkt->pts = timecode;
  1891. pkt->pos = pos;
  1892. if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
  1893. /*
  1894. * For backward compatibility.
  1895. * Historically, we have put subtitle duration
  1896. * in convergence_duration, on the off chance
  1897. * that the time_scale is less than 1us, which
  1898. * could result in a 32bit overflow on the
  1899. * normal duration field.
  1900. */
  1901. pkt->convergence_duration = lace_duration;
  1902. }
  1903. if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
  1904. lace_duration <= INT_MAX) {
  1905. /*
  1906. * For non subtitle tracks, just store the duration
  1907. * as normal.
  1908. *
  1909. * If it's a subtitle track and duration value does
  1910. * not overflow a uint32, then also store it normally.
  1911. */
  1912. pkt->duration = lace_duration;
  1913. }
  1914. if (st->codec->codec_id == AV_CODEC_ID_SSA)
  1915. matroska_fix_ass_packet(matroska, pkt, lace_duration);
  1916. if (matroska->prev_pkt &&
  1917. timecode != AV_NOPTS_VALUE &&
  1918. matroska->prev_pkt->pts == timecode &&
  1919. matroska->prev_pkt->stream_index == st->index &&
  1920. st->codec->codec_id == AV_CODEC_ID_SSA)
  1921. matroska_merge_packets(matroska->prev_pkt, pkt);
  1922. else {
  1923. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1924. matroska->prev_pkt = pkt;
  1925. }
  1926. return 0;
  1927. }
  1928. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1929. int size, int64_t pos, uint64_t cluster_time,
  1930. uint64_t block_duration, int is_keyframe,
  1931. int64_t cluster_pos)
  1932. {
  1933. uint64_t timecode = AV_NOPTS_VALUE;
  1934. MatroskaTrack *track;
  1935. int res = 0;
  1936. AVStream *st;
  1937. int16_t block_time;
  1938. uint32_t *lace_size = NULL;
  1939. int n, flags, laces = 0;
  1940. uint64_t num;
  1941. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1942. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1943. return n;
  1944. }
  1945. data += n;
  1946. size -= n;
  1947. track = matroska_find_track_by_num(matroska, num);
  1948. if (!track || !track->stream) {
  1949. av_log(matroska->ctx, AV_LOG_INFO,
  1950. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1951. return AVERROR_INVALIDDATA;
  1952. } else if (size <= 3)
  1953. return 0;
  1954. st = track->stream;
  1955. if (st->discard >= AVDISCARD_ALL)
  1956. return res;
  1957. av_assert1(block_duration != AV_NOPTS_VALUE);
  1958. block_time = AV_RB16(data);
  1959. data += 2;
  1960. flags = *data++;
  1961. size -= 3;
  1962. if (is_keyframe == -1)
  1963. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1964. if (cluster_time != (uint64_t)-1
  1965. && (block_time >= 0 || cluster_time >= -block_time)) {
  1966. timecode = cluster_time + block_time;
  1967. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1968. && timecode < track->end_timecode)
  1969. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1970. if (is_keyframe)
  1971. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1972. }
  1973. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1974. if (timecode < matroska->skip_to_timecode)
  1975. return res;
  1976. if (!st->skip_to_keyframe) {
  1977. av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
  1978. matroska->skip_to_keyframe = 0;
  1979. }
  1980. if (is_keyframe)
  1981. matroska->skip_to_keyframe = 0;
  1982. }
  1983. res = matroska_parse_laces(matroska, &data, size, (flags & 0x06) >> 1,
  1984. &lace_size, &laces);
  1985. if (res)
  1986. goto end;
  1987. if (!block_duration)
  1988. block_duration = track->default_duration * laces / matroska->time_scale;
  1989. if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
  1990. track->end_timecode =
  1991. FFMAX(track->end_timecode, timecode + block_duration);
  1992. for (n = 0; n < laces; n++) {
  1993. int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
  1994. if (lace_size[n] > size) {
  1995. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  1996. break;
  1997. }
  1998. if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
  1999. st->codec->codec_id == AV_CODEC_ID_COOK ||
  2000. st->codec->codec_id == AV_CODEC_ID_SIPR ||
  2001. st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
  2002. st->codec->block_align && track->audio.sub_packet_size) {
  2003. res = matroska_parse_rm_audio(matroska, track, st, data, size,
  2004. timecode, pos);
  2005. if (res)
  2006. goto end;
  2007. } else {
  2008. res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
  2009. timecode, lace_duration,
  2010. pos, !n? is_keyframe : 0);
  2011. if (res)
  2012. goto end;
  2013. }
  2014. if (timecode != AV_NOPTS_VALUE)
  2015. timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
  2016. data += lace_size[n];
  2017. size -= lace_size[n];
  2018. }
  2019. end:
  2020. av_free(lace_size);
  2021. return res;
  2022. }
  2023. static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
  2024. {
  2025. EbmlList *blocks_list;
  2026. MatroskaBlock *blocks;
  2027. int i, res;
  2028. res = ebml_parse(matroska,
  2029. matroska_cluster_incremental_parsing,
  2030. &matroska->current_cluster);
  2031. if (res == 1) {
  2032. /* New Cluster */
  2033. if (matroska->current_cluster_pos)
  2034. ebml_level_end(matroska);
  2035. ebml_free(matroska_cluster, &matroska->current_cluster);
  2036. memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
  2037. matroska->current_cluster_num_blocks = 0;
  2038. matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
  2039. matroska->prev_pkt = NULL;
  2040. /* sizeof the ID which was already read */
  2041. if (matroska->current_id)
  2042. matroska->current_cluster_pos -= 4;
  2043. res = ebml_parse(matroska,
  2044. matroska_clusters_incremental,
  2045. &matroska->current_cluster);
  2046. /* Try parsing the block again. */
  2047. if (res == 1)
  2048. res = ebml_parse(matroska,
  2049. matroska_cluster_incremental_parsing,
  2050. &matroska->current_cluster);
  2051. }
  2052. if (!res &&
  2053. matroska->current_cluster_num_blocks <
  2054. matroska->current_cluster.blocks.nb_elem) {
  2055. blocks_list = &matroska->current_cluster.blocks;
  2056. blocks = blocks_list->elem;
  2057. matroska->current_cluster_num_blocks = blocks_list->nb_elem;
  2058. i = blocks_list->nb_elem - 1;
  2059. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2060. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2061. if (!blocks[i].non_simple)
  2062. blocks[i].duration = 0;
  2063. res = matroska_parse_block(matroska,
  2064. blocks[i].bin.data, blocks[i].bin.size,
  2065. blocks[i].bin.pos,
  2066. matroska->current_cluster.timecode,
  2067. blocks[i].duration, is_keyframe,
  2068. matroska->current_cluster_pos);
  2069. }
  2070. }
  2071. if (res < 0) matroska->done = 1;
  2072. return res;
  2073. }
  2074. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  2075. {
  2076. MatroskaCluster cluster = { 0 };
  2077. EbmlList *blocks_list;
  2078. MatroskaBlock *blocks;
  2079. int i, res;
  2080. int64_t pos;
  2081. if (!matroska->contains_ssa)
  2082. return matroska_parse_cluster_incremental(matroska);
  2083. pos = avio_tell(matroska->ctx->pb);
  2084. matroska->prev_pkt = NULL;
  2085. if (matroska->current_id)
  2086. pos -= 4; /* sizeof the ID which was already read */
  2087. res = ebml_parse(matroska, matroska_clusters, &cluster);
  2088. blocks_list = &cluster.blocks;
  2089. blocks = blocks_list->elem;
  2090. for (i=0; i<blocks_list->nb_elem; i++)
  2091. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  2092. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  2093. res=matroska_parse_block(matroska,
  2094. blocks[i].bin.data, blocks[i].bin.size,
  2095. blocks[i].bin.pos, cluster.timecode,
  2096. blocks[i].duration, is_keyframe,
  2097. pos);
  2098. }
  2099. ebml_free(matroska_cluster, &cluster);
  2100. return res;
  2101. }
  2102. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  2103. {
  2104. MatroskaDemuxContext *matroska = s->priv_data;
  2105. while (matroska_deliver_packet(matroska, pkt)) {
  2106. int64_t pos = avio_tell(matroska->ctx->pb);
  2107. if (matroska->done)
  2108. return AVERROR_EOF;
  2109. if (matroska_parse_cluster(matroska) < 0)
  2110. matroska_resync(matroska, pos);
  2111. }
  2112. return 0;
  2113. }
  2114. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  2115. int64_t timestamp, int flags)
  2116. {
  2117. MatroskaDemuxContext *matroska = s->priv_data;
  2118. MatroskaTrack *tracks = matroska->tracks.elem;
  2119. AVStream *st = s->streams[stream_index];
  2120. int i, index, index_sub, index_min;
  2121. /* Parse the CUES now since we need the index data to seek. */
  2122. if (matroska->cues_parsing_deferred > 0) {
  2123. matroska->cues_parsing_deferred = 0;
  2124. matroska_parse_cues(matroska);
  2125. }
  2126. if (!st->nb_index_entries)
  2127. goto err;
  2128. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  2129. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2130. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  2131. matroska->current_id = 0;
  2132. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  2133. matroska->prev_pkt = NULL;
  2134. matroska_clear_queue(matroska);
  2135. if (matroska_parse_cluster(matroska) < 0)
  2136. break;
  2137. }
  2138. }
  2139. matroska_clear_queue(matroska);
  2140. if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
  2141. goto err;
  2142. index_min = index;
  2143. for (i=0; i < matroska->tracks.nb_elem; i++) {
  2144. tracks[i].audio.pkt_cnt = 0;
  2145. tracks[i].audio.sub_packet_cnt = 0;
  2146. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  2147. tracks[i].end_timecode = 0;
  2148. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  2149. && tracks[i].stream->discard != AVDISCARD_ALL) {
  2150. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  2151. if (index_sub >= 0
  2152. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  2153. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  2154. index_min = index_sub;
  2155. }
  2156. }
  2157. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  2158. matroska->current_id = 0;
  2159. st->skip_to_keyframe =
  2160. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  2161. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  2162. matroska->done = 0;
  2163. matroska->num_levels = 0;
  2164. ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
  2165. return 0;
  2166. err:
  2167. // slightly hackish but allows proper fallback to
  2168. // the generic seeking code.
  2169. matroska_clear_queue(matroska);
  2170. matroska->current_id = 0;
  2171. st->skip_to_keyframe =
  2172. matroska->skip_to_keyframe = 0;
  2173. matroska->done = 0;
  2174. matroska->num_levels = 0;
  2175. return -1;
  2176. }
  2177. static int matroska_read_close(AVFormatContext *s)
  2178. {
  2179. MatroskaDemuxContext *matroska = s->priv_data;
  2180. MatroskaTrack *tracks = matroska->tracks.elem;
  2181. int n;
  2182. matroska_clear_queue(matroska);
  2183. for (n=0; n < matroska->tracks.nb_elem; n++)
  2184. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  2185. av_free(tracks[n].audio.buf);
  2186. ebml_free(matroska_cluster, &matroska->current_cluster);
  2187. ebml_free(matroska_segment, matroska);
  2188. return 0;
  2189. }
  2190. AVInputFormat ff_matroska_demuxer = {
  2191. .name = "matroska,webm",
  2192. .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
  2193. .priv_data_size = sizeof(MatroskaDemuxContext),
  2194. .read_probe = matroska_probe,
  2195. .read_header = matroska_read_header,
  2196. .read_packet = matroska_read_packet,
  2197. .read_close = matroska_read_close,
  2198. .read_seek = matroska_read_seek,
  2199. };