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.

2336 lines
85KB

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