matroskadec.c 70 KB

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