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.

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