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.

1950 lines
70KB

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