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.

1933 lines
69KB

  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 read = 1, n = 1;
  474. uint64_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. read = 8 - ff_log2_tab[total];
  490. if (read > max_size) {
  491. int64_t pos = url_ftell(pb) - 1;
  492. av_log(matroska->ctx, AV_LOG_ERROR,
  493. "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
  494. (uint8_t) total, pos, pos);
  495. return AVERROR_INVALIDDATA;
  496. }
  497. /* read out length */
  498. total ^= 1 << ff_log2_tab[total];
  499. while (n++ < read)
  500. total = (total << 8) | get_byte(pb);
  501. *number = total;
  502. return read;
  503. }
  504. /**
  505. * Read a EBML length value.
  506. * This needs special handling for the "unknown length" case which has multiple
  507. * encodings.
  508. */
  509. static int ebml_read_length(MatroskaDemuxContext *matroska, ByteIOContext *pb,
  510. uint64_t *number)
  511. {
  512. int res = ebml_read_num(matroska, pb, 8, number);
  513. if (res > 0 && *number + 1 == 1ULL << (7 * res))
  514. *number = 0xffffffffffffffULL;
  515. return res;
  516. }
  517. /*
  518. * Read the next element as an unsigned int.
  519. * 0 is success, < 0 is failure.
  520. */
  521. static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
  522. {
  523. int n = 0;
  524. if (size > 8)
  525. return AVERROR_INVALIDDATA;
  526. /* big-endian ordering; build up number */
  527. *num = 0;
  528. while (n++ < size)
  529. *num = (*num << 8) | get_byte(pb);
  530. return 0;
  531. }
  532. /*
  533. * Read the next element as a float.
  534. * 0 is success, < 0 is failure.
  535. */
  536. static int ebml_read_float(ByteIOContext *pb, int size, double *num)
  537. {
  538. if (size == 0) {
  539. *num = 0;
  540. } else if (size == 4) {
  541. *num= av_int2flt(get_be32(pb));
  542. } else if(size==8){
  543. *num= av_int2dbl(get_be64(pb));
  544. } else
  545. return AVERROR_INVALIDDATA;
  546. return 0;
  547. }
  548. /*
  549. * Read the next element as an ASCII string.
  550. * 0 is success, < 0 is failure.
  551. */
  552. static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
  553. {
  554. av_free(*str);
  555. /* EBML strings are usually not 0-terminated, so we allocate one
  556. * byte more, read the string and NULL-terminate it ourselves. */
  557. if (!(*str = av_malloc(size + 1)))
  558. return AVERROR(ENOMEM);
  559. if (get_buffer(pb, (uint8_t *) *str, size) != size) {
  560. av_freep(str);
  561. return AVERROR(EIO);
  562. }
  563. (*str)[size] = '\0';
  564. return 0;
  565. }
  566. /*
  567. * Read the next element as binary data.
  568. * 0 is success, < 0 is failure.
  569. */
  570. static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
  571. {
  572. av_free(bin->data);
  573. if (!(bin->data = av_malloc(length)))
  574. return AVERROR(ENOMEM);
  575. bin->size = length;
  576. bin->pos = url_ftell(pb);
  577. if (get_buffer(pb, bin->data, length) != length) {
  578. av_freep(&bin->data);
  579. return AVERROR(EIO);
  580. }
  581. return 0;
  582. }
  583. /*
  584. * Read the next element, but only the header. The contents
  585. * are supposed to be sub-elements which can be read separately.
  586. * 0 is success, < 0 is failure.
  587. */
  588. static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
  589. {
  590. ByteIOContext *pb = matroska->ctx->pb;
  591. MatroskaLevel *level;
  592. if (matroska->num_levels >= EBML_MAX_DEPTH) {
  593. av_log(matroska->ctx, AV_LOG_ERROR,
  594. "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
  595. return AVERROR(ENOSYS);
  596. }
  597. level = &matroska->levels[matroska->num_levels++];
  598. level->start = url_ftell(pb);
  599. level->length = length;
  600. return 0;
  601. }
  602. /*
  603. * Read signed/unsigned "EBML" numbers.
  604. * Return: number of bytes processed, < 0 on error
  605. */
  606. static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
  607. uint8_t *data, uint32_t size, uint64_t *num)
  608. {
  609. ByteIOContext pb;
  610. init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
  611. return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
  612. }
  613. /*
  614. * Same as above, but signed.
  615. */
  616. static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
  617. uint8_t *data, uint32_t size, int64_t *num)
  618. {
  619. uint64_t unum;
  620. int res;
  621. /* read as unsigned number first */
  622. if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
  623. return res;
  624. /* make signed (weird way) */
  625. *num = unum - ((1LL << (7*res - 1)) - 1);
  626. return res;
  627. }
  628. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  629. EbmlSyntax *syntax, void *data);
  630. static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  631. uint32_t id, void *data)
  632. {
  633. int i;
  634. for (i=0; syntax[i].id; i++)
  635. if (id == syntax[i].id)
  636. break;
  637. if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
  638. matroska->num_levels > 0 &&
  639. matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
  640. return 0; // we reached the end of an unknown size cluster
  641. if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
  642. av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
  643. return ebml_parse_elem(matroska, &syntax[i], data);
  644. }
  645. static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  646. void *data)
  647. {
  648. if (!matroska->current_id) {
  649. uint64_t id;
  650. int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
  651. if (res < 0)
  652. return res;
  653. matroska->current_id = id | 1 << 7*res;
  654. }
  655. return ebml_parse_id(matroska, syntax, matroska->current_id, data);
  656. }
  657. static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
  658. void *data)
  659. {
  660. int i, res = 0;
  661. for (i=0; syntax[i].id; i++)
  662. switch (syntax[i].type) {
  663. case EBML_UINT:
  664. *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
  665. break;
  666. case EBML_FLOAT:
  667. *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
  668. break;
  669. case EBML_STR:
  670. case EBML_UTF8:
  671. *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
  672. break;
  673. }
  674. while (!res && !ebml_level_end(matroska))
  675. res = ebml_parse(matroska, syntax, data);
  676. return res;
  677. }
  678. static int ebml_parse_elem(MatroskaDemuxContext *matroska,
  679. EbmlSyntax *syntax, void *data)
  680. {
  681. ByteIOContext *pb = matroska->ctx->pb;
  682. uint32_t id = syntax->id;
  683. uint64_t length;
  684. int res;
  685. data = (char *)data + syntax->data_offset;
  686. if (syntax->list_elem_size) {
  687. EbmlList *list = data;
  688. list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  689. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  690. memset(data, 0, syntax->list_elem_size);
  691. list->nb_elem++;
  692. }
  693. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  694. matroska->current_id = 0;
  695. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  696. return res;
  697. }
  698. switch (syntax->type) {
  699. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  700. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  701. case EBML_STR:
  702. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  703. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  704. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  705. return res;
  706. if (id == MATROSKA_ID_SEGMENT)
  707. matroska->segment_start = url_ftell(matroska->ctx->pb);
  708. return ebml_parse_nest(matroska, syntax->def.n, data);
  709. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  710. case EBML_STOP: return 1;
  711. default: return url_fseek(pb,length,SEEK_CUR)<0 ? AVERROR(EIO) : 0;
  712. }
  713. if (res == AVERROR_INVALIDDATA)
  714. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  715. else if (res == AVERROR(EIO))
  716. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  717. return res;
  718. }
  719. static void ebml_free(EbmlSyntax *syntax, void *data)
  720. {
  721. int i, j;
  722. for (i=0; syntax[i].id; i++) {
  723. void *data_off = (char *)data + syntax[i].data_offset;
  724. switch (syntax[i].type) {
  725. case EBML_STR:
  726. case EBML_UTF8: av_freep(data_off); break;
  727. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  728. case EBML_NEST:
  729. if (syntax[i].list_elem_size) {
  730. EbmlList *list = data_off;
  731. char *ptr = list->elem;
  732. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  733. ebml_free(syntax[i].def.n, ptr);
  734. av_free(list->elem);
  735. } else
  736. ebml_free(syntax[i].def.n, data_off);
  737. default: break;
  738. }
  739. }
  740. }
  741. /*
  742. * Autodetecting...
  743. */
  744. static int matroska_probe(AVProbeData *p)
  745. {
  746. uint64_t total = 0;
  747. int len_mask = 0x80, size = 1, n = 1, i;
  748. /* EBML header? */
  749. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  750. return 0;
  751. /* length of header */
  752. total = p->buf[4];
  753. while (size <= 8 && !(total & len_mask)) {
  754. size++;
  755. len_mask >>= 1;
  756. }
  757. if (size > 8)
  758. return 0;
  759. total &= (len_mask - 1);
  760. while (n < size)
  761. total = (total << 8) | p->buf[4 + n++];
  762. /* Does the probe data contain the whole header? */
  763. if (p->buf_size < 4 + size + total)
  764. return 0;
  765. /* The header should contain a known document type. For now,
  766. * we don't parse the whole header but simply check for the
  767. * availability of that array of characters inside the header.
  768. * Not fully fool-proof, but good enough. */
  769. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  770. int probelen = strlen(matroska_doctypes[i]);
  771. for (n = 4+size; n <= 4+size+total-probelen; n++)
  772. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  773. return AVPROBE_SCORE_MAX;
  774. }
  775. // probably valid EBML header but no recognized doctype
  776. return AVPROBE_SCORE_MAX/2;
  777. }
  778. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  779. int num)
  780. {
  781. MatroskaTrack *tracks = matroska->tracks.elem;
  782. int i;
  783. for (i=0; i < matroska->tracks.nb_elem; i++)
  784. if (tracks[i].num == num)
  785. return &tracks[i];
  786. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  787. return NULL;
  788. }
  789. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  790. MatroskaTrack *track)
  791. {
  792. MatroskaTrackEncoding *encodings = track->encodings.elem;
  793. uint8_t* data = *buf;
  794. int isize = *buf_size;
  795. uint8_t* pkt_data = NULL;
  796. int pkt_size = isize;
  797. int result = 0;
  798. int olen;
  799. if (pkt_size >= 10000000)
  800. return -1;
  801. switch (encodings[0].compression.algo) {
  802. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  803. return encodings[0].compression.settings.size;
  804. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  805. do {
  806. olen = pkt_size *= 3;
  807. pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
  808. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  809. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  810. if (result)
  811. goto failed;
  812. pkt_size -= olen;
  813. break;
  814. #if CONFIG_ZLIB
  815. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  816. z_stream zstream = {0};
  817. if (inflateInit(&zstream) != Z_OK)
  818. return -1;
  819. zstream.next_in = data;
  820. zstream.avail_in = isize;
  821. do {
  822. pkt_size *= 3;
  823. pkt_data = av_realloc(pkt_data, pkt_size);
  824. zstream.avail_out = pkt_size - zstream.total_out;
  825. zstream.next_out = pkt_data + zstream.total_out;
  826. result = inflate(&zstream, Z_NO_FLUSH);
  827. } while (result==Z_OK && pkt_size<10000000);
  828. pkt_size = zstream.total_out;
  829. inflateEnd(&zstream);
  830. if (result != Z_STREAM_END)
  831. goto failed;
  832. break;
  833. }
  834. #endif
  835. #if CONFIG_BZLIB
  836. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  837. bz_stream bzstream = {0};
  838. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  839. return -1;
  840. bzstream.next_in = data;
  841. bzstream.avail_in = isize;
  842. do {
  843. pkt_size *= 3;
  844. pkt_data = av_realloc(pkt_data, pkt_size);
  845. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  846. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  847. result = BZ2_bzDecompress(&bzstream);
  848. } while (result==BZ_OK && pkt_size<10000000);
  849. pkt_size = bzstream.total_out_lo32;
  850. BZ2_bzDecompressEnd(&bzstream);
  851. if (result != BZ_STREAM_END)
  852. goto failed;
  853. break;
  854. }
  855. #endif
  856. default:
  857. return -1;
  858. }
  859. *buf = pkt_data;
  860. *buf_size = pkt_size;
  861. return 0;
  862. failed:
  863. av_free(pkt_data);
  864. return -1;
  865. }
  866. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  867. AVPacket *pkt, uint64_t display_duration)
  868. {
  869. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  870. for (; *ptr!=',' && ptr<end-1; ptr++);
  871. if (*ptr == ',')
  872. layer = ++ptr;
  873. for (; *ptr!=',' && ptr<end-1; ptr++);
  874. if (*ptr == ',') {
  875. int64_t end_pts = pkt->pts + display_duration;
  876. int sc = matroska->time_scale * pkt->pts / 10000000;
  877. int ec = matroska->time_scale * end_pts / 10000000;
  878. int sh, sm, ss, eh, em, es, len;
  879. sh = sc/360000; sc -= 360000*sh;
  880. sm = sc/ 6000; sc -= 6000*sm;
  881. ss = sc/ 100; sc -= 100*ss;
  882. eh = ec/360000; ec -= 360000*eh;
  883. em = ec/ 6000; ec -= 6000*em;
  884. es = ec/ 100; ec -= 100*es;
  885. *ptr++ = '\0';
  886. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  887. if (!(line = av_malloc(len)))
  888. return;
  889. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  890. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  891. av_free(pkt->data);
  892. pkt->data = line;
  893. pkt->size = strlen(line);
  894. }
  895. }
  896. static void matroska_merge_packets(AVPacket *out, AVPacket *in)
  897. {
  898. out->data = av_realloc(out->data, out->size+in->size);
  899. memcpy(out->data+out->size, in->data, in->size);
  900. out->size += in->size;
  901. av_destruct_packet(in);
  902. av_free(in);
  903. }
  904. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  905. AVMetadata **metadata, char *prefix)
  906. {
  907. MatroskaTag *tags = list->elem;
  908. char key[1024];
  909. int i;
  910. for (i=0; i < list->nb_elem; i++) {
  911. const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  912. if (!tags[i].name) {
  913. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  914. continue;
  915. }
  916. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  917. else av_strlcpy(key, tags[i].name, sizeof(key));
  918. if (tags[i].def || !lang) {
  919. av_metadata_set2(metadata, key, tags[i].string, 0);
  920. if (tags[i].sub.nb_elem)
  921. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  922. }
  923. if (lang) {
  924. av_strlcat(key, "-", sizeof(key));
  925. av_strlcat(key, lang, sizeof(key));
  926. av_metadata_set2(metadata, key, tags[i].string, 0);
  927. if (tags[i].sub.nb_elem)
  928. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  929. }
  930. }
  931. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  932. }
  933. static void matroska_convert_tags(AVFormatContext *s)
  934. {
  935. MatroskaDemuxContext *matroska = s->priv_data;
  936. MatroskaTags *tags = matroska->tags.elem;
  937. int i, j;
  938. for (i=0; i < matroska->tags.nb_elem; i++) {
  939. if (tags[i].target.attachuid) {
  940. MatroskaAttachement *attachment = matroska->attachments.elem;
  941. for (j=0; j<matroska->attachments.nb_elem; j++)
  942. if (attachment[j].uid == tags[i].target.attachuid)
  943. matroska_convert_tag(s, &tags[i].tag,
  944. &attachment[j].stream->metadata, NULL);
  945. } else if (tags[i].target.chapteruid) {
  946. MatroskaChapter *chapter = matroska->chapters.elem;
  947. for (j=0; j<matroska->chapters.nb_elem; j++)
  948. if (chapter[j].uid == tags[i].target.chapteruid)
  949. matroska_convert_tag(s, &tags[i].tag,
  950. &chapter[j].chapter->metadata, NULL);
  951. } else if (tags[i].target.trackuid) {
  952. MatroskaTrack *track = matroska->tracks.elem;
  953. for (j=0; j<matroska->tracks.nb_elem; j++)
  954. if (track[j].uid == tags[i].target.trackuid)
  955. matroska_convert_tag(s, &tags[i].tag,
  956. &track[j].stream->metadata, NULL);
  957. } else {
  958. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  959. tags[i].target.type);
  960. }
  961. }
  962. }
  963. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  964. {
  965. EbmlList *seekhead_list = &matroska->seekhead;
  966. MatroskaSeekhead *seekhead = seekhead_list->elem;
  967. uint32_t level_up = matroska->level_up;
  968. int64_t before_pos = url_ftell(matroska->ctx->pb);
  969. uint32_t saved_id = matroska->current_id;
  970. MatroskaLevel level;
  971. int i;
  972. // we should not do any seeking in the streaming case
  973. if (url_is_streamed(matroska->ctx->pb) ||
  974. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  975. return;
  976. for (i=0; i<seekhead_list->nb_elem; i++) {
  977. int64_t offset = seekhead[i].pos + matroska->segment_start;
  978. if (seekhead[i].pos <= before_pos
  979. || seekhead[i].id == MATROSKA_ID_SEEKHEAD
  980. || seekhead[i].id == MATROSKA_ID_CLUSTER)
  981. continue;
  982. /* seek */
  983. if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
  984. continue;
  985. /* We don't want to lose our seekhead level, so we add
  986. * a dummy. This is a crude hack. */
  987. if (matroska->num_levels == EBML_MAX_DEPTH) {
  988. av_log(matroska->ctx, AV_LOG_INFO,
  989. "Max EBML element depth (%d) reached, "
  990. "cannot parse further.\n", EBML_MAX_DEPTH);
  991. break;
  992. }
  993. level.start = 0;
  994. level.length = (uint64_t)-1;
  995. matroska->levels[matroska->num_levels] = level;
  996. matroska->num_levels++;
  997. matroska->current_id = 0;
  998. ebml_parse(matroska, matroska_segment, matroska);
  999. /* remove dummy level */
  1000. while (matroska->num_levels) {
  1001. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1002. if (length == (uint64_t)-1)
  1003. break;
  1004. }
  1005. }
  1006. /* seek back */
  1007. url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
  1008. matroska->level_up = level_up;
  1009. matroska->current_id = saved_id;
  1010. }
  1011. static int matroska_aac_profile(char *codec_id)
  1012. {
  1013. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1014. int profile;
  1015. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1016. if (strstr(codec_id, aac_profiles[profile]))
  1017. break;
  1018. return profile + 1;
  1019. }
  1020. static int matroska_aac_sri(int samplerate)
  1021. {
  1022. int sri;
  1023. for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
  1024. if (ff_mpeg4audio_sample_rates[sri] == samplerate)
  1025. break;
  1026. return sri;
  1027. }
  1028. static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1029. {
  1030. MatroskaDemuxContext *matroska = s->priv_data;
  1031. EbmlList *attachements_list = &matroska->attachments;
  1032. MatroskaAttachement *attachements;
  1033. EbmlList *chapters_list = &matroska->chapters;
  1034. MatroskaChapter *chapters;
  1035. MatroskaTrack *tracks;
  1036. EbmlList *index_list;
  1037. MatroskaIndex *index;
  1038. int index_scale = 1;
  1039. uint64_t max_start = 0;
  1040. Ebml ebml = { 0 };
  1041. AVStream *st;
  1042. int i, j, res;
  1043. matroska->ctx = s;
  1044. /* First read the EBML header. */
  1045. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1046. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1047. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
  1048. av_log(matroska->ctx, AV_LOG_ERROR,
  1049. "EBML header using unsupported features\n"
  1050. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1051. ebml.version, ebml.doctype, ebml.doctype_version);
  1052. ebml_free(ebml_syntax, &ebml);
  1053. return AVERROR_PATCHWELCOME;
  1054. }
  1055. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1056. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1057. break;
  1058. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1059. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1060. }
  1061. ebml_free(ebml_syntax, &ebml);
  1062. /* The next thing is a segment. */
  1063. if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
  1064. return res;
  1065. matroska_execute_seekhead(matroska);
  1066. if (!matroska->time_scale)
  1067. matroska->time_scale = 1000000;
  1068. if (matroska->duration)
  1069. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1070. * 1000 / AV_TIME_BASE;
  1071. av_metadata_set2(&s->metadata, "title", matroska->title, 0);
  1072. tracks = matroska->tracks.elem;
  1073. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1074. MatroskaTrack *track = &tracks[i];
  1075. enum CodecID codec_id = CODEC_ID_NONE;
  1076. EbmlList *encodings_list = &tracks->encodings;
  1077. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1078. uint8_t *extradata = NULL;
  1079. int extradata_size = 0;
  1080. int extradata_offset = 0;
  1081. ByteIOContext b;
  1082. /* Apply some sanity checks. */
  1083. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1084. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1085. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1086. av_log(matroska->ctx, AV_LOG_INFO,
  1087. "Unknown or unsupported track type %"PRIu64"\n",
  1088. track->type);
  1089. continue;
  1090. }
  1091. if (track->codec_id == NULL)
  1092. continue;
  1093. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1094. if (!track->default_duration)
  1095. track->default_duration = 1000000000/track->video.frame_rate;
  1096. if (!track->video.display_width)
  1097. track->video.display_width = track->video.pixel_width;
  1098. if (!track->video.display_height)
  1099. track->video.display_height = track->video.pixel_height;
  1100. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1101. if (!track->audio.out_samplerate)
  1102. track->audio.out_samplerate = track->audio.samplerate;
  1103. }
  1104. if (encodings_list->nb_elem > 1) {
  1105. av_log(matroska->ctx, AV_LOG_ERROR,
  1106. "Multiple combined encodings no supported");
  1107. } else if (encodings_list->nb_elem == 1) {
  1108. if (encodings[0].type ||
  1109. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1110. #if CONFIG_ZLIB
  1111. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1112. #endif
  1113. #if CONFIG_BZLIB
  1114. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1115. #endif
  1116. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1117. encodings[0].scope = 0;
  1118. av_log(matroska->ctx, AV_LOG_ERROR,
  1119. "Unsupported encoding type");
  1120. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1121. uint8_t *codec_priv = track->codec_priv.data;
  1122. int offset = matroska_decode_buffer(&track->codec_priv.data,
  1123. &track->codec_priv.size,
  1124. track);
  1125. if (offset < 0) {
  1126. track->codec_priv.data = NULL;
  1127. track->codec_priv.size = 0;
  1128. av_log(matroska->ctx, AV_LOG_ERROR,
  1129. "Failed to decode codec private data\n");
  1130. } else if (offset > 0) {
  1131. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  1132. memcpy(track->codec_priv.data,
  1133. encodings[0].compression.settings.data, offset);
  1134. memcpy(track->codec_priv.data+offset, codec_priv,
  1135. track->codec_priv.size);
  1136. track->codec_priv.size += offset;
  1137. }
  1138. if (codec_priv != track->codec_priv.data)
  1139. av_free(codec_priv);
  1140. }
  1141. }
  1142. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1143. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1144. strlen(ff_mkv_codec_tags[j].str))){
  1145. codec_id= ff_mkv_codec_tags[j].id;
  1146. break;
  1147. }
  1148. }
  1149. st = track->stream = av_new_stream(s, 0);
  1150. if (st == NULL)
  1151. return AVERROR(ENOMEM);
  1152. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1153. && track->codec_priv.size >= 40
  1154. && track->codec_priv.data != NULL) {
  1155. track->ms_compat = 1;
  1156. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1157. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1158. extradata_offset = 40;
  1159. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1160. && track->codec_priv.size >= 14
  1161. && track->codec_priv.data != NULL) {
  1162. init_put_byte(&b, track->codec_priv.data, track->codec_priv.size,
  1163. URL_RDONLY, NULL, NULL, NULL, NULL);
  1164. ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1165. codec_id = st->codec->codec_id;
  1166. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1167. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1168. && (track->codec_priv.size >= 86)
  1169. && (track->codec_priv.data != NULL)) {
  1170. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1171. codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
  1172. } else if (codec_id == CODEC_ID_PCM_S16BE) {
  1173. switch (track->audio.bitdepth) {
  1174. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1175. case 24: codec_id = CODEC_ID_PCM_S24BE; break;
  1176. case 32: codec_id = CODEC_ID_PCM_S32BE; break;
  1177. }
  1178. } else if (codec_id == CODEC_ID_PCM_S16LE) {
  1179. switch (track->audio.bitdepth) {
  1180. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1181. case 24: codec_id = CODEC_ID_PCM_S24LE; break;
  1182. case 32: codec_id = CODEC_ID_PCM_S32LE; break;
  1183. }
  1184. } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1185. codec_id = CODEC_ID_PCM_F64LE;
  1186. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  1187. int profile = matroska_aac_profile(track->codec_id);
  1188. int sri = matroska_aac_sri(track->audio.samplerate);
  1189. extradata = av_malloc(5);
  1190. if (extradata == NULL)
  1191. return AVERROR(ENOMEM);
  1192. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1193. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1194. if (strstr(track->codec_id, "SBR")) {
  1195. sri = matroska_aac_sri(track->audio.out_samplerate);
  1196. extradata[2] = 0x56;
  1197. extradata[3] = 0xE5;
  1198. extradata[4] = 0x80 | (sri<<3);
  1199. extradata_size = 5;
  1200. } else
  1201. extradata_size = 2;
  1202. } else if (codec_id == CODEC_ID_TTA) {
  1203. extradata_size = 30;
  1204. extradata = av_mallocz(extradata_size);
  1205. if (extradata == NULL)
  1206. return AVERROR(ENOMEM);
  1207. init_put_byte(&b, extradata, extradata_size, 1,
  1208. NULL, NULL, NULL, NULL);
  1209. put_buffer(&b, "TTA1", 4);
  1210. put_le16(&b, 1);
  1211. put_le16(&b, track->audio.channels);
  1212. put_le16(&b, track->audio.bitdepth);
  1213. put_le32(&b, track->audio.out_samplerate);
  1214. put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1215. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1216. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1217. extradata_offset = 26;
  1218. } else if (codec_id == CODEC_ID_RA_144) {
  1219. track->audio.out_samplerate = 8000;
  1220. track->audio.channels = 1;
  1221. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1222. codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
  1223. int flavor;
  1224. init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
  1225. 0, NULL, NULL, NULL, NULL);
  1226. url_fskip(&b, 22);
  1227. flavor = get_be16(&b);
  1228. track->audio.coded_framesize = get_be32(&b);
  1229. url_fskip(&b, 12);
  1230. track->audio.sub_packet_h = get_be16(&b);
  1231. track->audio.frame_size = get_be16(&b);
  1232. track->audio.sub_packet_size = get_be16(&b);
  1233. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1234. if (codec_id == CODEC_ID_RA_288) {
  1235. st->codec->block_align = track->audio.coded_framesize;
  1236. track->codec_priv.size = 0;
  1237. } else {
  1238. if (codec_id == CODEC_ID_SIPR && flavor < 4) {
  1239. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1240. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1241. st->codec->bit_rate = sipr_bit_rate[flavor];
  1242. }
  1243. st->codec->block_align = track->audio.sub_packet_size;
  1244. extradata_offset = 78;
  1245. }
  1246. }
  1247. track->codec_priv.size -= extradata_offset;
  1248. if (codec_id == CODEC_ID_NONE)
  1249. av_log(matroska->ctx, AV_LOG_INFO,
  1250. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1251. if (track->time_scale < 0.01)
  1252. track->time_scale = 1.0;
  1253. av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1254. st->codec->codec_id = codec_id;
  1255. st->start_time = 0;
  1256. if (strcmp(track->language, "und"))
  1257. av_metadata_set2(&st->metadata, "language", track->language, 0);
  1258. av_metadata_set2(&st->metadata, "title", track->name, 0);
  1259. if (track->flag_default)
  1260. st->disposition |= AV_DISPOSITION_DEFAULT;
  1261. if (track->flag_forced)
  1262. st->disposition |= AV_DISPOSITION_FORCED;
  1263. if (track->default_duration)
  1264. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1265. track->default_duration, 1000000000, 30000);
  1266. if (!st->codec->extradata) {
  1267. if(extradata){
  1268. st->codec->extradata = extradata;
  1269. st->codec->extradata_size = extradata_size;
  1270. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1271. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1272. FF_INPUT_BUFFER_PADDING_SIZE);
  1273. if(st->codec->extradata == NULL)
  1274. return AVERROR(ENOMEM);
  1275. st->codec->extradata_size = track->codec_priv.size;
  1276. memcpy(st->codec->extradata,
  1277. track->codec_priv.data + extradata_offset,
  1278. track->codec_priv.size);
  1279. }
  1280. }
  1281. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1282. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1283. st->codec->codec_tag = track->video.fourcc;
  1284. st->codec->width = track->video.pixel_width;
  1285. st->codec->height = track->video.pixel_height;
  1286. av_reduce(&st->sample_aspect_ratio.num,
  1287. &st->sample_aspect_ratio.den,
  1288. st->codec->height * track->video.display_width,
  1289. st->codec-> width * track->video.display_height,
  1290. 255);
  1291. if (st->codec->codec_id != CODEC_ID_H264)
  1292. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1293. if (track->default_duration)
  1294. st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
  1295. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1296. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1297. st->codec->sample_rate = track->audio.out_samplerate;
  1298. st->codec->channels = track->audio.channels;
  1299. if (st->codec->codec_id != CODEC_ID_AAC)
  1300. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1301. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1302. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1303. }
  1304. }
  1305. attachements = attachements_list->elem;
  1306. for (j=0; j<attachements_list->nb_elem; j++) {
  1307. if (!(attachements[j].filename && attachements[j].mime &&
  1308. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1309. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1310. } else {
  1311. AVStream *st = av_new_stream(s, 0);
  1312. if (st == NULL)
  1313. break;
  1314. av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
  1315. st->codec->codec_id = CODEC_ID_NONE;
  1316. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1317. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1318. if(st->codec->extradata == NULL)
  1319. break;
  1320. st->codec->extradata_size = attachements[j].bin.size;
  1321. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1322. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1323. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1324. strlen(ff_mkv_mime_tags[i].str))) {
  1325. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1326. break;
  1327. }
  1328. }
  1329. attachements[j].stream = st;
  1330. }
  1331. }
  1332. chapters = chapters_list->elem;
  1333. for (i=0; i<chapters_list->nb_elem; i++)
  1334. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1335. && (max_start==0 || chapters[i].start > max_start)) {
  1336. chapters[i].chapter =
  1337. ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1338. chapters[i].start, chapters[i].end,
  1339. chapters[i].title);
  1340. av_metadata_set2(&chapters[i].chapter->metadata,
  1341. "title", chapters[i].title, 0);
  1342. max_start = chapters[i].start;
  1343. }
  1344. index_list = &matroska->index;
  1345. index = index_list->elem;
  1346. if (index_list->nb_elem
  1347. && index[0].time > 100000000000000/matroska->time_scale) {
  1348. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1349. index_scale = matroska->time_scale;
  1350. }
  1351. for (i=0; i<index_list->nb_elem; i++) {
  1352. EbmlList *pos_list = &index[i].pos;
  1353. MatroskaIndexPos *pos = pos_list->elem;
  1354. for (j=0; j<pos_list->nb_elem; j++) {
  1355. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1356. pos[j].track);
  1357. if (track && track->stream)
  1358. av_add_index_entry(track->stream,
  1359. pos[j].pos + matroska->segment_start,
  1360. index[i].time/index_scale, 0, 0,
  1361. AVINDEX_KEYFRAME);
  1362. }
  1363. }
  1364. matroska_convert_tags(s);
  1365. return 0;
  1366. }
  1367. /*
  1368. * Put one packet in an application-supplied AVPacket struct.
  1369. * Returns 0 on success or -1 on failure.
  1370. */
  1371. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1372. AVPacket *pkt)
  1373. {
  1374. if (matroska->num_packets > 0) {
  1375. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1376. av_free(matroska->packets[0]);
  1377. if (matroska->num_packets > 1) {
  1378. memmove(&matroska->packets[0], &matroska->packets[1],
  1379. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1380. matroska->packets =
  1381. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  1382. sizeof(AVPacket *));
  1383. } else {
  1384. av_freep(&matroska->packets);
  1385. }
  1386. matroska->num_packets--;
  1387. return 0;
  1388. }
  1389. return -1;
  1390. }
  1391. /*
  1392. * Free all packets in our internal queue.
  1393. */
  1394. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1395. {
  1396. if (matroska->packets) {
  1397. int n;
  1398. for (n = 0; n < matroska->num_packets; n++) {
  1399. av_free_packet(matroska->packets[n]);
  1400. av_free(matroska->packets[n]);
  1401. }
  1402. av_freep(&matroska->packets);
  1403. matroska->num_packets = 0;
  1404. }
  1405. }
  1406. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1407. int size, int64_t pos, uint64_t cluster_time,
  1408. uint64_t duration, int is_keyframe,
  1409. int64_t cluster_pos)
  1410. {
  1411. uint64_t timecode = AV_NOPTS_VALUE;
  1412. MatroskaTrack *track;
  1413. int res = 0;
  1414. AVStream *st;
  1415. AVPacket *pkt;
  1416. int16_t block_time;
  1417. uint32_t *lace_size = NULL;
  1418. int n, flags, laces = 0;
  1419. uint64_t num;
  1420. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1421. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1422. return res;
  1423. }
  1424. data += n;
  1425. size -= n;
  1426. track = matroska_find_track_by_num(matroska, num);
  1427. if (size <= 3 || !track || !track->stream) {
  1428. av_log(matroska->ctx, AV_LOG_INFO,
  1429. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1430. return res;
  1431. }
  1432. st = track->stream;
  1433. if (st->discard >= AVDISCARD_ALL)
  1434. return res;
  1435. if (duration == AV_NOPTS_VALUE)
  1436. duration = track->default_duration / matroska->time_scale;
  1437. block_time = AV_RB16(data);
  1438. data += 2;
  1439. flags = *data++;
  1440. size -= 3;
  1441. if (is_keyframe == -1)
  1442. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1443. if (cluster_time != (uint64_t)-1
  1444. && (block_time >= 0 || cluster_time >= -block_time)) {
  1445. timecode = cluster_time + block_time;
  1446. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1447. && timecode < track->end_timecode)
  1448. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1449. if (is_keyframe)
  1450. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1451. track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
  1452. }
  1453. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1454. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1455. return res;
  1456. matroska->skip_to_keyframe = 0;
  1457. }
  1458. switch ((flags & 0x06) >> 1) {
  1459. case 0x0: /* no lacing */
  1460. laces = 1;
  1461. lace_size = av_mallocz(sizeof(int));
  1462. lace_size[0] = size;
  1463. break;
  1464. case 0x1: /* Xiph lacing */
  1465. case 0x2: /* fixed-size lacing */
  1466. case 0x3: /* EBML lacing */
  1467. assert(size>0); // size <=3 is checked before size-=3 above
  1468. laces = (*data) + 1;
  1469. data += 1;
  1470. size -= 1;
  1471. lace_size = av_mallocz(laces * sizeof(int));
  1472. switch ((flags & 0x06) >> 1) {
  1473. case 0x1: /* Xiph lacing */ {
  1474. uint8_t temp;
  1475. uint32_t total = 0;
  1476. for (n = 0; res == 0 && n < laces - 1; n++) {
  1477. while (1) {
  1478. if (size == 0) {
  1479. res = -1;
  1480. break;
  1481. }
  1482. temp = *data;
  1483. lace_size[n] += temp;
  1484. data += 1;
  1485. size -= 1;
  1486. if (temp != 0xff)
  1487. break;
  1488. }
  1489. total += lace_size[n];
  1490. }
  1491. lace_size[n] = size - total;
  1492. break;
  1493. }
  1494. case 0x2: /* fixed-size lacing */
  1495. for (n = 0; n < laces; n++)
  1496. lace_size[n] = size / laces;
  1497. break;
  1498. case 0x3: /* EBML lacing */ {
  1499. uint32_t total;
  1500. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1501. if (n < 0) {
  1502. av_log(matroska->ctx, AV_LOG_INFO,
  1503. "EBML block data error\n");
  1504. break;
  1505. }
  1506. data += n;
  1507. size -= n;
  1508. total = lace_size[0] = num;
  1509. for (n = 1; res == 0 && n < laces - 1; n++) {
  1510. int64_t snum;
  1511. int r;
  1512. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1513. if (r < 0) {
  1514. av_log(matroska->ctx, AV_LOG_INFO,
  1515. "EBML block data error\n");
  1516. break;
  1517. }
  1518. data += r;
  1519. size -= r;
  1520. lace_size[n] = lace_size[n - 1] + snum;
  1521. total += lace_size[n];
  1522. }
  1523. lace_size[n] = size - total;
  1524. break;
  1525. }
  1526. }
  1527. break;
  1528. }
  1529. if (res == 0) {
  1530. for (n = 0; n < laces; n++) {
  1531. if ((st->codec->codec_id == CODEC_ID_RA_288 ||
  1532. st->codec->codec_id == CODEC_ID_COOK ||
  1533. st->codec->codec_id == CODEC_ID_SIPR ||
  1534. st->codec->codec_id == CODEC_ID_ATRAC3) &&
  1535. st->codec->block_align && track->audio.sub_packet_size) {
  1536. int a = st->codec->block_align;
  1537. int sps = track->audio.sub_packet_size;
  1538. int cfs = track->audio.coded_framesize;
  1539. int h = track->audio.sub_packet_h;
  1540. int y = track->audio.sub_packet_cnt;
  1541. int w = track->audio.frame_size;
  1542. int x;
  1543. if (!track->audio.pkt_cnt) {
  1544. if (st->codec->codec_id == CODEC_ID_RA_288)
  1545. for (x=0; x<h/2; x++)
  1546. memcpy(track->audio.buf+x*2*w+y*cfs,
  1547. data+x*cfs, cfs);
  1548. else if (st->codec->codec_id == CODEC_ID_SIPR)
  1549. memcpy(track->audio.buf + y*w, data, w);
  1550. else
  1551. for (x=0; x<w/sps; x++)
  1552. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1553. if (++track->audio.sub_packet_cnt >= h) {
  1554. if (st->codec->codec_id == CODEC_ID_SIPR)
  1555. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1556. track->audio.sub_packet_cnt = 0;
  1557. track->audio.pkt_cnt = h*w / a;
  1558. }
  1559. }
  1560. while (track->audio.pkt_cnt) {
  1561. pkt = av_mallocz(sizeof(AVPacket));
  1562. av_new_packet(pkt, a);
  1563. memcpy(pkt->data, track->audio.buf
  1564. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1565. pkt->pos = pos;
  1566. pkt->stream_index = st->index;
  1567. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1568. }
  1569. } else {
  1570. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1571. int offset = 0, pkt_size = lace_size[n];
  1572. uint8_t *pkt_data = data;
  1573. if (pkt_size > size) {
  1574. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  1575. break;
  1576. }
  1577. if (encodings && encodings->scope & 1) {
  1578. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1579. if (offset < 0)
  1580. continue;
  1581. }
  1582. pkt = av_mallocz(sizeof(AVPacket));
  1583. /* XXX: prevent data copy... */
  1584. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1585. av_free(pkt);
  1586. res = AVERROR(ENOMEM);
  1587. break;
  1588. }
  1589. if (offset)
  1590. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1591. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1592. if (pkt_data != data)
  1593. av_free(pkt_data);
  1594. if (n == 0)
  1595. pkt->flags = is_keyframe;
  1596. pkt->stream_index = st->index;
  1597. if (track->ms_compat)
  1598. pkt->dts = timecode;
  1599. else
  1600. pkt->pts = timecode;
  1601. pkt->pos = pos;
  1602. if (st->codec->codec_id == CODEC_ID_TEXT)
  1603. pkt->convergence_duration = duration;
  1604. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1605. pkt->duration = duration;
  1606. if (st->codec->codec_id == CODEC_ID_SSA)
  1607. matroska_fix_ass_packet(matroska, pkt, duration);
  1608. if (matroska->prev_pkt &&
  1609. timecode != AV_NOPTS_VALUE &&
  1610. matroska->prev_pkt->pts == timecode &&
  1611. matroska->prev_pkt->stream_index == st->index &&
  1612. st->codec->codec_id == CODEC_ID_SSA)
  1613. matroska_merge_packets(matroska->prev_pkt, pkt);
  1614. else {
  1615. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1616. matroska->prev_pkt = pkt;
  1617. }
  1618. }
  1619. if (timecode != AV_NOPTS_VALUE)
  1620. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1621. data += lace_size[n];
  1622. size -= lace_size[n];
  1623. }
  1624. }
  1625. av_free(lace_size);
  1626. return res;
  1627. }
  1628. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1629. {
  1630. MatroskaCluster cluster = { 0 };
  1631. EbmlList *blocks_list;
  1632. MatroskaBlock *blocks;
  1633. int i, res;
  1634. int64_t pos = url_ftell(matroska->ctx->pb);
  1635. matroska->prev_pkt = NULL;
  1636. if (matroska->current_id)
  1637. pos -= 4; /* sizeof the ID which was already read */
  1638. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1639. blocks_list = &cluster.blocks;
  1640. blocks = blocks_list->elem;
  1641. for (i=0; i<blocks_list->nb_elem; i++)
  1642. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1643. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1644. res=matroska_parse_block(matroska,
  1645. blocks[i].bin.data, blocks[i].bin.size,
  1646. blocks[i].bin.pos, cluster.timecode,
  1647. blocks[i].duration, is_keyframe,
  1648. pos);
  1649. }
  1650. ebml_free(matroska_cluster, &cluster);
  1651. if (res < 0) matroska->done = 1;
  1652. return res;
  1653. }
  1654. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1655. {
  1656. MatroskaDemuxContext *matroska = s->priv_data;
  1657. while (matroska_deliver_packet(matroska, pkt)) {
  1658. if (matroska->done)
  1659. return AVERROR_EOF;
  1660. matroska_parse_cluster(matroska);
  1661. }
  1662. return 0;
  1663. }
  1664. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1665. int64_t timestamp, int flags)
  1666. {
  1667. MatroskaDemuxContext *matroska = s->priv_data;
  1668. MatroskaTrack *tracks = matroska->tracks.elem;
  1669. AVStream *st = s->streams[stream_index];
  1670. int i, index, index_sub, index_min;
  1671. if (!st->nb_index_entries)
  1672. return 0;
  1673. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1674. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1675. url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1676. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1677. matroska_clear_queue(matroska);
  1678. if (matroska_parse_cluster(matroska) < 0)
  1679. break;
  1680. }
  1681. }
  1682. matroska_clear_queue(matroska);
  1683. if (index < 0)
  1684. return 0;
  1685. index_min = index;
  1686. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1687. tracks[i].end_timecode = 0;
  1688. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  1689. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  1690. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  1691. if (index_sub >= 0
  1692. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  1693. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  1694. index_min = index_sub;
  1695. }
  1696. }
  1697. url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  1698. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1699. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  1700. matroska->done = 0;
  1701. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1702. return 0;
  1703. }
  1704. static int matroska_read_close(AVFormatContext *s)
  1705. {
  1706. MatroskaDemuxContext *matroska = s->priv_data;
  1707. MatroskaTrack *tracks = matroska->tracks.elem;
  1708. int n;
  1709. matroska_clear_queue(matroska);
  1710. for (n=0; n < matroska->tracks.nb_elem; n++)
  1711. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1712. av_free(tracks[n].audio.buf);
  1713. ebml_free(matroska_segment, matroska);
  1714. return 0;
  1715. }
  1716. AVInputFormat matroska_demuxer = {
  1717. "matroska,webm",
  1718. NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
  1719. sizeof(MatroskaDemuxContext),
  1720. matroska_probe,
  1721. matroska_read_header,
  1722. matroska_read_packet,
  1723. matroska_read_close,
  1724. matroska_read_seek,
  1725. };