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.

1915 lines
68KB

  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. * by Ronald Bultje <rbultje@ronald.bitfreak.net>
  25. * with a little help from Moritz Bunkus <moritz@bunkus.org>
  26. * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
  27. * 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. /* For ff_codec_get_id(). */
  33. #include "riff.h"
  34. #include "isom.h"
  35. #include "rm.h"
  36. #include "matroska.h"
  37. #include "libavcodec/mpeg4audio.h"
  38. #include "libavutil/intfloat_readwrite.h"
  39. #include "libavutil/intreadwrite.h"
  40. #include "libavutil/avstring.h"
  41. #include "libavutil/lzo.h"
  42. #if CONFIG_ZLIB
  43. #include <zlib.h>
  44. #endif
  45. #if CONFIG_BZLIB
  46. #include <bzlib.h>
  47. #endif
  48. typedef enum {
  49. EBML_NONE,
  50. EBML_UINT,
  51. EBML_FLOAT,
  52. EBML_STR,
  53. EBML_UTF8,
  54. EBML_BIN,
  55. EBML_NEST,
  56. EBML_PASS,
  57. EBML_STOP,
  58. } EbmlType;
  59. typedef const struct EbmlSyntax {
  60. uint32_t id;
  61. EbmlType type;
  62. int list_elem_size;
  63. int data_offset;
  64. union {
  65. uint64_t u;
  66. double f;
  67. const char *s;
  68. const struct EbmlSyntax *n;
  69. } def;
  70. } EbmlSyntax;
  71. typedef struct {
  72. int nb_elem;
  73. void *elem;
  74. } EbmlList;
  75. typedef struct {
  76. int size;
  77. uint8_t *data;
  78. int64_t pos;
  79. } EbmlBin;
  80. typedef struct {
  81. uint64_t version;
  82. uint64_t max_size;
  83. uint64_t id_length;
  84. char *doctype;
  85. uint64_t doctype_version;
  86. } Ebml;
  87. typedef struct {
  88. uint64_t algo;
  89. EbmlBin settings;
  90. } MatroskaTrackCompression;
  91. typedef struct {
  92. uint64_t scope;
  93. uint64_t type;
  94. MatroskaTrackCompression compression;
  95. } MatroskaTrackEncoding;
  96. typedef struct {
  97. double frame_rate;
  98. uint64_t display_width;
  99. uint64_t display_height;
  100. uint64_t pixel_width;
  101. uint64_t pixel_height;
  102. uint64_t fourcc;
  103. } MatroskaTrackVideo;
  104. typedef struct {
  105. double samplerate;
  106. double out_samplerate;
  107. uint64_t bitdepth;
  108. uint64_t channels;
  109. /* real audio header (extracted from extradata) */
  110. int coded_framesize;
  111. int sub_packet_h;
  112. int frame_size;
  113. int sub_packet_size;
  114. int sub_packet_cnt;
  115. int pkt_cnt;
  116. uint8_t *buf;
  117. } MatroskaTrackAudio;
  118. typedef struct {
  119. uint64_t num;
  120. uint64_t uid;
  121. uint64_t type;
  122. char *name;
  123. char *codec_id;
  124. EbmlBin codec_priv;
  125. char *language;
  126. double time_scale;
  127. uint64_t default_duration;
  128. uint64_t flag_default;
  129. uint64_t flag_forced;
  130. MatroskaTrackVideo video;
  131. MatroskaTrackAudio audio;
  132. EbmlList encodings;
  133. AVStream *stream;
  134. int64_t end_timecode;
  135. int ms_compat;
  136. } MatroskaTrack;
  137. typedef struct {
  138. uint64_t uid;
  139. char *filename;
  140. char *mime;
  141. EbmlBin bin;
  142. AVStream *stream;
  143. } MatroskaAttachement;
  144. typedef struct {
  145. uint64_t start;
  146. uint64_t end;
  147. uint64_t uid;
  148. char *title;
  149. AVChapter *chapter;
  150. } MatroskaChapter;
  151. typedef struct {
  152. uint64_t track;
  153. uint64_t pos;
  154. } MatroskaIndexPos;
  155. typedef struct {
  156. uint64_t time;
  157. EbmlList pos;
  158. } MatroskaIndex;
  159. typedef struct {
  160. char *name;
  161. char *string;
  162. char *lang;
  163. uint64_t def;
  164. EbmlList sub;
  165. } MatroskaTag;
  166. typedef struct {
  167. char *type;
  168. uint64_t typevalue;
  169. uint64_t trackuid;
  170. uint64_t chapteruid;
  171. uint64_t attachuid;
  172. } MatroskaTagTarget;
  173. typedef struct {
  174. MatroskaTagTarget target;
  175. EbmlList tag;
  176. } MatroskaTags;
  177. typedef struct {
  178. uint64_t id;
  179. uint64_t pos;
  180. } MatroskaSeekhead;
  181. typedef struct {
  182. uint64_t start;
  183. uint64_t length;
  184. } MatroskaLevel;
  185. typedef struct {
  186. AVFormatContext *ctx;
  187. /* EBML stuff */
  188. int num_levels;
  189. MatroskaLevel levels[EBML_MAX_DEPTH];
  190. int level_up;
  191. uint32_t current_id;
  192. uint64_t time_scale;
  193. double duration;
  194. char *title;
  195. EbmlList tracks;
  196. EbmlList attachments;
  197. EbmlList chapters;
  198. EbmlList index;
  199. EbmlList tags;
  200. EbmlList seekhead;
  201. /* byte position of the segment inside the stream */
  202. int64_t segment_start;
  203. /* the packet queue */
  204. AVPacket **packets;
  205. int num_packets;
  206. AVPacket *prev_pkt;
  207. int done;
  208. /* What to skip before effectively reading a packet. */
  209. int skip_to_keyframe;
  210. uint64_t skip_to_timecode;
  211. } MatroskaDemuxContext;
  212. typedef struct {
  213. uint64_t duration;
  214. int64_t reference;
  215. uint64_t non_simple;
  216. EbmlBin bin;
  217. } MatroskaBlock;
  218. typedef struct {
  219. uint64_t timecode;
  220. EbmlList blocks;
  221. } MatroskaCluster;
  222. static EbmlSyntax ebml_header[] = {
  223. { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
  224. { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
  225. { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
  226. { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
  227. { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
  228. { EBML_ID_EBMLVERSION, EBML_NONE },
  229. { EBML_ID_DOCTYPEVERSION, EBML_NONE },
  230. { 0 }
  231. };
  232. static EbmlSyntax ebml_syntax[] = {
  233. { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
  234. { 0 }
  235. };
  236. static EbmlSyntax matroska_info[] = {
  237. { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
  238. { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
  239. { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
  240. { MATROSKA_ID_WRITINGAPP, EBML_NONE },
  241. { MATROSKA_ID_MUXINGAPP, EBML_NONE },
  242. { MATROSKA_ID_DATEUTC, EBML_NONE },
  243. { MATROSKA_ID_SEGMENTUID, EBML_NONE },
  244. { 0 }
  245. };
  246. static EbmlSyntax matroska_track_video[] = {
  247. { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
  248. { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
  249. { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
  250. { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
  251. { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
  252. { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
  253. { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
  254. { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
  255. { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
  256. { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
  257. { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
  258. { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
  259. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
  260. { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
  261. { 0 }
  262. };
  263. static EbmlSyntax matroska_track_audio[] = {
  264. { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
  265. { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
  266. { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
  267. { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
  268. { 0 }
  269. };
  270. static EbmlSyntax matroska_track_encoding_compression[] = {
  271. { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
  272. { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
  273. { 0 }
  274. };
  275. static EbmlSyntax matroska_track_encoding[] = {
  276. { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
  277. { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
  278. { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
  279. { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
  280. { 0 }
  281. };
  282. static EbmlSyntax matroska_track_encodings[] = {
  283. { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
  284. { 0 }
  285. };
  286. static EbmlSyntax matroska_track[] = {
  287. { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
  288. { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
  289. { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
  290. { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
  291. { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
  292. { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
  293. { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
  294. { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
  295. { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
  296. { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
  297. { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
  298. { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
  299. { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
  300. { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
  301. { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
  302. { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
  303. { MATROSKA_ID_CODECNAME, EBML_NONE },
  304. { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
  305. { MATROSKA_ID_CODECINFOURL, EBML_NONE },
  306. { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
  307. { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
  308. { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
  309. { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
  310. { 0 }
  311. };
  312. static EbmlSyntax matroska_tracks[] = {
  313. { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
  314. { 0 }
  315. };
  316. static EbmlSyntax matroska_attachment[] = {
  317. { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
  318. { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
  319. { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
  320. { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
  321. { MATROSKA_ID_FILEDESC, EBML_NONE },
  322. { 0 }
  323. };
  324. static EbmlSyntax matroska_attachments[] = {
  325. { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
  326. { 0 }
  327. };
  328. static EbmlSyntax matroska_chapter_display[] = {
  329. { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
  330. { MATROSKA_ID_CHAPLANG, EBML_NONE },
  331. { 0 }
  332. };
  333. static EbmlSyntax matroska_chapter_entry[] = {
  334. { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
  335. { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
  336. { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
  337. { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
  338. { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
  339. { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
  340. { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
  341. { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
  342. { 0 }
  343. };
  344. static EbmlSyntax matroska_chapter[] = {
  345. { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
  346. { MATROSKA_ID_EDITIONUID, EBML_NONE },
  347. { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
  348. { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
  349. { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
  350. { 0 }
  351. };
  352. static EbmlSyntax matroska_chapters[] = {
  353. { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
  354. { 0 }
  355. };
  356. static EbmlSyntax matroska_index_pos[] = {
  357. { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
  358. { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
  359. { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
  360. { 0 }
  361. };
  362. static EbmlSyntax matroska_index_entry[] = {
  363. { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
  364. { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
  365. { 0 }
  366. };
  367. static EbmlSyntax matroska_index[] = {
  368. { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
  369. { 0 }
  370. };
  371. static EbmlSyntax matroska_simpletag[] = {
  372. { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
  373. { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
  374. { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
  375. { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  376. { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
  377. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
  378. { 0 }
  379. };
  380. static EbmlSyntax matroska_tagtargets[] = {
  381. { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
  382. { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
  383. { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
  384. { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
  385. { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
  386. { 0 }
  387. };
  388. static EbmlSyntax matroska_tag[] = {
  389. { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
  390. { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
  391. { 0 }
  392. };
  393. static EbmlSyntax matroska_tags[] = {
  394. { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
  395. { 0 }
  396. };
  397. static EbmlSyntax matroska_seekhead_entry[] = {
  398. { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
  399. { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
  400. { 0 }
  401. };
  402. static EbmlSyntax matroska_seekhead[] = {
  403. { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
  404. { 0 }
  405. };
  406. static EbmlSyntax matroska_segment[] = {
  407. { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
  408. { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
  409. { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
  410. { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
  411. { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
  412. { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
  413. { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
  414. { MATROSKA_ID_CLUSTER, EBML_STOP },
  415. { 0 }
  416. };
  417. static EbmlSyntax matroska_segments[] = {
  418. { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
  419. { 0 }
  420. };
  421. static EbmlSyntax matroska_blockgroup[] = {
  422. { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  423. { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
  424. { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
  425. { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
  426. { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
  427. { 0 }
  428. };
  429. static EbmlSyntax matroska_cluster[] = {
  430. { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
  431. { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  432. { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
  433. { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
  434. { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
  435. { 0 }
  436. };
  437. static EbmlSyntax matroska_clusters[] = {
  438. { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
  439. { MATROSKA_ID_INFO, EBML_NONE },
  440. { MATROSKA_ID_CUES, EBML_NONE },
  441. { MATROSKA_ID_TAGS, EBML_NONE },
  442. { MATROSKA_ID_SEEKHEAD, EBML_NONE },
  443. { 0 }
  444. };
  445. static const char *matroska_doctypes[] = { "matroska", "webm" };
  446. /*
  447. * Return: Whether we reached the end of a level in the hierarchy or not.
  448. */
  449. static int ebml_level_end(MatroskaDemuxContext *matroska)
  450. {
  451. ByteIOContext *pb = matroska->ctx->pb;
  452. int64_t pos = url_ftell(pb);
  453. if (matroska->num_levels > 0) {
  454. MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
  455. if (pos - level->start >= level->length || matroska->current_id) {
  456. matroska->num_levels--;
  457. return 1;
  458. }
  459. }
  460. return 0;
  461. }
  462. /*
  463. * Read: an "EBML number", which is defined as a variable-length
  464. * array of bytes. The first byte indicates the length by giving a
  465. * number of 0-bits followed by a one. The position of the first
  466. * "one" bit inside the first byte indicates the length of this
  467. * number.
  468. * Returns: number of bytes read, < 0 on error
  469. */
  470. static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
  471. int max_size, uint64_t *number)
  472. {
  473. int len_mask = 0x80, read = 1, n = 1;
  474. int64_t total = 0;
  475. /* The first byte tells us the length in bytes - get_byte() can normally
  476. * return 0, but since that's not a valid first ebmlID byte, we can
  477. * use it safely here to catch EOS. */
  478. if (!(total = get_byte(pb))) {
  479. /* we might encounter EOS here */
  480. if (!url_feof(pb)) {
  481. int64_t pos = url_ftell(pb);
  482. av_log(matroska->ctx, AV_LOG_ERROR,
  483. "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
  484. pos, pos);
  485. }
  486. return AVERROR(EIO); /* EOS or actual I/O error */
  487. }
  488. /* get the length of the EBML number */
  489. while (read <= max_size && !(total & len_mask)) {
  490. read++;
  491. len_mask >>= 1;
  492. }
  493. if (read > max_size) {
  494. int64_t pos = url_ftell(pb) - 1;
  495. av_log(matroska->ctx, AV_LOG_ERROR,
  496. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  497. (uint8_t) total, pos, pos);
  498. return AVERROR_INVALIDDATA;
  499. }
  500. /* read out length */
  501. total &= ~len_mask;
  502. while (n++ < read)
  503. total = (total << 8) | get_byte(pb);
  504. *number = total;
  505. return read;
  506. }
  507. /*
  508. * Read the next element as an unsigned int.
  509. * 0 is success, < 0 is failure.
  510. */
  511. static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
  512. {
  513. int n = 0;
  514. if (size < 1 || size > 8)
  515. return AVERROR_INVALIDDATA;
  516. /* big-endian ordering; build up number */
  517. *num = 0;
  518. while (n++ < size)
  519. *num = (*num << 8) | get_byte(pb);
  520. return 0;
  521. }
  522. /*
  523. * Read the next element as a float.
  524. * 0 is success, < 0 is failure.
  525. */
  526. static int ebml_read_float(ByteIOContext *pb, int size, double *num)
  527. {
  528. if (size == 4) {
  529. *num= av_int2flt(get_be32(pb));
  530. } else if(size==8){
  531. *num= av_int2dbl(get_be64(pb));
  532. } else
  533. return AVERROR_INVALIDDATA;
  534. return 0;
  535. }
  536. /*
  537. * Read the next element as an ASCII string.
  538. * 0 is success, < 0 is failure.
  539. */
  540. static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
  541. {
  542. av_free(*str);
  543. /* EBML strings are usually not 0-terminated, so we allocate one
  544. * byte more, read the string and NULL-terminate it ourselves. */
  545. if (!(*str = av_malloc(size + 1)))
  546. return AVERROR(ENOMEM);
  547. if (get_buffer(pb, (uint8_t *) *str, size) != size) {
  548. av_freep(str);
  549. return AVERROR(EIO);
  550. }
  551. (*str)[size] = '\0';
  552. return 0;
  553. }
  554. /*
  555. * Read the next element as binary data.
  556. * 0 is success, < 0 is failure.
  557. */
  558. static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
  559. {
  560. av_free(bin->data);
  561. if (!(bin->data = av_malloc(length)))
  562. return AVERROR(ENOMEM);
  563. bin->size = length;
  564. bin->pos = url_ftell(pb);
  565. if (get_buffer(pb, bin->data, length) != length) {
  566. av_freep(&bin->data);
  567. return AVERROR(EIO);
  568. }
  569. return 0;
  570. }
  571. /*
  572. * Read the next element, but only the header. The contents
  573. * are supposed to be sub-elements which can be read separately.
  574. * 0 is success, < 0 is failure.
  575. */
  576. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  577. {
  578. ByteIOContext *pb = matroska->ctx->pb;
  579. MatroskaLevel *level;
  580. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  581. av_log(matroska->ctx, AV_LOG_ERROR,
  582. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  583. return AVERROR(ENOSYS);
  584. }
  585. level = &matroska->levels[matroska->num_levels++];
  586. level->start = url_ftell(pb);
  587. level->length = length;
  588. return 0;
  589. }
  590. /*
  591. * Read signed/unsigned "EBML" numbers.
  592. * Return: number of bytes processed, < 0 on error
  593. */
  594. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  595. uint8_t *data, uint32_t size, uint64_t *num)
  596. {
  597. ByteIOContext pb;
  598. init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  599. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  600. }
  601. /*
  602. * Same as above, but signed.
  603. */
  604. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  605. uint8_t *data, uint32_t size, int64_t *num)
  606. {
  607. uint64_t unum;
  608. int res;
  609. /* read as unsigned number first */
  610. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  611. return res;
  612. /* make signed (weird way) */
  613. *num = unum - ((1LL << (7*res - 1)) - 1);
  614. return res;
  615. }
  616. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  617. EbmlSyntax *syntax, void *data);
  618. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  619. uint32_t id, void *data)
  620. {
  621. int i;
  622. for (i=0; syntax[i].id; i++)
  623. if (id == syntax[i].id)
  624. break;
  625. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  626. matroska->num_levels > 0 &&
  627. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  628. return 0; // we reached the end of an unknown size cluster
  629. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
  630. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  631. return ebml_parse_elem(matroska, &syntax[i], data);
  632. }
  633. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  634. void *data)
  635. {
  636. if (!matroska->current_id) {
  637. uint64_t id;
  638. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  639. if (res < 0)
  640. return res;
  641. matroska->current_id = id | 1 << 7*res;
  642. }
  643. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  644. }
  645. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  646. void *data)
  647. {
  648. int i, res = 0;
  649. for (i=0; syntax[i].id; i++)
  650. switch (syntax[i].type) {
  651. case EBML_UINT:
  652. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  653. break;
  654. case EBML_FLOAT:
  655. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  656. break;
  657. case EBML_STR:
  658. case EBML_UTF8:
  659. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  660. break;
  661. }
  662. while (!res && !ebml_level_end(matroska))
  663. res = ebml_parse(matroska, syntax, data);
  664. return res;
  665. }
  666. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  667. EbmlSyntax *syntax, void *data)
  668. {
  669. ByteIOContext *pb = matroska->ctx->pb;
  670. uint32_t id = syntax->id;
  671. uint64_t length;
  672. int res;
  673. data = (char *)data + syntax->data_offset;
  674. if (syntax->list_elem_size) {
  675. EbmlList *list = data;
  676. list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  677. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  678. memset(data, 0, syntax->list_elem_size);
  679. list->nb_elem++;
  680. }
  681. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  682. matroska->current_id = 0;
  683. if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
  684. return res;
  685. }
  686. switch (syntax->type) {
  687. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  688. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  689. case EBML_STR:
  690. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  691. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  692. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  693. return res;
  694. if (id == MATROSKA_ID_SEGMENT)
  695. matroska->segment_start = url_ftell(matroska->ctx->pb);
  696. return ebml_parse_nest(matroska, syntax->def.n, data);
  697. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  698. case EBML_STOP: return 1;
  699. default: return url_fseek(pb,length,SEEK_CUR)<0 ? AVERROR(EIO) : 0;
  700. }
  701. if (res == AVERROR_INVALIDDATA)
  702. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  703. else if (res == AVERROR(EIO))
  704. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  705. return res;
  706. }
  707. static void ebml_free(EbmlSyntax *syntax, void *data)
  708. {
  709. int i, j;
  710. for (i=0; syntax[i].id; i++) {
  711. void *data_off = (char *)data + syntax[i].data_offset;
  712. switch (syntax[i].type) {
  713. case EBML_STR:
  714. case EBML_UTF8: av_freep(data_off); break;
  715. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  716. case EBML_NEST:
  717. if (syntax[i].list_elem_size) {
  718. EbmlList *list = data_off;
  719. char *ptr = list->elem;
  720. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  721. ebml_free(syntax[i].def.n, ptr);
  722. av_free(list->elem);
  723. } else
  724. ebml_free(syntax[i].def.n, data_off);
  725. default: break;
  726. }
  727. }
  728. }
  729. /*
  730. * Autodetecting...
  731. */
  732. static int matroska_probe(AVProbeData *p)
  733. {
  734. uint64_t total = 0;
  735. int len_mask = 0x80, size = 1, n = 1, i;
  736. /* EBML header? */
  737. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  738. return 0;
  739. /* length of header */
  740. total = p->buf[4];
  741. while (size <= 8 && !(total & len_mask)) {
  742. size++;
  743. len_mask >>= 1;
  744. }
  745. if (size > 8)
  746. return 0;
  747. total &= (len_mask - 1);
  748. while (n < size)
  749. total = (total << 8) | p->buf[4 + n++];
  750. /* Does the probe data contain the whole header? */
  751. if (p->buf_size < 4 + size + total)
  752. return 0;
  753. /* The header should contain a known document type. For now,
  754. * we don't parse the whole header but simply check for the
  755. * availability of that array of characters inside the header.
  756. * Not fully fool-proof, but good enough. */
  757. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  758. int probelen = strlen(matroska_doctypes[i]);
  759. for (n = 4+size; n <= 4+size+total-probelen; n++)
  760. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  761. return AVPROBE_SCORE_MAX;
  762. }
  763. // probably valid EBML header but no recognized doctype
  764. return AVPROBE_SCORE_MAX/2;
  765. }
  766. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  767. int num)
  768. {
  769. MatroskaTrack *tracks = matroska->tracks.elem;
  770. int i;
  771. for (i=0; i < matroska->tracks.nb_elem; i++)
  772. if (tracks[i].num == num)
  773. return &tracks[i];
  774. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  775. return NULL;
  776. }
  777. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  778. MatroskaTrack *track)
  779. {
  780. MatroskaTrackEncoding *encodings = track->encodings.elem;
  781. uint8_t* data = *buf;
  782. int isize = *buf_size;
  783. uint8_t* pkt_data = NULL;
  784. int pkt_size = isize;
  785. int result = 0;
  786. int olen;
  787. if (pkt_size >= 10000000)
  788. return -1;
  789. switch (encodings[0].compression.algo) {
  790. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  791. return encodings[0].compression.settings.size;
  792. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  793. do {
  794. olen = pkt_size *= 3;
  795. pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
  796. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  797. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  798. if (result)
  799. goto failed;
  800. pkt_size -= olen;
  801. break;
  802. #if CONFIG_ZLIB
  803. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  804. z_stream zstream = {0};
  805. if (inflateInit(&zstream) != Z_OK)
  806. return -1;
  807. zstream.next_in = data;
  808. zstream.avail_in = isize;
  809. do {
  810. pkt_size *= 3;
  811. pkt_data = av_realloc(pkt_data, pkt_size);
  812. zstream.avail_out = pkt_size - zstream.total_out;
  813. zstream.next_out = pkt_data + zstream.total_out;
  814. result = inflate(&zstream, Z_NO_FLUSH);
  815. } while (result==Z_OK && pkt_size<10000000);
  816. pkt_size = zstream.total_out;
  817. inflateEnd(&zstream);
  818. if (result != Z_STREAM_END)
  819. goto failed;
  820. break;
  821. }
  822. #endif
  823. #if CONFIG_BZLIB
  824. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  825. bz_stream bzstream = {0};
  826. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  827. return -1;
  828. bzstream.next_in = data;
  829. bzstream.avail_in = isize;
  830. do {
  831. pkt_size *= 3;
  832. pkt_data = av_realloc(pkt_data, pkt_size);
  833. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  834. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  835. result = BZ2_bzDecompress(&bzstream);
  836. } while (result==BZ_OK && pkt_size<10000000);
  837. pkt_size = bzstream.total_out_lo32;
  838. BZ2_bzDecompressEnd(&bzstream);
  839. if (result != BZ_STREAM_END)
  840. goto failed;
  841. break;
  842. }
  843. #endif
  844. default:
  845. return -1;
  846. }
  847. *buf = pkt_data;
  848. *buf_size = pkt_size;
  849. return 0;
  850. failed:
  851. av_free(pkt_data);
  852. return -1;
  853. }
  854. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  855. AVPacket *pkt, uint64_t display_duration)
  856. {
  857. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  858. for (; *ptr!=',' && ptr<end-1; ptr++);
  859. if (*ptr == ',')
  860. layer = ++ptr;
  861. for (; *ptr!=',' && ptr<end-1; ptr++);
  862. if (*ptr == ',') {
  863. int64_t end_pts = pkt->pts + display_duration;
  864. int sc = matroska->time_scale * pkt->pts / 10000000;
  865. int ec = matroska->time_scale * end_pts / 10000000;
  866. int sh, sm, ss, eh, em, es, len;
  867. sh = sc/360000; sc -= 360000*sh;
  868. sm = sc/ 6000; sc -= 6000*sm;
  869. ss = sc/ 100; sc -= 100*ss;
  870. eh = ec/360000; ec -= 360000*eh;
  871. em = ec/ 6000; ec -= 6000*em;
  872. es = ec/ 100; ec -= 100*es;
  873. *ptr++ = '\0';
  874. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  875. if (!(line = av_malloc(len)))
  876. return;
  877. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  878. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  879. av_free(pkt->data);
  880. pkt->data = line;
  881. pkt->size = strlen(line);
  882. }
  883. }
  884. static void matroska_merge_packets(AVPacket *out, AVPacket *in)
  885. {
  886. out->data = av_realloc(out->data, out->size+in->size);
  887. memcpy(out->data+out->size, in->data, in->size);
  888. out->size += in->size;
  889. av_destruct_packet(in);
  890. av_free(in);
  891. }
  892. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  893. AVMetadata **metadata, char *prefix)
  894. {
  895. MatroskaTag *tags = list->elem;
  896. char key[1024];
  897. int i;
  898. for (i=0; i < list->nb_elem; i++) {
  899. const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  900. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  901. else av_strlcpy(key, tags[i].name, sizeof(key));
  902. if (tags[i].def || !lang) {
  903. av_metadata_set2(metadata, key, tags[i].string, 0);
  904. if (tags[i].sub.nb_elem)
  905. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  906. }
  907. if (lang) {
  908. av_strlcat(key, "-", sizeof(key));
  909. av_strlcat(key, lang, sizeof(key));
  910. av_metadata_set2(metadata, key, tags[i].string, 0);
  911. if (tags[i].sub.nb_elem)
  912. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  913. }
  914. }
  915. }
  916. static void matroska_convert_tags(AVFormatContext *s)
  917. {
  918. MatroskaDemuxContext *matroska = s->priv_data;
  919. MatroskaTags *tags = matroska->tags.elem;
  920. int i, j;
  921. for (i=0; i < matroska->tags.nb_elem; i++) {
  922. if (tags[i].target.attachuid) {
  923. MatroskaAttachement *attachment = matroska->attachments.elem;
  924. for (j=0; j<matroska->attachments.nb_elem; j++)
  925. if (attachment[j].uid == tags[i].target.attachuid)
  926. matroska_convert_tag(s, &tags[i].tag,
  927. &attachment[j].stream->metadata, NULL);
  928. } else if (tags[i].target.chapteruid) {
  929. MatroskaChapter *chapter = matroska->chapters.elem;
  930. for (j=0; j<matroska->chapters.nb_elem; j++)
  931. if (chapter[j].uid == tags[i].target.chapteruid)
  932. matroska_convert_tag(s, &tags[i].tag,
  933. &chapter[j].chapter->metadata, NULL);
  934. } else if (tags[i].target.trackuid) {
  935. MatroskaTrack *track = matroska->tracks.elem;
  936. for (j=0; j<matroska->tracks.nb_elem; j++)
  937. if (track[j].uid == tags[i].target.trackuid)
  938. matroska_convert_tag(s, &tags[i].tag,
  939. &track[j].stream->metadata, NULL);
  940. } else {
  941. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  942. tags[i].target.type);
  943. }
  944. }
  945. }
  946. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  947. {
  948. EbmlList *seekhead_list = &matroska->seekhead;
  949. MatroskaSeekhead *seekhead = seekhead_list->elem;
  950. uint32_t level_up = matroska->level_up;
  951. int64_t before_pos = url_ftell(matroska->ctx->pb);
  952. uint32_t saved_id = matroska->current_id;
  953. MatroskaLevel level;
  954. int i;
  955. // we should not do any seeking in the streaming case
  956. if (url_is_streamed(matroska->ctx->pb) ||
  957. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  958. return;
  959. for (i=0; i<seekhead_list->nb_elem; i++) {
  960. int64_t offset = seekhead[i].pos + matroska->segment_start;
  961. if (seekhead[i].pos <= before_pos
  962. || seekhead[i].id == MATROSKA_ID_SEEKHEAD
  963. || seekhead[i].id == MATROSKA_ID_CLUSTER)
  964. continue;
  965. /* seek */
  966. if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
  967. continue;
  968. /* We don't want to lose our seekhead level, so we add
  969. * a dummy. This is a crude hack. */
  970. if (matroska->num_levels == EBML_MAX_DEPTH) {
  971. av_log(matroska->ctx, AV_LOG_INFO,
  972. "Max EBML element depth (%d) reached, "
  973. "cannot parse further.\n", EBML_MAX_DEPTH);
  974. break;
  975. }
  976. level.start = 0;
  977. level.length = (uint64_t)-1;
  978. matroska->levels[matroska->num_levels] = level;
  979. matroska->num_levels++;
  980. matroska->current_id = 0;
  981. ebml_parse(matroska, matroska_segment, matroska);
  982. /* remove dummy level */
  983. while (matroska->num_levels) {
  984. uint64_t length = matroska->levels[--matroska->num_levels].length;
  985. if (length == (uint64_t)-1)
  986. break;
  987. }
  988. }
  989. /* seek back */
  990. url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
  991. matroska->level_up = level_up;
  992. matroska->current_id = saved_id;
  993. }
  994. static int matroska_aac_profile(char *codec_id)
  995. {
  996. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  997. int profile;
  998. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  999. if (strstr(codec_id, aac_profiles[profile]))
  1000. break;
  1001. return profile + 1;
  1002. }
  1003. static int matroska_aac_sri(int samplerate)
  1004. {
  1005. int sri;
  1006. for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
  1007. if (ff_mpeg4audio_sample_rates[sri] == samplerate)
  1008. break;
  1009. return sri;
  1010. }
  1011. static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1012. {
  1013. MatroskaDemuxContext *matroska = s->priv_data;
  1014. EbmlList *attachements_list = &matroska->attachments;
  1015. MatroskaAttachement *attachements;
  1016. EbmlList *chapters_list = &matroska->chapters;
  1017. MatroskaChapter *chapters;
  1018. MatroskaTrack *tracks;
  1019. EbmlList *index_list;
  1020. MatroskaIndex *index;
  1021. int index_scale = 1;
  1022. uint64_t max_start = 0;
  1023. Ebml ebml = { 0 };
  1024. AVStream *st;
  1025. int i, j, res;
  1026. matroska->ctx = s;
  1027. /* First read the EBML header. */
  1028. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1029. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1030. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
  1031. av_log(matroska->ctx, AV_LOG_ERROR,
  1032. "EBML header using unsupported features\n"
  1033. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1034. ebml.version, ebml.doctype, ebml.doctype_version);
  1035. ebml_free(ebml_syntax, &ebml);
  1036. return AVERROR_PATCHWELCOME;
  1037. }
  1038. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1039. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1040. break;
  1041. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1042. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1043. }
  1044. ebml_free(ebml_syntax, &ebml);
  1045. /* The next thing is a segment. */
  1046. if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
  1047. return res;
  1048. matroska_execute_seekhead(matroska);
  1049. if (!matroska->time_scale)
  1050. matroska->time_scale = 1000000;
  1051. if (matroska->duration)
  1052. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1053. * 1000 / AV_TIME_BASE;
  1054. av_metadata_set2(&s->metadata, "title", matroska->title, 0);
  1055. tracks = matroska->tracks.elem;
  1056. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1057. MatroskaTrack *track = &tracks[i];
  1058. enum CodecID codec_id = CODEC_ID_NONE;
  1059. EbmlList *encodings_list = &tracks->encodings;
  1060. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1061. uint8_t *extradata = NULL;
  1062. int extradata_size = 0;
  1063. int extradata_offset = 0;
  1064. ByteIOContext b;
  1065. /* Apply some sanity checks. */
  1066. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1067. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1068. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1069. av_log(matroska->ctx, AV_LOG_INFO,
  1070. "Unknown or unsupported track type %"PRIu64"\n",
  1071. track->type);
  1072. continue;
  1073. }
  1074. if (track->codec_id == NULL)
  1075. continue;
  1076. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1077. if (!track->default_duration)
  1078. track->default_duration = 1000000000/track->video.frame_rate;
  1079. if (!track->video.display_width)
  1080. track->video.display_width = track->video.pixel_width;
  1081. if (!track->video.display_height)
  1082. track->video.display_height = track->video.pixel_height;
  1083. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1084. if (!track->audio.out_samplerate)
  1085. track->audio.out_samplerate = track->audio.samplerate;
  1086. }
  1087. if (encodings_list->nb_elem > 1) {
  1088. av_log(matroska->ctx, AV_LOG_ERROR,
  1089. "Multiple combined encodings no supported");
  1090. } else if (encodings_list->nb_elem == 1) {
  1091. if (encodings[0].type ||
  1092. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1093. #if CONFIG_ZLIB
  1094. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1095. #endif
  1096. #if CONFIG_BZLIB
  1097. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1098. #endif
  1099. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1100. encodings[0].scope = 0;
  1101. av_log(matroska->ctx, AV_LOG_ERROR,
  1102. "Unsupported encoding type");
  1103. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1104. uint8_t *codec_priv = track->codec_priv.data;
  1105. int offset = matroska_decode_buffer(&track->codec_priv.data,
  1106. &track->codec_priv.size,
  1107. track);
  1108. if (offset < 0) {
  1109. track->codec_priv.data = NULL;
  1110. track->codec_priv.size = 0;
  1111. av_log(matroska->ctx, AV_LOG_ERROR,
  1112. "Failed to decode codec private data\n");
  1113. } else if (offset > 0) {
  1114. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  1115. memcpy(track->codec_priv.data,
  1116. encodings[0].compression.settings.data, offset);
  1117. memcpy(track->codec_priv.data+offset, codec_priv,
  1118. track->codec_priv.size);
  1119. track->codec_priv.size += offset;
  1120. }
  1121. if (codec_priv != track->codec_priv.data)
  1122. av_free(codec_priv);
  1123. }
  1124. }
  1125. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1126. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1127. strlen(ff_mkv_codec_tags[j].str))){
  1128. codec_id= ff_mkv_codec_tags[j].id;
  1129. break;
  1130. }
  1131. }
  1132. st = track->stream = av_new_stream(s, 0);
  1133. if (st == NULL)
  1134. return AVERROR(ENOMEM);
  1135. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1136. && track->codec_priv.size >= 40
  1137. && track->codec_priv.data != NULL) {
  1138. track->ms_compat = 1;
  1139. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1140. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1141. extradata_offset = 40;
  1142. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1143. && track->codec_priv.size >= 14
  1144. && track->codec_priv.data != NULL) {
  1145. init_put_byte(&b, track->codec_priv.data, track->codec_priv.size,
  1146. URL_RDONLY, NULL, NULL, NULL, NULL);
  1147. ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1148. codec_id = st->codec->codec_id;
  1149. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1150. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1151. && (track->codec_priv.size >= 86)
  1152. && (track->codec_priv.data != NULL)) {
  1153. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1154. codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
  1155. } else if (codec_id == CODEC_ID_PCM_S16BE) {
  1156. switch (track->audio.bitdepth) {
  1157. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1158. case 24: codec_id = CODEC_ID_PCM_S24BE; break;
  1159. case 32: codec_id = CODEC_ID_PCM_S32BE; break;
  1160. }
  1161. } else if (codec_id == CODEC_ID_PCM_S16LE) {
  1162. switch (track->audio.bitdepth) {
  1163. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1164. case 24: codec_id = CODEC_ID_PCM_S24LE; break;
  1165. case 32: codec_id = CODEC_ID_PCM_S32LE; break;
  1166. }
  1167. } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1168. codec_id = CODEC_ID_PCM_F64LE;
  1169. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  1170. int profile = matroska_aac_profile(track->codec_id);
  1171. int sri = matroska_aac_sri(track->audio.samplerate);
  1172. extradata = av_malloc(5);
  1173. if (extradata == NULL)
  1174. return AVERROR(ENOMEM);
  1175. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1176. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1177. if (strstr(track->codec_id, "SBR")) {
  1178. sri = matroska_aac_sri(track->audio.out_samplerate);
  1179. extradata[2] = 0x56;
  1180. extradata[3] = 0xE5;
  1181. extradata[4] = 0x80 | (sri<<3);
  1182. extradata_size = 5;
  1183. } else
  1184. extradata_size = 2;
  1185. } else if (codec_id == CODEC_ID_TTA) {
  1186. extradata_size = 30;
  1187. extradata = av_mallocz(extradata_size);
  1188. if (extradata == NULL)
  1189. return AVERROR(ENOMEM);
  1190. init_put_byte(&b, extradata, extradata_size, 1,
  1191. NULL, NULL, NULL, NULL);
  1192. put_buffer(&b, "TTA1", 4);
  1193. put_le16(&b, 1);
  1194. put_le16(&b, track->audio.channels);
  1195. put_le16(&b, track->audio.bitdepth);
  1196. put_le32(&b, track->audio.out_samplerate);
  1197. put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1198. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1199. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1200. extradata_offset = 26;
  1201. } else if (codec_id == CODEC_ID_RA_144) {
  1202. track->audio.out_samplerate = 8000;
  1203. track->audio.channels = 1;
  1204. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1205. codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
  1206. int flavor;
  1207. init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
  1208. 0, NULL, NULL, NULL, NULL);
  1209. url_fskip(&b, 22);
  1210. flavor = get_be16(&b);
  1211. track->audio.coded_framesize = get_be32(&b);
  1212. url_fskip(&b, 12);
  1213. track->audio.sub_packet_h = get_be16(&b);
  1214. track->audio.frame_size = get_be16(&b);
  1215. track->audio.sub_packet_size = get_be16(&b);
  1216. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1217. if (codec_id == CODEC_ID_RA_288) {
  1218. st->codec->block_align = track->audio.coded_framesize;
  1219. track->codec_priv.size = 0;
  1220. } else {
  1221. if (codec_id == CODEC_ID_SIPR && flavor < 4) {
  1222. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1223. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1224. st->codec->bit_rate = sipr_bit_rate[flavor];
  1225. }
  1226. st->codec->block_align = track->audio.sub_packet_size;
  1227. extradata_offset = 78;
  1228. }
  1229. }
  1230. track->codec_priv.size -= extradata_offset;
  1231. if (codec_id == CODEC_ID_NONE)
  1232. av_log(matroska->ctx, AV_LOG_INFO,
  1233. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1234. if (track->time_scale < 0.01)
  1235. track->time_scale = 1.0;
  1236. av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1237. st->codec->codec_id = codec_id;
  1238. st->start_time = 0;
  1239. if (strcmp(track->language, "und"))
  1240. av_metadata_set2(&st->metadata, "language", track->language, 0);
  1241. av_metadata_set2(&st->metadata, "title", track->name, 0);
  1242. if (track->flag_default)
  1243. st->disposition |= AV_DISPOSITION_DEFAULT;
  1244. if (track->flag_forced)
  1245. st->disposition |= AV_DISPOSITION_FORCED;
  1246. if (track->default_duration)
  1247. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1248. track->default_duration, 1000000000, 30000);
  1249. if (!st->codec->extradata) {
  1250. if(extradata){
  1251. st->codec->extradata = extradata;
  1252. st->codec->extradata_size = extradata_size;
  1253. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1254. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1255. FF_INPUT_BUFFER_PADDING_SIZE);
  1256. if(st->codec->extradata == NULL)
  1257. return AVERROR(ENOMEM);
  1258. st->codec->extradata_size = track->codec_priv.size;
  1259. memcpy(st->codec->extradata,
  1260. track->codec_priv.data + extradata_offset,
  1261. track->codec_priv.size);
  1262. }
  1263. }
  1264. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1265. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1266. st->codec->codec_tag = track->video.fourcc;
  1267. st->codec->width = track->video.pixel_width;
  1268. st->codec->height = track->video.pixel_height;
  1269. av_reduce(&st->sample_aspect_ratio.num,
  1270. &st->sample_aspect_ratio.den,
  1271. st->codec->height * track->video.display_width,
  1272. st->codec-> width * track->video.display_height,
  1273. 255);
  1274. if (st->codec->codec_id != CODEC_ID_H264)
  1275. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1276. if (track->default_duration)
  1277. st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
  1278. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1279. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1280. st->codec->sample_rate = track->audio.out_samplerate;
  1281. st->codec->channels = track->audio.channels;
  1282. if (st->codec->codec_id != CODEC_ID_AAC)
  1283. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1284. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1285. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1286. }
  1287. }
  1288. attachements = attachements_list->elem;
  1289. for (j=0; j<attachements_list->nb_elem; j++) {
  1290. if (!(attachements[j].filename && attachements[j].mime &&
  1291. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1292. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1293. } else {
  1294. AVStream *st = av_new_stream(s, 0);
  1295. if (st == NULL)
  1296. break;
  1297. av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
  1298. st->codec->codec_id = CODEC_ID_NONE;
  1299. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1300. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1301. if(st->codec->extradata == NULL)
  1302. break;
  1303. st->codec->extradata_size = attachements[j].bin.size;
  1304. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1305. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1306. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1307. strlen(ff_mkv_mime_tags[i].str))) {
  1308. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1309. break;
  1310. }
  1311. }
  1312. attachements[j].stream = st;
  1313. }
  1314. }
  1315. chapters = chapters_list->elem;
  1316. for (i=0; i<chapters_list->nb_elem; i++)
  1317. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1318. && (max_start==0 || chapters[i].start > max_start)) {
  1319. chapters[i].chapter =
  1320. ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1321. chapters[i].start, chapters[i].end,
  1322. chapters[i].title);
  1323. av_metadata_set2(&chapters[i].chapter->metadata,
  1324. "title", chapters[i].title, 0);
  1325. max_start = chapters[i].start;
  1326. }
  1327. index_list = &matroska->index;
  1328. index = index_list->elem;
  1329. if (index_list->nb_elem
  1330. && index[0].time > 100000000000000/matroska->time_scale) {
  1331. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1332. index_scale = matroska->time_scale;
  1333. }
  1334. for (i=0; i<index_list->nb_elem; i++) {
  1335. EbmlList *pos_list = &index[i].pos;
  1336. MatroskaIndexPos *pos = pos_list->elem;
  1337. for (j=0; j<pos_list->nb_elem; j++) {
  1338. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1339. pos[j].track);
  1340. if (track && track->stream)
  1341. av_add_index_entry(track->stream,
  1342. pos[j].pos + matroska->segment_start,
  1343. index[i].time/index_scale, 0, 0,
  1344. AVINDEX_KEYFRAME);
  1345. }
  1346. }
  1347. matroska_convert_tags(s);
  1348. return 0;
  1349. }
  1350. /*
  1351. * Put one packet in an application-supplied AVPacket struct.
  1352. * Returns 0 on success or -1 on failure.
  1353. */
  1354. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1355. AVPacket *pkt)
  1356. {
  1357. if (matroska->num_packets > 0) {
  1358. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1359. av_free(matroska->packets[0]);
  1360. if (matroska->num_packets > 1) {
  1361. memmove(&matroska->packets[0], &matroska->packets[1],
  1362. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1363. matroska->packets =
  1364. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  1365. sizeof(AVPacket *));
  1366. } else {
  1367. av_freep(&matroska->packets);
  1368. }
  1369. matroska->num_packets--;
  1370. return 0;
  1371. }
  1372. return -1;
  1373. }
  1374. /*
  1375. * Free all packets in our internal queue.
  1376. */
  1377. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1378. {
  1379. if (matroska->packets) {
  1380. int n;
  1381. for (n = 0; n < matroska->num_packets; n++) {
  1382. av_free_packet(matroska->packets[n]);
  1383. av_free(matroska->packets[n]);
  1384. }
  1385. av_freep(&matroska->packets);
  1386. matroska->num_packets = 0;
  1387. }
  1388. }
  1389. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1390. int size, int64_t pos, uint64_t cluster_time,
  1391. uint64_t duration, int is_keyframe,
  1392. int64_t cluster_pos)
  1393. {
  1394. uint64_t timecode = AV_NOPTS_VALUE;
  1395. MatroskaTrack *track;
  1396. int res = 0;
  1397. AVStream *st;
  1398. AVPacket *pkt;
  1399. int16_t block_time;
  1400. uint32_t *lace_size = NULL;
  1401. int n, flags, laces = 0;
  1402. uint64_t num;
  1403. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1404. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1405. return res;
  1406. }
  1407. data += n;
  1408. size -= n;
  1409. track = matroska_find_track_by_num(matroska, num);
  1410. if (size <= 3 || !track || !track->stream) {
  1411. av_log(matroska->ctx, AV_LOG_INFO,
  1412. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1413. return res;
  1414. }
  1415. st = track->stream;
  1416. if (st->discard >= AVDISCARD_ALL)
  1417. return res;
  1418. if (duration == AV_NOPTS_VALUE)
  1419. duration = track->default_duration / matroska->time_scale;
  1420. block_time = AV_RB16(data);
  1421. data += 2;
  1422. flags = *data++;
  1423. size -= 3;
  1424. if (is_keyframe == -1)
  1425. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1426. if (cluster_time != (uint64_t)-1
  1427. && (block_time >= 0 || cluster_time >= -block_time)) {
  1428. timecode = cluster_time + block_time;
  1429. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1430. && timecode < track->end_timecode)
  1431. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1432. if (is_keyframe)
  1433. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1434. track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
  1435. }
  1436. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1437. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1438. return res;
  1439. matroska->skip_to_keyframe = 0;
  1440. }
  1441. switch ((flags & 0x06) >> 1) {
  1442. case 0x0: /* no lacing */
  1443. laces = 1;
  1444. lace_size = av_mallocz(sizeof(int));
  1445. lace_size[0] = size;
  1446. break;
  1447. case 0x1: /* Xiph lacing */
  1448. case 0x2: /* fixed-size lacing */
  1449. case 0x3: /* EBML lacing */
  1450. assert(size>0); // size <=3 is checked before size-=3 above
  1451. laces = (*data) + 1;
  1452. data += 1;
  1453. size -= 1;
  1454. lace_size = av_mallocz(laces * sizeof(int));
  1455. switch ((flags & 0x06) >> 1) {
  1456. case 0x1: /* Xiph lacing */ {
  1457. uint8_t temp;
  1458. uint32_t total = 0;
  1459. for (n = 0; res == 0 && n < laces - 1; n++) {
  1460. while (1) {
  1461. if (size == 0) {
  1462. res = -1;
  1463. break;
  1464. }
  1465. temp = *data;
  1466. lace_size[n] += temp;
  1467. data += 1;
  1468. size -= 1;
  1469. if (temp != 0xff)
  1470. break;
  1471. }
  1472. total += lace_size[n];
  1473. }
  1474. lace_size[n] = size - total;
  1475. break;
  1476. }
  1477. case 0x2: /* fixed-size lacing */
  1478. for (n = 0; n < laces; n++)
  1479. lace_size[n] = size / laces;
  1480. break;
  1481. case 0x3: /* EBML lacing */ {
  1482. uint32_t total;
  1483. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1484. if (n < 0) {
  1485. av_log(matroska->ctx, AV_LOG_INFO,
  1486. "EBML block data error\n");
  1487. break;
  1488. }
  1489. data += n;
  1490. size -= n;
  1491. total = lace_size[0] = num;
  1492. for (n = 1; res == 0 && n < laces - 1; n++) {
  1493. int64_t snum;
  1494. int r;
  1495. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1496. if (r < 0) {
  1497. av_log(matroska->ctx, AV_LOG_INFO,
  1498. "EBML block data error\n");
  1499. break;
  1500. }
  1501. data += r;
  1502. size -= r;
  1503. lace_size[n] = lace_size[n - 1] + snum;
  1504. total += lace_size[n];
  1505. }
  1506. lace_size[n] = size - total;
  1507. break;
  1508. }
  1509. }
  1510. break;
  1511. }
  1512. if (res == 0) {
  1513. for (n = 0; n < laces; n++) {
  1514. if ((st->codec->codec_id == CODEC_ID_RA_288 ||
  1515. st->codec->codec_id == CODEC_ID_COOK ||
  1516. st->codec->codec_id == CODEC_ID_SIPR ||
  1517. st->codec->codec_id == CODEC_ID_ATRAC3) &&
  1518. st->codec->block_align && track->audio.sub_packet_size) {
  1519. int a = st->codec->block_align;
  1520. int sps = track->audio.sub_packet_size;
  1521. int cfs = track->audio.coded_framesize;
  1522. int h = track->audio.sub_packet_h;
  1523. int y = track->audio.sub_packet_cnt;
  1524. int w = track->audio.frame_size;
  1525. int x;
  1526. if (!track->audio.pkt_cnt) {
  1527. if (st->codec->codec_id == CODEC_ID_RA_288)
  1528. for (x=0; x<h/2; x++)
  1529. memcpy(track->audio.buf+x*2*w+y*cfs,
  1530. data+x*cfs, cfs);
  1531. else if (st->codec->codec_id == CODEC_ID_SIPR)
  1532. memcpy(track->audio.buf + y*w, data, w);
  1533. else
  1534. for (x=0; x<w/sps; x++)
  1535. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1536. if (++track->audio.sub_packet_cnt >= h) {
  1537. if (st->codec->codec_id == CODEC_ID_SIPR)
  1538. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1539. track->audio.sub_packet_cnt = 0;
  1540. track->audio.pkt_cnt = h*w / a;
  1541. }
  1542. }
  1543. while (track->audio.pkt_cnt) {
  1544. pkt = av_mallocz(sizeof(AVPacket));
  1545. av_new_packet(pkt, a);
  1546. memcpy(pkt->data, track->audio.buf
  1547. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1548. pkt->pos = pos;
  1549. pkt->stream_index = st->index;
  1550. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1551. }
  1552. } else {
  1553. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1554. int offset = 0, pkt_size = lace_size[n];
  1555. uint8_t *pkt_data = data;
  1556. if (pkt_size > size) {
  1557. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  1558. break;
  1559. }
  1560. if (encodings && encodings->scope & 1) {
  1561. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1562. if (offset < 0)
  1563. continue;
  1564. }
  1565. pkt = av_mallocz(sizeof(AVPacket));
  1566. /* XXX: prevent data copy... */
  1567. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1568. av_free(pkt);
  1569. res = AVERROR(ENOMEM);
  1570. break;
  1571. }
  1572. if (offset)
  1573. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1574. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1575. if (pkt_data != data)
  1576. av_free(pkt_data);
  1577. if (n == 0)
  1578. pkt->flags = is_keyframe;
  1579. pkt->stream_index = st->index;
  1580. if (track->ms_compat)
  1581. pkt->dts = timecode;
  1582. else
  1583. pkt->pts = timecode;
  1584. pkt->pos = pos;
  1585. if (st->codec->codec_id == CODEC_ID_TEXT)
  1586. pkt->convergence_duration = duration;
  1587. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1588. pkt->duration = duration;
  1589. if (st->codec->codec_id == CODEC_ID_SSA)
  1590. matroska_fix_ass_packet(matroska, pkt, duration);
  1591. if (matroska->prev_pkt &&
  1592. timecode != AV_NOPTS_VALUE &&
  1593. matroska->prev_pkt->pts == timecode &&
  1594. matroska->prev_pkt->stream_index == st->index &&
  1595. st->codec->codec_id == CODEC_ID_SSA)
  1596. matroska_merge_packets(matroska->prev_pkt, pkt);
  1597. else {
  1598. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1599. matroska->prev_pkt = pkt;
  1600. }
  1601. }
  1602. if (timecode != AV_NOPTS_VALUE)
  1603. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1604. data += lace_size[n];
  1605. size -= lace_size[n];
  1606. }
  1607. }
  1608. av_free(lace_size);
  1609. return res;
  1610. }
  1611. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1612. {
  1613. MatroskaCluster cluster = { 0 };
  1614. EbmlList *blocks_list;
  1615. MatroskaBlock *blocks;
  1616. int i, res;
  1617. int64_t pos = url_ftell(matroska->ctx->pb);
  1618. matroska->prev_pkt = NULL;
  1619. if (matroska->current_id)
  1620. pos -= 4; /* sizeof the ID which was already read */
  1621. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1622. blocks_list = &cluster.blocks;
  1623. blocks = blocks_list->elem;
  1624. for (i=0; i<blocks_list->nb_elem; i++)
  1625. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1626. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1627. res=matroska_parse_block(matroska,
  1628. blocks[i].bin.data, blocks[i].bin.size,
  1629. blocks[i].bin.pos, cluster.timecode,
  1630. blocks[i].duration, is_keyframe,
  1631. pos);
  1632. }
  1633. ebml_free(matroska_cluster, &cluster);
  1634. if (res < 0) matroska->done = 1;
  1635. return res;
  1636. }
  1637. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1638. {
  1639. MatroskaDemuxContext *matroska = s->priv_data;
  1640. while (matroska_deliver_packet(matroska, pkt)) {
  1641. if (matroska->done)
  1642. return AVERROR_EOF;
  1643. matroska_parse_cluster(matroska);
  1644. }
  1645. return 0;
  1646. }
  1647. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1648. int64_t timestamp, int flags)
  1649. {
  1650. MatroskaDemuxContext *matroska = s->priv_data;
  1651. MatroskaTrack *tracks = matroska->tracks.elem;
  1652. AVStream *st = s->streams[stream_index];
  1653. int i, index, index_sub, index_min;
  1654. if (!st->nb_index_entries)
  1655. return 0;
  1656. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1657. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1658. url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1659. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1660. matroska_clear_queue(matroska);
  1661. if (matroska_parse_cluster(matroska) < 0)
  1662. break;
  1663. }
  1664. }
  1665. matroska_clear_queue(matroska);
  1666. if (index < 0)
  1667. return 0;
  1668. index_min = index;
  1669. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1670. tracks[i].end_timecode = 0;
  1671. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  1672. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  1673. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  1674. if (index_sub >= 0
  1675. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  1676. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  1677. index_min = index_sub;
  1678. }
  1679. }
  1680. url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  1681. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1682. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  1683. matroska->done = 0;
  1684. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1685. return 0;
  1686. }
  1687. static int matroska_read_close(AVFormatContext *s)
  1688. {
  1689. MatroskaDemuxContext *matroska = s->priv_data;
  1690. MatroskaTrack *tracks = matroska->tracks.elem;
  1691. int n;
  1692. matroska_clear_queue(matroska);
  1693. for (n=0; n < matroska->tracks.nb_elem; n++)
  1694. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1695. av_free(tracks[n].audio.buf);
  1696. ebml_free(matroska_segment, matroska);
  1697. return 0;
  1698. }
  1699. AVInputFormat matroska_demuxer = {
  1700. "matroska,webm",
  1701. NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
  1702. sizeof(MatroskaDemuxContext),
  1703. matroska_probe,
  1704. matroska_read_header,
  1705. matroska_read_packet,
  1706. matroska_read_close,
  1707. matroska_read_seek,
  1708. .metadata_conv = ff_mkv_metadata_conv,
  1709. };