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.

2450 lines
85KB

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