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.

2511 lines
88KB

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