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.

2043 lines
73KB

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