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.

2156 lines
77KB

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