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.

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