matroskadec.c 66 KB

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