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.

2081 lines
76KB

  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. #if CONFIG_ZLIB
  44. #include <zlib.h>
  45. #endif
  46. #if CONFIG_BZLIB
  47. #include <bzlib.h>
  48. #endif
  49. typedef enum {
  50. EBML_NONE,
  51. EBML_UINT,
  52. EBML_FLOAT,
  53. EBML_STR,
  54. EBML_UTF8,
  55. EBML_BIN,
  56. EBML_NEST,
  57. EBML_PASS,
  58. EBML_STOP,
  59. EBML_TYPE_COUNT
  60. } EbmlType;
  61. typedef const struct EbmlSyntax {
  62. uint32_t id;
  63. EbmlType type;
  64. int list_elem_size;
  65. int data_offset;
  66. union {
  67. uint64_t u;
  68. double f;
  69. const char *s;
  70. const struct EbmlSyntax *n;
  71. } def;
  72. } EbmlSyntax;
  73. typedef struct {
  74. int nb_elem;
  75. void *elem;
  76. } EbmlList;
  77. typedef struct {
  78. int size;
  79. uint8_t *data;
  80. int64_t pos;
  81. } EbmlBin;
  82. typedef struct {
  83. uint64_t version;
  84. uint64_t max_size;
  85. uint64_t id_length;
  86. char *doctype;
  87. uint64_t doctype_version;
  88. } Ebml;
  89. typedef struct {
  90. uint64_t algo;
  91. EbmlBin settings;
  92. } MatroskaTrackCompression;
  93. typedef struct {
  94. uint64_t scope;
  95. uint64_t type;
  96. MatroskaTrackCompression compression;
  97. } MatroskaTrackEncoding;
  98. typedef struct {
  99. double frame_rate;
  100. uint64_t display_width;
  101. uint64_t display_height;
  102. uint64_t pixel_width;
  103. uint64_t pixel_height;
  104. uint64_t fourcc;
  105. uint64_t stereoMode;
  106. } MatroskaTrackVideo;
  107. typedef struct {
  108. double samplerate;
  109. double out_samplerate;
  110. uint64_t bitdepth;
  111. uint64_t channels;
  112. /* real audio header (extracted from extradata) */
  113. int coded_framesize;
  114. int sub_packet_h;
  115. int frame_size;
  116. int sub_packet_size;
  117. int sub_packet_cnt;
  118. int pkt_cnt;
  119. uint64_t buf_timecode;
  120. uint8_t *buf;
  121. } MatroskaTrackAudio;
  122. typedef struct {
  123. uint64_t uid;
  124. uint64_t type;
  125. } MatroskaTrackPlane;
  126. typedef struct {
  127. EbmlList combine_planes;
  128. /*EbmlList join_blocks;*/
  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_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
  266. { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, MATROSKA_VIDEO_STEREOMODE_MONO, offsetof(MatroskaTrackVideo,stereoMode) },
  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. data = (char *)data + syntax->data_offset;
  723. if (syntax->list_elem_size) {
  724. EbmlList *list = data;
  725. list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
  726. data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
  727. memset(data, 0, syntax->list_elem_size);
  728. list->nb_elem++;
  729. }
  730. if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
  731. matroska->current_id = 0;
  732. if ((res = ebml_read_length(matroska, pb, &length)) < 0)
  733. return res;
  734. if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
  735. av_log(matroska->ctx, AV_LOG_ERROR,
  736. "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
  737. length, max_lengths[syntax->type], syntax->type);
  738. return AVERROR_INVALIDDATA;
  739. }
  740. }
  741. switch (syntax->type) {
  742. case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
  743. case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
  744. case EBML_STR:
  745. case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
  746. case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
  747. case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
  748. return res;
  749. if (id == MATROSKA_ID_SEGMENT)
  750. matroska->segment_start = avio_tell(matroska->ctx->pb);
  751. return ebml_parse_nest(matroska, syntax->def.n, data);
  752. case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
  753. case EBML_STOP: return 1;
  754. default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
  755. }
  756. if (res == AVERROR_INVALIDDATA)
  757. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
  758. else if (res == AVERROR(EIO))
  759. av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
  760. return res;
  761. }
  762. static void ebml_free(EbmlSyntax *syntax, void *data)
  763. {
  764. int i, j;
  765. for (i=0; syntax[i].id; i++) {
  766. void *data_off = (char *)data + syntax[i].data_offset;
  767. switch (syntax[i].type) {
  768. case EBML_STR:
  769. case EBML_UTF8: av_freep(data_off); break;
  770. case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
  771. case EBML_NEST:
  772. if (syntax[i].list_elem_size) {
  773. EbmlList *list = data_off;
  774. char *ptr = list->elem;
  775. for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
  776. ebml_free(syntax[i].def.n, ptr);
  777. av_free(list->elem);
  778. } else
  779. ebml_free(syntax[i].def.n, data_off);
  780. default: break;
  781. }
  782. }
  783. }
  784. /*
  785. * Autodetecting...
  786. */
  787. static int matroska_probe(AVProbeData *p)
  788. {
  789. uint64_t total = 0;
  790. int len_mask = 0x80, size = 1, n = 1, i;
  791. /* EBML header? */
  792. if (AV_RB32(p->buf) != EBML_ID_HEADER)
  793. return 0;
  794. /* length of header */
  795. total = p->buf[4];
  796. while (size <= 8 && !(total & len_mask)) {
  797. size++;
  798. len_mask >>= 1;
  799. }
  800. if (size > 8)
  801. return 0;
  802. total &= (len_mask - 1);
  803. while (n < size)
  804. total = (total << 8) | p->buf[4 + n++];
  805. /* Does the probe data contain the whole header? */
  806. if (p->buf_size < 4 + size + total)
  807. return 0;
  808. /* The header should contain a known document type. For now,
  809. * we don't parse the whole header but simply check for the
  810. * availability of that array of characters inside the header.
  811. * Not fully fool-proof, but good enough. */
  812. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
  813. int probelen = strlen(matroska_doctypes[i]);
  814. for (n = 4+size; n <= 4+size+total-probelen; n++)
  815. if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
  816. return AVPROBE_SCORE_MAX;
  817. }
  818. // probably valid EBML header but no recognized doctype
  819. return AVPROBE_SCORE_MAX/2;
  820. }
  821. static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
  822. int num)
  823. {
  824. MatroskaTrack *tracks = matroska->tracks.elem;
  825. int i;
  826. for (i=0; i < matroska->tracks.nb_elem; i++)
  827. if (tracks[i].num == num)
  828. return &tracks[i];
  829. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
  830. return NULL;
  831. }
  832. static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
  833. MatroskaTrack *track)
  834. {
  835. MatroskaTrackEncoding *encodings = track->encodings.elem;
  836. uint8_t* data = *buf;
  837. int isize = *buf_size;
  838. uint8_t* pkt_data = NULL;
  839. int pkt_size = isize;
  840. int result = 0;
  841. int olen;
  842. if (pkt_size >= 10000000)
  843. return -1;
  844. switch (encodings[0].compression.algo) {
  845. case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
  846. return encodings[0].compression.settings.size;
  847. case MATROSKA_TRACK_ENCODING_COMP_LZO:
  848. do {
  849. olen = pkt_size *= 3;
  850. pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
  851. result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
  852. } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
  853. if (result)
  854. goto failed;
  855. pkt_size -= olen;
  856. break;
  857. #if CONFIG_ZLIB
  858. case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
  859. z_stream zstream = {0};
  860. if (inflateInit(&zstream) != Z_OK)
  861. return -1;
  862. zstream.next_in = data;
  863. zstream.avail_in = isize;
  864. do {
  865. pkt_size *= 3;
  866. pkt_data = av_realloc(pkt_data, pkt_size);
  867. zstream.avail_out = pkt_size - zstream.total_out;
  868. zstream.next_out = pkt_data + zstream.total_out;
  869. result = inflate(&zstream, Z_NO_FLUSH);
  870. } while (result==Z_OK && pkt_size<10000000);
  871. pkt_size = zstream.total_out;
  872. inflateEnd(&zstream);
  873. if (result != Z_STREAM_END)
  874. goto failed;
  875. break;
  876. }
  877. #endif
  878. #if CONFIG_BZLIB
  879. case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
  880. bz_stream bzstream = {0};
  881. if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
  882. return -1;
  883. bzstream.next_in = data;
  884. bzstream.avail_in = isize;
  885. do {
  886. pkt_size *= 3;
  887. pkt_data = av_realloc(pkt_data, pkt_size);
  888. bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
  889. bzstream.next_out = pkt_data + bzstream.total_out_lo32;
  890. result = BZ2_bzDecompress(&bzstream);
  891. } while (result==BZ_OK && pkt_size<10000000);
  892. pkt_size = bzstream.total_out_lo32;
  893. BZ2_bzDecompressEnd(&bzstream);
  894. if (result != BZ_STREAM_END)
  895. goto failed;
  896. break;
  897. }
  898. #endif
  899. default:
  900. return -1;
  901. }
  902. *buf = pkt_data;
  903. *buf_size = pkt_size;
  904. return 0;
  905. failed:
  906. av_free(pkt_data);
  907. return -1;
  908. }
  909. static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
  910. AVPacket *pkt, uint64_t display_duration)
  911. {
  912. char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
  913. for (; *ptr!=',' && ptr<end-1; ptr++);
  914. if (*ptr == ',')
  915. layer = ++ptr;
  916. for (; *ptr!=',' && ptr<end-1; ptr++);
  917. if (*ptr == ',') {
  918. int64_t end_pts = pkt->pts + display_duration;
  919. int sc = matroska->time_scale * pkt->pts / 10000000;
  920. int ec = matroska->time_scale * end_pts / 10000000;
  921. int sh, sm, ss, eh, em, es, len;
  922. sh = sc/360000; sc -= 360000*sh;
  923. sm = sc/ 6000; sc -= 6000*sm;
  924. ss = sc/ 100; sc -= 100*ss;
  925. eh = ec/360000; ec -= 360000*eh;
  926. em = ec/ 6000; ec -= 6000*em;
  927. es = ec/ 100; ec -= 100*es;
  928. *ptr++ = '\0';
  929. len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
  930. if (!(line = av_malloc(len)))
  931. return;
  932. snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
  933. layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
  934. av_free(pkt->data);
  935. pkt->data = line;
  936. pkt->size = strlen(line);
  937. }
  938. }
  939. static void matroska_merge_packets(AVPacket *out, AVPacket *in)
  940. {
  941. out->data = av_realloc(out->data, out->size+in->size);
  942. memcpy(out->data+out->size, in->data, in->size);
  943. out->size += in->size;
  944. av_destruct_packet(in);
  945. av_free(in);
  946. }
  947. static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
  948. AVMetadata **metadata, char *prefix)
  949. {
  950. MatroskaTag *tags = list->elem;
  951. char key[1024];
  952. int i;
  953. for (i=0; i < list->nb_elem; i++) {
  954. const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
  955. if (!tags[i].name) {
  956. av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
  957. continue;
  958. }
  959. if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
  960. else av_strlcpy(key, tags[i].name, sizeof(key));
  961. if (tags[i].def || !lang) {
  962. av_metadata_set2(metadata, key, tags[i].string, 0);
  963. if (tags[i].sub.nb_elem)
  964. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  965. }
  966. if (lang) {
  967. av_strlcat(key, "-", sizeof(key));
  968. av_strlcat(key, lang, sizeof(key));
  969. av_metadata_set2(metadata, key, tags[i].string, 0);
  970. if (tags[i].sub.nb_elem)
  971. matroska_convert_tag(s, &tags[i].sub, metadata, key);
  972. }
  973. }
  974. ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
  975. }
  976. static void matroska_convert_tags(AVFormatContext *s)
  977. {
  978. MatroskaDemuxContext *matroska = s->priv_data;
  979. MatroskaTags *tags = matroska->tags.elem;
  980. int i, j;
  981. for (i=0; i < matroska->tags.nb_elem; i++) {
  982. if (tags[i].target.attachuid) {
  983. MatroskaAttachement *attachment = matroska->attachments.elem;
  984. for (j=0; j<matroska->attachments.nb_elem; j++)
  985. if (attachment[j].uid == tags[i].target.attachuid
  986. && attachment[j].stream)
  987. matroska_convert_tag(s, &tags[i].tag,
  988. &attachment[j].stream->metadata, NULL);
  989. } else if (tags[i].target.chapteruid) {
  990. MatroskaChapter *chapter = matroska->chapters.elem;
  991. for (j=0; j<matroska->chapters.nb_elem; j++)
  992. if (chapter[j].uid == tags[i].target.chapteruid
  993. && chapter[j].chapter)
  994. matroska_convert_tag(s, &tags[i].tag,
  995. &chapter[j].chapter->metadata, NULL);
  996. } else if (tags[i].target.trackuid) {
  997. MatroskaTrack *track = matroska->tracks.elem;
  998. for (j=0; j<matroska->tracks.nb_elem; j++)
  999. if (track[j].uid == tags[i].target.trackuid && track[j].stream)
  1000. matroska_convert_tag(s, &tags[i].tag,
  1001. &track[j].stream->metadata, NULL);
  1002. } else {
  1003. matroska_convert_tag(s, &tags[i].tag, &s->metadata,
  1004. tags[i].target.type);
  1005. }
  1006. }
  1007. }
  1008. static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
  1009. {
  1010. EbmlList *seekhead_list = &matroska->seekhead;
  1011. MatroskaSeekhead *seekhead = seekhead_list->elem;
  1012. uint32_t level_up = matroska->level_up;
  1013. int64_t before_pos = avio_tell(matroska->ctx->pb);
  1014. uint32_t saved_id = matroska->current_id;
  1015. MatroskaLevel level;
  1016. int i;
  1017. // we should not do any seeking in the streaming case
  1018. if (!matroska->ctx->pb->seekable ||
  1019. (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
  1020. return;
  1021. for (i=0; i<seekhead_list->nb_elem; i++) {
  1022. int64_t offset = seekhead[i].pos + matroska->segment_start;
  1023. if (seekhead[i].pos <= before_pos
  1024. || seekhead[i].id == MATROSKA_ID_SEEKHEAD
  1025. || seekhead[i].id == MATROSKA_ID_CLUSTER)
  1026. continue;
  1027. /* seek */
  1028. if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) != offset)
  1029. continue;
  1030. /* We don't want to lose our seekhead level, so we add
  1031. * a dummy. This is a crude hack. */
  1032. if (matroska->num_levels == EBML_MAX_DEPTH) {
  1033. av_log(matroska->ctx, AV_LOG_INFO,
  1034. "Max EBML element depth (%d) reached, "
  1035. "cannot parse further.\n", EBML_MAX_DEPTH);
  1036. break;
  1037. }
  1038. level.start = 0;
  1039. level.length = (uint64_t)-1;
  1040. matroska->levels[matroska->num_levels] = level;
  1041. matroska->num_levels++;
  1042. matroska->current_id = 0;
  1043. ebml_parse(matroska, matroska_segment, matroska);
  1044. /* remove dummy level */
  1045. while (matroska->num_levels) {
  1046. uint64_t length = matroska->levels[--matroska->num_levels].length;
  1047. if (length == (uint64_t)-1)
  1048. break;
  1049. }
  1050. }
  1051. /* seek back */
  1052. avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
  1053. matroska->level_up = level_up;
  1054. matroska->current_id = saved_id;
  1055. }
  1056. static int matroska_aac_profile(char *codec_id)
  1057. {
  1058. static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
  1059. int profile;
  1060. for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
  1061. if (strstr(codec_id, aac_profiles[profile]))
  1062. break;
  1063. return profile + 1;
  1064. }
  1065. static int matroska_aac_sri(int samplerate)
  1066. {
  1067. int sri;
  1068. for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
  1069. if (ff_mpeg4audio_sample_rates[sri] == samplerate)
  1070. break;
  1071. return sri;
  1072. }
  1073. static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1074. {
  1075. MatroskaDemuxContext *matroska = s->priv_data;
  1076. EbmlList *attachements_list = &matroska->attachments;
  1077. MatroskaAttachement *attachements;
  1078. EbmlList *chapters_list = &matroska->chapters;
  1079. MatroskaChapter *chapters;
  1080. MatroskaTrack *tracks;
  1081. EbmlList *combined_list;
  1082. MatroskaTrackPlane *planes;
  1083. char stereo_str[256];
  1084. EbmlList *index_list;
  1085. MatroskaIndex *index;
  1086. int index_scale = 1;
  1087. uint64_t max_start = 0;
  1088. Ebml ebml = { 0 };
  1089. AVStream *st;
  1090. int i, j, res;
  1091. matroska->ctx = s;
  1092. /* First read the EBML header. */
  1093. if (ebml_parse(matroska, ebml_syntax, &ebml)
  1094. || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
  1095. || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3) {
  1096. av_log(matroska->ctx, AV_LOG_ERROR,
  1097. "EBML header using unsupported features\n"
  1098. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1099. ebml.version, ebml.doctype, ebml.doctype_version);
  1100. ebml_free(ebml_syntax, &ebml);
  1101. return AVERROR_PATCHWELCOME;
  1102. } else if (ebml.doctype_version == 3) {
  1103. av_log(matroska->ctx, AV_LOG_WARNING,
  1104. "EBML header using unsupported features\n"
  1105. "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
  1106. ebml.version, ebml.doctype, ebml.doctype_version);
  1107. }
  1108. for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
  1109. if (!strcmp(ebml.doctype, matroska_doctypes[i]))
  1110. break;
  1111. if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
  1112. av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
  1113. }
  1114. ebml_free(ebml_syntax, &ebml);
  1115. /* The next thing is a segment. */
  1116. if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
  1117. return res;
  1118. matroska_execute_seekhead(matroska);
  1119. if (!matroska->time_scale)
  1120. matroska->time_scale = 1000000;
  1121. if (matroska->duration)
  1122. matroska->ctx->duration = matroska->duration * matroska->time_scale
  1123. * 1000 / AV_TIME_BASE;
  1124. av_metadata_set2(&s->metadata, "title", matroska->title, 0);
  1125. tracks = matroska->tracks.elem;
  1126. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1127. MatroskaTrack *track = &tracks[i];
  1128. enum CodecID codec_id = CODEC_ID_NONE;
  1129. EbmlList *encodings_list = &tracks->encodings;
  1130. MatroskaTrackEncoding *encodings = encodings_list->elem;
  1131. uint8_t *extradata = NULL;
  1132. int extradata_size = 0;
  1133. int extradata_offset = 0;
  1134. AVIOContext b;
  1135. /* Apply some sanity checks. */
  1136. if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
  1137. track->type != MATROSKA_TRACK_TYPE_AUDIO &&
  1138. track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1139. av_log(matroska->ctx, AV_LOG_INFO,
  1140. "Unknown or unsupported track type %"PRIu64"\n",
  1141. track->type);
  1142. continue;
  1143. }
  1144. if (track->codec_id == NULL)
  1145. continue;
  1146. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1147. if (!track->default_duration)
  1148. track->default_duration = 1000000000/track->video.frame_rate;
  1149. if (!track->video.display_width)
  1150. track->video.display_width = track->video.pixel_width;
  1151. if (!track->video.display_height)
  1152. track->video.display_height = track->video.pixel_height;
  1153. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1154. if (!track->audio.out_samplerate)
  1155. track->audio.out_samplerate = track->audio.samplerate;
  1156. }
  1157. if (encodings_list->nb_elem > 1) {
  1158. av_log(matroska->ctx, AV_LOG_ERROR,
  1159. "Multiple combined encodings no supported");
  1160. } else if (encodings_list->nb_elem == 1) {
  1161. if (encodings[0].type ||
  1162. (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
  1163. #if CONFIG_ZLIB
  1164. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
  1165. #endif
  1166. #if CONFIG_BZLIB
  1167. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
  1168. #endif
  1169. encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
  1170. encodings[0].scope = 0;
  1171. av_log(matroska->ctx, AV_LOG_ERROR,
  1172. "Unsupported encoding type");
  1173. } else if (track->codec_priv.size && encodings[0].scope&2) {
  1174. uint8_t *codec_priv = track->codec_priv.data;
  1175. int offset = matroska_decode_buffer(&track->codec_priv.data,
  1176. &track->codec_priv.size,
  1177. track);
  1178. if (offset < 0) {
  1179. track->codec_priv.data = NULL;
  1180. track->codec_priv.size = 0;
  1181. av_log(matroska->ctx, AV_LOG_ERROR,
  1182. "Failed to decode codec private data\n");
  1183. } else if (offset > 0) {
  1184. track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
  1185. memcpy(track->codec_priv.data,
  1186. encodings[0].compression.settings.data, offset);
  1187. memcpy(track->codec_priv.data+offset, codec_priv,
  1188. track->codec_priv.size);
  1189. track->codec_priv.size += offset;
  1190. }
  1191. if (codec_priv != track->codec_priv.data)
  1192. av_free(codec_priv);
  1193. }
  1194. }
  1195. for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
  1196. if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
  1197. strlen(ff_mkv_codec_tags[j].str))){
  1198. codec_id= ff_mkv_codec_tags[j].id;
  1199. break;
  1200. }
  1201. }
  1202. st = track->stream = av_new_stream(s, 0);
  1203. if (st == NULL)
  1204. return AVERROR(ENOMEM);
  1205. if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
  1206. && track->codec_priv.size >= 40
  1207. && track->codec_priv.data != NULL) {
  1208. track->ms_compat = 1;
  1209. track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
  1210. codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
  1211. extradata_offset = 40;
  1212. } else if (!strcmp(track->codec_id, "A_MS/ACM")
  1213. && track->codec_priv.size >= 14
  1214. && track->codec_priv.data != NULL) {
  1215. int ret;
  1216. ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
  1217. AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
  1218. ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
  1219. if (ret < 0)
  1220. return ret;
  1221. codec_id = st->codec->codec_id;
  1222. extradata_offset = FFMIN(track->codec_priv.size, 18);
  1223. } else if (!strcmp(track->codec_id, "V_QUICKTIME")
  1224. && (track->codec_priv.size >= 86)
  1225. && (track->codec_priv.data != NULL)) {
  1226. track->video.fourcc = AV_RL32(track->codec_priv.data);
  1227. codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
  1228. } else if (codec_id == CODEC_ID_PCM_S16BE) {
  1229. switch (track->audio.bitdepth) {
  1230. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1231. case 24: codec_id = CODEC_ID_PCM_S24BE; break;
  1232. case 32: codec_id = CODEC_ID_PCM_S32BE; break;
  1233. }
  1234. } else if (codec_id == CODEC_ID_PCM_S16LE) {
  1235. switch (track->audio.bitdepth) {
  1236. case 8: codec_id = CODEC_ID_PCM_U8; break;
  1237. case 24: codec_id = CODEC_ID_PCM_S24LE; break;
  1238. case 32: codec_id = CODEC_ID_PCM_S32LE; break;
  1239. }
  1240. } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
  1241. codec_id = CODEC_ID_PCM_F64LE;
  1242. } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
  1243. int profile = matroska_aac_profile(track->codec_id);
  1244. int sri = matroska_aac_sri(track->audio.samplerate);
  1245. extradata = av_malloc(5);
  1246. if (extradata == NULL)
  1247. return AVERROR(ENOMEM);
  1248. extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
  1249. extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
  1250. if (strstr(track->codec_id, "SBR")) {
  1251. sri = matroska_aac_sri(track->audio.out_samplerate);
  1252. extradata[2] = 0x56;
  1253. extradata[3] = 0xE5;
  1254. extradata[4] = 0x80 | (sri<<3);
  1255. extradata_size = 5;
  1256. } else
  1257. extradata_size = 2;
  1258. } else if (codec_id == CODEC_ID_TTA) {
  1259. extradata_size = 30;
  1260. extradata = av_mallocz(extradata_size);
  1261. if (extradata == NULL)
  1262. return AVERROR(ENOMEM);
  1263. ffio_init_context(&b, extradata, extradata_size, 1,
  1264. NULL, NULL, NULL, NULL);
  1265. avio_write(&b, "TTA1", 4);
  1266. avio_wl16(&b, 1);
  1267. avio_wl16(&b, track->audio.channels);
  1268. avio_wl16(&b, track->audio.bitdepth);
  1269. avio_wl32(&b, track->audio.out_samplerate);
  1270. avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
  1271. } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
  1272. codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
  1273. extradata_offset = 26;
  1274. } else if (codec_id == CODEC_ID_RA_144) {
  1275. track->audio.out_samplerate = 8000;
  1276. track->audio.channels = 1;
  1277. } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
  1278. codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
  1279. int flavor;
  1280. ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
  1281. 0, NULL, NULL, NULL, NULL);
  1282. avio_skip(&b, 22);
  1283. flavor = avio_rb16(&b);
  1284. track->audio.coded_framesize = avio_rb32(&b);
  1285. avio_skip(&b, 12);
  1286. track->audio.sub_packet_h = avio_rb16(&b);
  1287. track->audio.frame_size = avio_rb16(&b);
  1288. track->audio.sub_packet_size = avio_rb16(&b);
  1289. track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
  1290. if (codec_id == CODEC_ID_RA_288) {
  1291. st->codec->block_align = track->audio.coded_framesize;
  1292. track->codec_priv.size = 0;
  1293. } else {
  1294. if (codec_id == CODEC_ID_SIPR && flavor < 4) {
  1295. const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
  1296. track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
  1297. st->codec->bit_rate = sipr_bit_rate[flavor];
  1298. }
  1299. st->codec->block_align = track->audio.sub_packet_size;
  1300. extradata_offset = 78;
  1301. }
  1302. }
  1303. track->codec_priv.size -= extradata_offset;
  1304. if (codec_id == CODEC_ID_NONE)
  1305. av_log(matroska->ctx, AV_LOG_INFO,
  1306. "Unknown/unsupported CodecID %s.\n", track->codec_id);
  1307. if (track->time_scale < 0.01)
  1308. track->time_scale = 1.0;
  1309. av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
  1310. st->codec->codec_id = codec_id;
  1311. st->start_time = 0;
  1312. if (strcmp(track->language, "und"))
  1313. av_metadata_set2(&st->metadata, "language", track->language, 0);
  1314. av_metadata_set2(&st->metadata, "title", track->name, 0);
  1315. if (track->flag_default)
  1316. st->disposition |= AV_DISPOSITION_DEFAULT;
  1317. if (track->flag_forced)
  1318. st->disposition |= AV_DISPOSITION_FORCED;
  1319. if (track->default_duration)
  1320. av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
  1321. track->default_duration, 1000000000, 30000);
  1322. if (!st->codec->extradata) {
  1323. if(extradata){
  1324. st->codec->extradata = extradata;
  1325. st->codec->extradata_size = extradata_size;
  1326. } else if(track->codec_priv.data && track->codec_priv.size > 0){
  1327. st->codec->extradata = av_mallocz(track->codec_priv.size +
  1328. FF_INPUT_BUFFER_PADDING_SIZE);
  1329. if(st->codec->extradata == NULL)
  1330. return AVERROR(ENOMEM);
  1331. st->codec->extradata_size = track->codec_priv.size;
  1332. memcpy(st->codec->extradata,
  1333. track->codec_priv.data + extradata_offset,
  1334. track->codec_priv.size);
  1335. }
  1336. }
  1337. if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
  1338. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1339. st->codec->codec_tag = track->video.fourcc;
  1340. st->codec->width = track->video.pixel_width;
  1341. st->codec->height = track->video.pixel_height;
  1342. av_reduce(&st->sample_aspect_ratio.num,
  1343. &st->sample_aspect_ratio.den,
  1344. st->codec->height * track->video.display_width,
  1345. st->codec-> width * track->video.display_height,
  1346. 255);
  1347. if (st->codec->codec_id != CODEC_ID_H264)
  1348. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1349. if (track->default_duration)
  1350. st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
  1351. /* restore stereo mode flag as metadata tag */
  1352. switch (track->video.stereoMode) {
  1353. case MATROSKA_VIDEO_STEREOMODE_LEFT_RIGHT:
  1354. av_metadata_set2(&st->metadata, "STEREO_MODE", "left_right", 0);
  1355. break;
  1356. case MATROSKA_VIDEO_STEREOMODE_BOTTOM_TOP:
  1357. av_metadata_set2(&st->metadata, "STEREO_MODE", "bottom_top", 0);
  1358. break;
  1359. case MATROSKA_VIDEO_STEREOMODE_TOP_BOTTOM:
  1360. av_metadata_set2(&st->metadata, "STEREO_MODE", "top_bottom", 0);
  1361. break;
  1362. case MATROSKA_VIDEO_STEREOMODE_CHECKERBOARD_RL:
  1363. av_metadata_set2(&st->metadata, "STEREO_MODE", "checkerboard_rl", 0);
  1364. break;
  1365. case MATROSKA_VIDEO_STEREOMODE_CHECKERBOARD_LR:
  1366. av_metadata_set2(&st->metadata, "STEREO_MODE", "checkerboard_lr", 0);
  1367. break;
  1368. case MATROSKA_VIDEO_STEREOMODE_ROW_INTERLEAVED_RL:
  1369. av_metadata_set2(&st->metadata, "STEREO_MODE", "row_interleaved_rl", 0);
  1370. break;
  1371. case MATROSKA_VIDEO_STEREOMODE_ROW_INTERLEAVED_LR:
  1372. av_metadata_set2(&st->metadata, "STEREO_MODE", "row_interleaved_lr", 0);
  1373. break;
  1374. case MATROSKA_VIDEO_STEREOMODE_COL_INTERLEAVED_RL:
  1375. av_metadata_set2(&st->metadata, "STEREO_MODE", "col_interleaved_rl", 0);
  1376. break;
  1377. case MATROSKA_VIDEO_STEREOMODE_COL_INTERLEAVED_LR:
  1378. av_metadata_set2(&st->metadata, "STEREO_MODE", "col_interleaved_lr", 0);
  1379. break;
  1380. case MATROSKA_VIDEO_STEREOMODE_ANAGLYPH_CYAN_RED:
  1381. av_metadata_set2(&st->metadata, "STEREO_MODE", "anaglyph_cyan_red", 0);
  1382. break;
  1383. case MATROSKA_VIDEO_STEREOMODE_RIGHT_LEFT:
  1384. av_metadata_set2(&st->metadata, "STEREO_MODE", "right_left", 0);
  1385. break;
  1386. case MATROSKA_VIDEO_STEREOMODE_ANAGLYPH_GREEN_MAG:
  1387. av_metadata_set2(&st->metadata, "STEREO_MODE", "anaglyph_green_magenta", 0);
  1388. break;
  1389. case MATROSKA_VIDEO_STEREOMODE_BOTH_EYES_BLOCK_LR:
  1390. av_metadata_set2(&st->metadata, "STEREO_MODE", "block_lr", 0);
  1391. break;
  1392. case MATROSKA_VIDEO_STEREOMODE_BOTH_EYES_BLOCK_RL:
  1393. av_metadata_set2(&st->metadata, "STEREO_MODE", "block_rl", 0);
  1394. break;
  1395. case MATROSKA_VIDEO_STEREOMODE_MONO:
  1396. default:
  1397. /**av_metadata_set2(&st->metadata, "STEREO_MODE", "mono", 0);*/
  1398. break;
  1399. }
  1400. /* if we have virtual track - mark the real tracks */
  1401. combined_list = &track->operation.combine_planes;
  1402. planes = combined_list->elem;
  1403. for (int plane_id = 0; plane_id < combined_list->nb_elem; ++plane_id) {
  1404. switch (planes[plane_id].type) {
  1405. case 0: {
  1406. snprintf(stereo_str, sizeof(stereo_str), "left_%d", i);
  1407. break;
  1408. }
  1409. case 1: {
  1410. snprintf(stereo_str, sizeof(stereo_str), "right_%d", i);
  1411. break;
  1412. }
  1413. case 2: {
  1414. snprintf(stereo_str, sizeof(stereo_str), "background_%d", i);
  1415. break;
  1416. }
  1417. default: {
  1418. continue;
  1419. }
  1420. }
  1421. for (int track_id = 0; track_id < matroska->tracks.nb_elem && track_id < i; ++track_id) {
  1422. MatroskaTrack *check_track = &tracks[track_id];
  1423. if (planes[plane_id].uid == check_track->uid) {
  1424. av_metadata_set2(&s->streams[track_id]->metadata, "STEREO_MODE", stereo_str, 0);
  1425. break;
  1426. }
  1427. }
  1428. }
  1429. } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
  1430. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1431. st->codec->sample_rate = track->audio.out_samplerate;
  1432. st->codec->channels = track->audio.channels;
  1433. if (st->codec->codec_id != CODEC_ID_AAC)
  1434. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1435. } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
  1436. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1437. }
  1438. }
  1439. attachements = attachements_list->elem;
  1440. for (j=0; j<attachements_list->nb_elem; j++) {
  1441. if (!(attachements[j].filename && attachements[j].mime &&
  1442. attachements[j].bin.data && attachements[j].bin.size > 0)) {
  1443. av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
  1444. } else {
  1445. AVStream *st = av_new_stream(s, 0);
  1446. if (st == NULL)
  1447. break;
  1448. av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
  1449. st->codec->codec_id = CODEC_ID_NONE;
  1450. st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
  1451. st->codec->extradata = av_malloc(attachements[j].bin.size);
  1452. if(st->codec->extradata == NULL)
  1453. break;
  1454. st->codec->extradata_size = attachements[j].bin.size;
  1455. memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
  1456. for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
  1457. if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
  1458. strlen(ff_mkv_mime_tags[i].str))) {
  1459. st->codec->codec_id = ff_mkv_mime_tags[i].id;
  1460. break;
  1461. }
  1462. }
  1463. attachements[j].stream = st;
  1464. }
  1465. }
  1466. chapters = chapters_list->elem;
  1467. for (i=0; i<chapters_list->nb_elem; i++)
  1468. if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
  1469. && (max_start==0 || chapters[i].start > max_start)) {
  1470. chapters[i].chapter =
  1471. ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
  1472. chapters[i].start, chapters[i].end,
  1473. chapters[i].title);
  1474. av_metadata_set2(&chapters[i].chapter->metadata,
  1475. "title", chapters[i].title, 0);
  1476. max_start = chapters[i].start;
  1477. }
  1478. index_list = &matroska->index;
  1479. index = index_list->elem;
  1480. if (index_list->nb_elem
  1481. && index[0].time > 100000000000000/matroska->time_scale) {
  1482. av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
  1483. index_scale = matroska->time_scale;
  1484. }
  1485. for (i=0; i<index_list->nb_elem; i++) {
  1486. EbmlList *pos_list = &index[i].pos;
  1487. MatroskaIndexPos *pos = pos_list->elem;
  1488. for (j=0; j<pos_list->nb_elem; j++) {
  1489. MatroskaTrack *track = matroska_find_track_by_num(matroska,
  1490. pos[j].track);
  1491. if (track && track->stream)
  1492. av_add_index_entry(track->stream,
  1493. pos[j].pos + matroska->segment_start,
  1494. index[i].time/index_scale, 0, 0,
  1495. AVINDEX_KEYFRAME);
  1496. }
  1497. }
  1498. matroska_convert_tags(s);
  1499. return 0;
  1500. }
  1501. /*
  1502. * Put one packet in an application-supplied AVPacket struct.
  1503. * Returns 0 on success or -1 on failure.
  1504. */
  1505. static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
  1506. AVPacket *pkt)
  1507. {
  1508. if (matroska->num_packets > 0) {
  1509. memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
  1510. av_free(matroska->packets[0]);
  1511. if (matroska->num_packets > 1) {
  1512. memmove(&matroska->packets[0], &matroska->packets[1],
  1513. (matroska->num_packets - 1) * sizeof(AVPacket *));
  1514. matroska->packets =
  1515. av_realloc(matroska->packets, (matroska->num_packets - 1) *
  1516. sizeof(AVPacket *));
  1517. } else {
  1518. av_freep(&matroska->packets);
  1519. }
  1520. matroska->num_packets--;
  1521. return 0;
  1522. }
  1523. return -1;
  1524. }
  1525. /*
  1526. * Free all packets in our internal queue.
  1527. */
  1528. static void matroska_clear_queue(MatroskaDemuxContext *matroska)
  1529. {
  1530. if (matroska->packets) {
  1531. int n;
  1532. for (n = 0; n < matroska->num_packets; n++) {
  1533. av_free_packet(matroska->packets[n]);
  1534. av_free(matroska->packets[n]);
  1535. }
  1536. av_freep(&matroska->packets);
  1537. matroska->num_packets = 0;
  1538. }
  1539. }
  1540. static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
  1541. int size, int64_t pos, uint64_t cluster_time,
  1542. uint64_t duration, int is_keyframe,
  1543. int64_t cluster_pos)
  1544. {
  1545. uint64_t timecode = AV_NOPTS_VALUE;
  1546. MatroskaTrack *track;
  1547. int res = 0;
  1548. AVStream *st;
  1549. AVPacket *pkt;
  1550. int16_t block_time;
  1551. uint32_t *lace_size = NULL;
  1552. int n, flags, laces = 0;
  1553. uint64_t num;
  1554. if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
  1555. av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
  1556. return res;
  1557. }
  1558. data += n;
  1559. size -= n;
  1560. track = matroska_find_track_by_num(matroska, num);
  1561. if (size <= 3 || !track || !track->stream) {
  1562. av_log(matroska->ctx, AV_LOG_INFO,
  1563. "Invalid stream %"PRIu64" or size %u\n", num, size);
  1564. return res;
  1565. }
  1566. st = track->stream;
  1567. if (st->discard >= AVDISCARD_ALL)
  1568. return res;
  1569. if (!duration)
  1570. duration = track->default_duration / matroska->time_scale;
  1571. block_time = AV_RB16(data);
  1572. data += 2;
  1573. flags = *data++;
  1574. size -= 3;
  1575. if (is_keyframe == -1)
  1576. is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
  1577. if (cluster_time != (uint64_t)-1
  1578. && (block_time >= 0 || cluster_time >= -block_time)) {
  1579. timecode = cluster_time + block_time;
  1580. if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
  1581. && timecode < track->end_timecode)
  1582. is_keyframe = 0; /* overlapping subtitles are not key frame */
  1583. if (is_keyframe)
  1584. av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
  1585. track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
  1586. }
  1587. if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
  1588. if (!is_keyframe || timecode < matroska->skip_to_timecode)
  1589. return res;
  1590. matroska->skip_to_keyframe = 0;
  1591. }
  1592. switch ((flags & 0x06) >> 1) {
  1593. case 0x0: /* no lacing */
  1594. laces = 1;
  1595. lace_size = av_mallocz(sizeof(int));
  1596. lace_size[0] = size;
  1597. break;
  1598. case 0x1: /* Xiph lacing */
  1599. case 0x2: /* fixed-size lacing */
  1600. case 0x3: /* EBML lacing */
  1601. assert(size>0); // size <=3 is checked before size-=3 above
  1602. laces = (*data) + 1;
  1603. data += 1;
  1604. size -= 1;
  1605. lace_size = av_mallocz(laces * sizeof(int));
  1606. switch ((flags & 0x06) >> 1) {
  1607. case 0x1: /* Xiph lacing */ {
  1608. uint8_t temp;
  1609. uint32_t total = 0;
  1610. for (n = 0; res == 0 && n < laces - 1; n++) {
  1611. while (1) {
  1612. if (size == 0) {
  1613. res = -1;
  1614. break;
  1615. }
  1616. temp = *data;
  1617. lace_size[n] += temp;
  1618. data += 1;
  1619. size -= 1;
  1620. if (temp != 0xff)
  1621. break;
  1622. }
  1623. total += lace_size[n];
  1624. }
  1625. lace_size[n] = size - total;
  1626. break;
  1627. }
  1628. case 0x2: /* fixed-size lacing */
  1629. for (n = 0; n < laces; n++)
  1630. lace_size[n] = size / laces;
  1631. break;
  1632. case 0x3: /* EBML lacing */ {
  1633. uint32_t total;
  1634. n = matroska_ebmlnum_uint(matroska, data, size, &num);
  1635. if (n < 0) {
  1636. av_log(matroska->ctx, AV_LOG_INFO,
  1637. "EBML block data error\n");
  1638. break;
  1639. }
  1640. data += n;
  1641. size -= n;
  1642. total = lace_size[0] = num;
  1643. for (n = 1; res == 0 && n < laces - 1; n++) {
  1644. int64_t snum;
  1645. int r;
  1646. r = matroska_ebmlnum_sint(matroska, data, size, &snum);
  1647. if (r < 0) {
  1648. av_log(matroska->ctx, AV_LOG_INFO,
  1649. "EBML block data error\n");
  1650. break;
  1651. }
  1652. data += r;
  1653. size -= r;
  1654. lace_size[n] = lace_size[n - 1] + snum;
  1655. total += lace_size[n];
  1656. }
  1657. lace_size[n] = size - total;
  1658. break;
  1659. }
  1660. }
  1661. break;
  1662. }
  1663. if (res == 0) {
  1664. for (n = 0; n < laces; n++) {
  1665. if ((st->codec->codec_id == CODEC_ID_RA_288 ||
  1666. st->codec->codec_id == CODEC_ID_COOK ||
  1667. st->codec->codec_id == CODEC_ID_SIPR ||
  1668. st->codec->codec_id == CODEC_ID_ATRAC3) &&
  1669. st->codec->block_align && track->audio.sub_packet_size) {
  1670. int a = st->codec->block_align;
  1671. int sps = track->audio.sub_packet_size;
  1672. int cfs = track->audio.coded_framesize;
  1673. int h = track->audio.sub_packet_h;
  1674. int y = track->audio.sub_packet_cnt;
  1675. int w = track->audio.frame_size;
  1676. int x;
  1677. if (!track->audio.pkt_cnt) {
  1678. if (track->audio.sub_packet_cnt == 0)
  1679. track->audio.buf_timecode = timecode;
  1680. if (st->codec->codec_id == CODEC_ID_RA_288)
  1681. for (x=0; x<h/2; x++)
  1682. memcpy(track->audio.buf+x*2*w+y*cfs,
  1683. data+x*cfs, cfs);
  1684. else if (st->codec->codec_id == CODEC_ID_SIPR)
  1685. memcpy(track->audio.buf + y*w, data, w);
  1686. else
  1687. for (x=0; x<w/sps; x++)
  1688. memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
  1689. if (++track->audio.sub_packet_cnt >= h) {
  1690. if (st->codec->codec_id == CODEC_ID_SIPR)
  1691. ff_rm_reorder_sipr_data(track->audio.buf, h, w);
  1692. track->audio.sub_packet_cnt = 0;
  1693. track->audio.pkt_cnt = h*w / a;
  1694. }
  1695. }
  1696. while (track->audio.pkt_cnt) {
  1697. pkt = av_mallocz(sizeof(AVPacket));
  1698. av_new_packet(pkt, a);
  1699. memcpy(pkt->data, track->audio.buf
  1700. + a * (h*w / a - track->audio.pkt_cnt--), a);
  1701. pkt->pts = track->audio.buf_timecode;
  1702. track->audio.buf_timecode = AV_NOPTS_VALUE;
  1703. pkt->pos = pos;
  1704. pkt->stream_index = st->index;
  1705. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1706. }
  1707. } else {
  1708. MatroskaTrackEncoding *encodings = track->encodings.elem;
  1709. int offset = 0, pkt_size = lace_size[n];
  1710. uint8_t *pkt_data = data;
  1711. if (pkt_size > size) {
  1712. av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
  1713. break;
  1714. }
  1715. if (encodings && encodings->scope & 1) {
  1716. offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
  1717. if (offset < 0)
  1718. continue;
  1719. }
  1720. pkt = av_mallocz(sizeof(AVPacket));
  1721. /* XXX: prevent data copy... */
  1722. if (av_new_packet(pkt, pkt_size+offset) < 0) {
  1723. av_free(pkt);
  1724. res = AVERROR(ENOMEM);
  1725. break;
  1726. }
  1727. if (offset)
  1728. memcpy (pkt->data, encodings->compression.settings.data, offset);
  1729. memcpy (pkt->data+offset, pkt_data, pkt_size);
  1730. if (pkt_data != data)
  1731. av_free(pkt_data);
  1732. if (n == 0)
  1733. pkt->flags = is_keyframe;
  1734. pkt->stream_index = st->index;
  1735. if (track->ms_compat)
  1736. pkt->dts = timecode;
  1737. else
  1738. pkt->pts = timecode;
  1739. pkt->pos = pos;
  1740. if (st->codec->codec_id == CODEC_ID_TEXT)
  1741. pkt->convergence_duration = duration;
  1742. else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
  1743. pkt->duration = duration;
  1744. if (st->codec->codec_id == CODEC_ID_SSA)
  1745. matroska_fix_ass_packet(matroska, pkt, duration);
  1746. if (matroska->prev_pkt &&
  1747. timecode != AV_NOPTS_VALUE &&
  1748. matroska->prev_pkt->pts == timecode &&
  1749. matroska->prev_pkt->stream_index == st->index &&
  1750. st->codec->codec_id == CODEC_ID_SSA)
  1751. matroska_merge_packets(matroska->prev_pkt, pkt);
  1752. else {
  1753. dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
  1754. matroska->prev_pkt = pkt;
  1755. }
  1756. }
  1757. if (timecode != AV_NOPTS_VALUE)
  1758. timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
  1759. data += lace_size[n];
  1760. size -= lace_size[n];
  1761. }
  1762. }
  1763. av_free(lace_size);
  1764. return res;
  1765. }
  1766. static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
  1767. {
  1768. MatroskaCluster cluster = { 0 };
  1769. EbmlList *blocks_list;
  1770. MatroskaBlock *blocks;
  1771. int i, res;
  1772. int64_t pos = avio_tell(matroska->ctx->pb);
  1773. matroska->prev_pkt = NULL;
  1774. if (matroska->current_id)
  1775. pos -= 4; /* sizeof the ID which was already read */
  1776. res = ebml_parse(matroska, matroska_clusters, &cluster);
  1777. blocks_list = &cluster.blocks;
  1778. blocks = blocks_list->elem;
  1779. for (i=0; i<blocks_list->nb_elem; i++)
  1780. if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
  1781. int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
  1782. res=matroska_parse_block(matroska,
  1783. blocks[i].bin.data, blocks[i].bin.size,
  1784. blocks[i].bin.pos, cluster.timecode,
  1785. blocks[i].duration, is_keyframe,
  1786. pos);
  1787. }
  1788. ebml_free(matroska_cluster, &cluster);
  1789. if (res < 0) matroska->done = 1;
  1790. return res;
  1791. }
  1792. static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
  1793. {
  1794. MatroskaDemuxContext *matroska = s->priv_data;
  1795. while (matroska_deliver_packet(matroska, pkt)) {
  1796. if (matroska->done)
  1797. return AVERROR_EOF;
  1798. matroska_parse_cluster(matroska);
  1799. }
  1800. return 0;
  1801. }
  1802. static int matroska_read_seek(AVFormatContext *s, int stream_index,
  1803. int64_t timestamp, int flags)
  1804. {
  1805. MatroskaDemuxContext *matroska = s->priv_data;
  1806. MatroskaTrack *tracks = matroska->tracks.elem;
  1807. AVStream *st = s->streams[stream_index];
  1808. int i, index, index_sub, index_min;
  1809. if (!st->nb_index_entries)
  1810. return 0;
  1811. timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
  1812. if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1813. avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
  1814. while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
  1815. matroska_clear_queue(matroska);
  1816. if (matroska_parse_cluster(matroska) < 0)
  1817. break;
  1818. }
  1819. }
  1820. matroska_clear_queue(matroska);
  1821. if (index < 0)
  1822. return 0;
  1823. index_min = index;
  1824. for (i=0; i < matroska->tracks.nb_elem; i++) {
  1825. tracks[i].audio.pkt_cnt = 0;
  1826. tracks[i].audio.sub_packet_cnt = 0;
  1827. tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
  1828. tracks[i].end_timecode = 0;
  1829. if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
  1830. && !tracks[i].stream->discard != AVDISCARD_ALL) {
  1831. index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
  1832. if (index_sub >= 0
  1833. && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
  1834. && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
  1835. index_min = index_sub;
  1836. }
  1837. }
  1838. avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
  1839. matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
  1840. matroska->skip_to_timecode = st->index_entries[index].timestamp;
  1841. matroska->done = 0;
  1842. av_update_cur_dts(s, st, st->index_entries[index].timestamp);
  1843. return 0;
  1844. }
  1845. static int matroska_read_close(AVFormatContext *s)
  1846. {
  1847. MatroskaDemuxContext *matroska = s->priv_data;
  1848. MatroskaTrack *tracks = matroska->tracks.elem;
  1849. int n;
  1850. matroska_clear_queue(matroska);
  1851. for (n=0; n < matroska->tracks.nb_elem; n++)
  1852. if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
  1853. av_free(tracks[n].audio.buf);
  1854. ebml_free(matroska_segment, matroska);
  1855. return 0;
  1856. }
  1857. AVInputFormat ff_matroska_demuxer = {
  1858. "matroska,webm",
  1859. NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
  1860. sizeof(MatroskaDemuxContext),
  1861. matroska_probe,
  1862. matroska_read_header,
  1863. matroska_read_packet,
  1864. matroska_read_close,
  1865. matroska_read_seek,
  1866. };