opusfile.c 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  5. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  6. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  7. * *
  8. * THE libopusfile SOURCE CODE IS (C) COPYRIGHT 1994-2012 *
  9. * by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
  10. * *
  11. ********************************************************************
  12. function: stdio-based convenience library for opening/seeking/decoding
  13. last mod: $Id: vorbisfile.c 17573 2010-10-27 14:53:59Z xiphmont $
  14. ********************************************************************/
  15. #ifdef HAVE_CONFIG_H
  16. #include "config.h"
  17. #endif
  18. #include "internal.h"
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <errno.h>
  22. #include <limits.h>
  23. #include <string.h>
  24. #include <math.h>
  25. #include "opusfile.h"
  26. /*This implementation is largely based off of libvorbisfile.
  27. All of the Ogg bits work roughly the same, though I have made some
  28. "improvements" that have not been folded back there, yet.*/
  29. /*A 'chained bitstream' is an Ogg Opus bitstream that contains more than one
  30. logical bitstream arranged end to end (the only form of Ogg multiplexing
  31. supported by this library.
  32. Grouping (parallel multiplexing) is not supported, except to the extent that
  33. if there are multiple logical Ogg streams in a single link of the chain, we
  34. will ignore all but the first Opus stream we find.*/
  35. /*An Ogg Opus file can be played beginning to end (streamed) without worrying
  36. ahead of time about chaining (see opusdec from the opus-tools package).
  37. If we have the whole file, however, and want random access
  38. (seeking/scrubbing) or desire to know the total length/time of a file, we
  39. need to account for the possibility of chaining.*/
  40. /*We can handle things a number of ways.
  41. We can determine the entire bitstream structure right off the bat, or find
  42. pieces on demand.
  43. This library determines and caches structure for the entire bitstream, but
  44. builds a virtual decoder on the fly when moving between links in the chain.*/
  45. /*There are also different ways to implement seeking.
  46. Enough information exists in an Ogg bitstream to seek to sample-granularity
  47. positions in the output.
  48. Or, one can seek by picking some portion of the stream roughly in the desired
  49. area if we only want coarse navigation through the stream.
  50. We implement and expose both strategies.*/
  51. /*The maximum number of bytes in a page (including the page headers).*/
  52. #define OP_PAGE_SIZE_MAX (65307)
  53. /*The default amount to seek backwards per step when trying to find the
  54. previous page.
  55. This must be at least as large as the maximum size of a page.*/
  56. #define OP_CHUNK_SIZE (65536)
  57. /*The maximum amount to seek backwards per step when trying to find the
  58. previous page.*/
  59. #define OP_CHUNK_SIZE_MAX (1024*(opus_int32)1024)
  60. /*A smaller read size is needed for low-rate streaming.*/
  61. #define OP_READ_SIZE (2048)
  62. int op_test(OpusHead *_head,
  63. const unsigned char *_initial_data,size_t _initial_bytes){
  64. ogg_sync_state oy;
  65. char *data;
  66. int err;
  67. /*The first page of a normal Opus file will be at most 57 bytes (27 Ogg
  68. page header bytes + 1 lacing value + 21 Opus header bytes + 8 channel
  69. mapping bytes).
  70. It will be at least 47 bytes (27 Ogg page header bytes + 1 lacing value +
  71. 19 Opus header bytes using channel mapping family 0).
  72. If we don't have at least that much data, give up now.*/
  73. if(_initial_bytes<47)return OP_FALSE;
  74. /*Only proceed if we start with the magic OggS string.
  75. This is to prevent us spending a lot of time allocating memory and looking
  76. for Ogg pages in non-Ogg files.*/
  77. if(memcmp(_initial_data,"OggS",4)!=0)return OP_ENOTFORMAT;
  78. ogg_sync_init(&oy);
  79. data=ogg_sync_buffer(&oy,_initial_bytes);
  80. if(data!=NULL){
  81. ogg_stream_state os;
  82. ogg_page og;
  83. int ret;
  84. memcpy(data,_initial_data,_initial_bytes);
  85. ogg_sync_wrote(&oy,_initial_bytes);
  86. ogg_stream_init(&os,-1);
  87. err=OP_FALSE;
  88. do{
  89. ogg_packet op;
  90. ret=ogg_sync_pageout(&oy,&og);
  91. /*Ignore holes.*/
  92. if(ret<0)continue;
  93. /*Stop if we run out of data.*/
  94. if(!ret)break;
  95. ogg_stream_reset_serialno(&os,ogg_page_serialno(&og));
  96. ogg_stream_pagein(&os,&og);
  97. /*Only process the first packet on this page (if it's a BOS packet,
  98. it's required to be the only one).*/
  99. if(ogg_stream_packetout(&os,&op)==1){
  100. if(op.b_o_s){
  101. ret=opus_head_parse(_head,op.packet,op.bytes);
  102. /*If this didn't look like Opus, keep going.*/
  103. if(ret==OP_ENOTFORMAT)continue;
  104. /*Otherwise we're done, one way or another.*/
  105. err=ret;
  106. }
  107. /*We finished parsing the headers.
  108. There is no Opus to be found.*/
  109. else err=OP_ENOTFORMAT;
  110. }
  111. }
  112. while(err==OP_FALSE);
  113. ogg_stream_clear(&os);
  114. }
  115. else err=OP_EFAULT;
  116. ogg_sync_clear(&oy);
  117. return err;
  118. }
  119. /*Many, many internal helpers.
  120. The intention is not to be confusing.
  121. Rampant duplication and monolithic function implementation (though we do have
  122. some large, omnibus functions still) would be harder to understand anyway.
  123. The high level functions are last.
  124. Begin grokking near the end of the file if you prefer to read things
  125. top-down.*/
  126. /*The read/seek functions track absolute position within the stream.*/
  127. /*Read a little more data from the file/pipe into the ogg_sync framer.
  128. _nbytes: The maximum number of bytes to read.
  129. Return: A positive number of bytes read on success, 0 on end-of-file, or a
  130. negative value on failure.*/
  131. static int op_get_data(OggOpusFile *_of,int _nbytes){
  132. unsigned char *buffer;
  133. int nbytes;
  134. OP_ASSERT(_nbytes>0);
  135. buffer=(unsigned char *)ogg_sync_buffer(&_of->oy,_nbytes);
  136. nbytes=(int)(*_of->callbacks.read)(_of->source,buffer,_nbytes);
  137. OP_ASSERT(nbytes<=_nbytes);
  138. if(OP_LIKELY(nbytes>0))ogg_sync_wrote(&_of->oy,nbytes);
  139. return nbytes;
  140. }
  141. /*Save a tiny smidge of verbosity to make the code more readable.*/
  142. static int op_seek_helper(OggOpusFile *_of,opus_int64 _offset){
  143. if(_offset==_of->offset)return 0;
  144. if(_of->callbacks.seek==NULL
  145. ||(*_of->callbacks.seek)(_of->source,_offset,SEEK_SET)){
  146. return OP_EREAD;
  147. }
  148. _of->offset=_offset;
  149. ogg_sync_reset(&_of->oy);
  150. return 0;
  151. }
  152. /*Get the current position indicator of the underlying source.
  153. This should be the same as the value reported by tell().*/
  154. static opus_int64 op_position(const OggOpusFile *_of){
  155. /*The current position indicator is _not_ simply offset.
  156. We may also have unprocessed, buffered data in the sync state.*/
  157. return _of->offset+_of->oy.fill-_of->oy.returned;
  158. }
  159. /*From the head of the stream, get the next page.
  160. _boundary specifies if the function is allowed to fetch more data from the
  161. stream (and how much) or only use internally buffered data.
  162. _boundary: -1: Unbounded search.
  163. 0: Read no additional data.
  164. Use only cached data.
  165. n: Search for the start of a new page up to file position n.
  166. Return: n>=0: Found a page at absolute offset n.
  167. OP_FALSE: Hit the _boundary limit.
  168. OP_EREAD: An underlying read operation failed.
  169. OP_BADLINK: We hit end-of-file before reaching _boundary.*/
  170. static opus_int64 op_get_next_page(OggOpusFile *_of,ogg_page *_og,
  171. opus_int64 _boundary){
  172. while(_boundary<=0||_of->offset<_boundary){
  173. int more;
  174. more=ogg_sync_pageseek(&_of->oy,_og);
  175. /*Skipped (-more) bytes.*/
  176. if(OP_UNLIKELY(more<0))_of->offset-=more;
  177. else if(more==0){
  178. int read_nbytes;
  179. int ret;
  180. /*Send more paramedics.*/
  181. if(!_boundary)return OP_FALSE;
  182. if(_boundary<0)read_nbytes=OP_READ_SIZE;
  183. else{
  184. opus_int64 position;
  185. position=op_position(_of);
  186. if(position>=_boundary)return OP_FALSE;
  187. read_nbytes=(int)OP_MIN(_boundary-position,OP_READ_SIZE);
  188. }
  189. ret=op_get_data(_of,read_nbytes);
  190. if(OP_UNLIKELY(ret<0))return OP_EREAD;
  191. if(OP_UNLIKELY(ret==0)){
  192. /*Only fail cleanly on EOF if we didn't have a known boundary.
  193. Otherwise, we should have been able to reach that boundary, and this
  194. is a fatal error.*/
  195. return OP_UNLIKELY(_boundary<0)?OP_FALSE:OP_EBADLINK;
  196. }
  197. }
  198. else{
  199. /*Got a page.
  200. Return the page start offset and advance the internal offset past the
  201. page end.*/
  202. opus_int64 page_offset;
  203. page_offset=_of->offset;
  204. _of->offset+=more;
  205. OP_ASSERT(page_offset>=0);
  206. return page_offset;
  207. }
  208. }
  209. return OP_FALSE;
  210. }
  211. static int op_add_serialno(const ogg_page *_og,
  212. ogg_uint32_t **_serialnos,int *_nserialnos,int *_cserialnos){
  213. ogg_uint32_t *serialnos;
  214. int nserialnos;
  215. int cserialnos;
  216. ogg_uint32_t s;
  217. s=ogg_page_serialno(_og);
  218. serialnos=*_serialnos;
  219. nserialnos=*_nserialnos;
  220. cserialnos=*_cserialnos;
  221. if(OP_UNLIKELY(nserialnos>=cserialnos)){
  222. if(OP_UNLIKELY(cserialnos>INT_MAX/(int)sizeof(*serialnos)-1>>1)){
  223. return OP_EFAULT;
  224. }
  225. cserialnos=2*cserialnos+1;
  226. OP_ASSERT(nserialnos<cserialnos);
  227. serialnos=(ogg_uint32_t *)_ogg_realloc(serialnos,
  228. sizeof(*serialnos)*cserialnos);
  229. if(OP_UNLIKELY(serialnos==NULL))return OP_EFAULT;
  230. }
  231. serialnos[nserialnos++]=s;
  232. *_serialnos=serialnos;
  233. *_nserialnos=nserialnos;
  234. *_cserialnos=cserialnos;
  235. return 0;
  236. }
  237. /*Returns nonzero if found.*/
  238. static int op_lookup_serialno(ogg_uint32_t _s,
  239. const ogg_uint32_t *_serialnos,int _nserialnos){
  240. int i;
  241. for(i=0;i<_nserialnos&&_serialnos[i]!=_s;i++);
  242. return i<_nserialnos;
  243. }
  244. static int op_lookup_page_serialno(const ogg_page *_og,
  245. const ogg_uint32_t *_serialnos,int _nserialnos){
  246. return op_lookup_serialno(ogg_page_serialno(_og),_serialnos,_nserialnos);
  247. }
  248. typedef struct OpusSeekRecord OpusSeekRecord;
  249. /*We use this to remember the pages we found while enumerating the links of a
  250. chained stream.
  251. We keep track of the starting and ending offsets, as well as the point we
  252. started searching from, so we know where to bisect.
  253. We also keep the serial number, so we can tell if the page belonged to the
  254. current link or not, as well as the granule position, to aid in estimating
  255. the start of the link.*/
  256. struct OpusSeekRecord{
  257. /*The earliest byte we know of such that reading forward from it causes
  258. capture to be regained at this page.*/
  259. opus_int64 search_start;
  260. /*The offset of this page.*/
  261. opus_int64 offset;
  262. /*The size of this page.*/
  263. opus_int32 size;
  264. /*The serial number of this page.*/
  265. ogg_uint32_t serialno;
  266. /*The granule position of this page.*/
  267. ogg_int64_t gp;
  268. };
  269. /*Find the last page beginning before _offset with a valid granule position.
  270. There is no '_boundary' parameter as it will always have to read more data.
  271. This is much dirtier than the above, as Ogg doesn't have any backward search
  272. linkage.
  273. This search prefers pages of the specified serial number.
  274. If a page of the specified serial number is spotted during the
  275. seek-back-and-read-forward, it will return the info of last page of the
  276. matching serial number, instead of the very last page, unless the very last
  277. page belongs to a different link than preferred serial number.
  278. If no page of the specified serial number is seen, it will return the info of
  279. the last page.
  280. [out] _sr: Returns information about the page that was found on success.
  281. _offset: The _offset before which to find a page.
  282. Any page returned will consist of data entirely before _offset.
  283. _serialno: The preferred serial number.
  284. If a page with this serial number is found, it will be returned
  285. even if another page in the same link is found closer to
  286. _offset.
  287. This is purely opportunistic: there is no guarantee such a page
  288. will be found if it exists.
  289. _serialnos: The list of serial numbers in the link that contains the
  290. preferred serial number.
  291. _nserialnos: The number of serial numbers in the current link.
  292. Return: 0 on success, or a negative value on failure.
  293. OP_EREAD: Failed to read more data (error or EOF).
  294. OP_EBADLINK: We couldn't find a page even after seeking back to the
  295. start of the stream.*/
  296. static int op_get_prev_page_serial(OggOpusFile *_of,OpusSeekRecord *_sr,
  297. opus_int64 _offset,ogg_uint32_t _serialno,
  298. const ogg_uint32_t *_serialnos,int _nserialnos){
  299. OpusSeekRecord preferred_sr;
  300. ogg_page og;
  301. opus_int64 begin;
  302. opus_int64 end;
  303. opus_int64 original_end;
  304. opus_int32 chunk_size;
  305. int preferred_found;
  306. original_end=end=begin=_offset;
  307. preferred_found=0;
  308. _offset=-1;
  309. chunk_size=OP_CHUNK_SIZE;
  310. do{
  311. opus_int64 search_start;
  312. int ret;
  313. OP_ASSERT(chunk_size>=OP_PAGE_SIZE_MAX);
  314. begin=OP_MAX(begin-chunk_size,0);
  315. ret=op_seek_helper(_of,begin);
  316. if(OP_UNLIKELY(ret<0))return ret;
  317. search_start=begin;
  318. while(_of->offset<end){
  319. opus_int64 llret;
  320. ogg_uint32_t serialno;
  321. llret=op_get_next_page(_of,&og,end);
  322. if(OP_UNLIKELY(llret<OP_FALSE))return (int)llret;
  323. else if(llret==OP_FALSE)break;
  324. serialno=ogg_page_serialno(&og);
  325. /*Save the information for this page.
  326. We're not interested in the page itself... just the serial number, byte
  327. offset, page size, and granule position.*/
  328. _sr->search_start=search_start;
  329. _sr->offset=_offset=llret;
  330. _sr->serialno=serialno;
  331. OP_ASSERT(_of->offset-_offset>=0);
  332. OP_ASSERT(_of->offset-_offset<=OP_PAGE_SIZE_MAX);
  333. _sr->size=(opus_int32)(_of->offset-_offset);
  334. _sr->gp=ogg_page_granulepos(&og);
  335. /*If this page is from the stream we're looking for, remember it.*/
  336. if(serialno==_serialno){
  337. preferred_found=1;
  338. *&preferred_sr=*_sr;
  339. }
  340. if(!op_lookup_serialno(serialno,_serialnos,_nserialnos)){
  341. /*We fell off the end of the link, which means we seeked back too far
  342. and shouldn't have been looking in that link to begin with.
  343. If we found the preferred serial number, forget that we saw it.*/
  344. preferred_found=0;
  345. }
  346. search_start=llret+1;
  347. }
  348. /*We started from the beginning of the stream and found nothing.
  349. This should be impossible unless the contents of the source changed out
  350. from under us after we read from it.*/
  351. if(OP_UNLIKELY(!begin)&&OP_UNLIKELY(_offset<0))return OP_EBADLINK;
  352. /*Bump up the chunk size.
  353. This is mildly helpful when seeks are very expensive (http).*/
  354. chunk_size=OP_MIN(2*chunk_size,OP_CHUNK_SIZE_MAX);
  355. /*Avoid quadratic complexity if we hit an invalid patch of the file.*/
  356. end=OP_MIN(begin+OP_PAGE_SIZE_MAX-1,original_end);
  357. }
  358. while(_offset<0);
  359. if(preferred_found)*_sr=*&preferred_sr;
  360. return 0;
  361. }
  362. /*Find the last page beginning before _offset with the given serial number and
  363. a valid granule position.
  364. Unlike the above search, this continues until it finds such a page, but does
  365. not stray outside the current link.
  366. We could implement it (inefficiently) by calling op_get_prev_page_serial()
  367. repeatedly until it returned a page that had both our preferred serial
  368. number and a valid granule position, but doing it with a separate function
  369. allows us to avoid repeatedly re-scanning valid pages from other streams as
  370. we seek-back-and-read-forward.
  371. [out] _gp: Returns the granule position of the page that was found on
  372. success.
  373. _offset: The _offset before which to find a page.
  374. Any page returned will consist of data entirely before _offset.
  375. _serialno: The target serial number.
  376. _serialnos: The list of serial numbers in the link that contains the
  377. preferred serial number.
  378. _nserialnos: The number of serial numbers in the current link.
  379. Return: The offset of the page on success, or a negative value on failure.
  380. OP_EREAD: Failed to read more data (error or EOF).
  381. OP_EBADLINK: We couldn't find a page even after seeking back past the
  382. beginning of the link.*/
  383. static opus_int64 op_get_last_page(OggOpusFile *_of,ogg_int64_t *_gp,
  384. opus_int64 _offset,ogg_uint32_t _serialno,
  385. const ogg_uint32_t *_serialnos,int _nserialnos){
  386. ogg_page og;
  387. ogg_int64_t gp;
  388. opus_int64 begin;
  389. opus_int64 end;
  390. opus_int64 original_end;
  391. opus_int32 chunk_size;
  392. /*The target serial number must belong to the current link.*/
  393. OP_ASSERT(op_lookup_serialno(_serialno,_serialnos,_nserialnos));
  394. original_end=end=begin=_offset;
  395. _offset=-1;
  396. /*We shouldn't have to initialize gp, but gcc is too dumb to figure out that
  397. ret>=0 implies we entered the if(page_gp!=-1) block at least once.*/
  398. gp=-1;
  399. chunk_size=OP_CHUNK_SIZE;
  400. do{
  401. int left_link;
  402. int ret;
  403. OP_ASSERT(chunk_size>=OP_PAGE_SIZE_MAX);
  404. begin=OP_MAX(begin-chunk_size,0);
  405. ret=op_seek_helper(_of,begin);
  406. if(OP_UNLIKELY(ret<0))return ret;
  407. left_link=0;
  408. while(_of->offset<end){
  409. opus_int64 llret;
  410. ogg_uint32_t serialno;
  411. llret=op_get_next_page(_of,&og,end);
  412. if(OP_UNLIKELY(llret<OP_FALSE))return llret;
  413. else if(llret==OP_FALSE)break;
  414. serialno=ogg_page_serialno(&og);
  415. if(serialno==_serialno){
  416. ogg_int64_t page_gp;
  417. /*The page is from the right stream...*/
  418. page_gp=ogg_page_granulepos(&og);
  419. if(page_gp!=-1){
  420. /*And has a valid granule position.
  421. Let's remember it.*/
  422. _offset=llret;
  423. gp=page_gp;
  424. }
  425. }
  426. else if(OP_UNLIKELY(!op_lookup_serialno(serialno,
  427. _serialnos,_nserialnos))){
  428. /*We fell off the start of the link, which means we don't need to keep
  429. seeking any farther back.*/
  430. left_link=1;
  431. }
  432. }
  433. /*We started from at or before the beginning of the link and found nothing.
  434. This should be impossible unless the contents of the source changed out
  435. from under us after we read from it.*/
  436. if((OP_UNLIKELY(left_link)||OP_UNLIKELY(!begin))&&OP_UNLIKELY(_offset<0)){
  437. return OP_EBADLINK;
  438. }
  439. /*Bump up the chunk size.
  440. This is mildly helpful when seeks are very expensive (http).*/
  441. chunk_size=OP_MIN(2*chunk_size,OP_CHUNK_SIZE_MAX);
  442. /*Avoid quadratic complexity if we hit an invalid patch of the file.*/
  443. end=OP_MIN(begin+OP_PAGE_SIZE_MAX-1,original_end);
  444. }
  445. while(_offset<0);
  446. *_gp=gp;
  447. return _offset;
  448. }
  449. /*Uses the local ogg_stream storage in _of.
  450. This is important for non-streaming input sources.*/
  451. static int op_fetch_headers_impl(OggOpusFile *_of,OpusHead *_head,
  452. OpusTags *_tags,ogg_uint32_t **_serialnos,int *_nserialnos,
  453. int *_cserialnos,ogg_page *_og){
  454. ogg_packet op;
  455. int ret;
  456. if(_serialnos!=NULL)*_nserialnos=0;
  457. /*Extract the serialnos of all BOS pages plus the first set of Opus headers
  458. we see in the link.*/
  459. while(ogg_page_bos(_og)){
  460. if(_serialnos!=NULL){
  461. if(OP_UNLIKELY(op_lookup_page_serialno(_og,*_serialnos,*_nserialnos))){
  462. /*A dupe serialnumber in an initial header packet set==invalid stream.*/
  463. return OP_EBADHEADER;
  464. }
  465. ret=op_add_serialno(_og,_serialnos,_nserialnos,_cserialnos);
  466. if(OP_UNLIKELY(ret<0))return ret;
  467. }
  468. if(_of->ready_state<OP_STREAMSET){
  469. /*We don't have an Opus stream in this link yet, so begin prospective
  470. stream setup.
  471. We need a stream to get packets.*/
  472. ogg_stream_reset_serialno(&_of->os,ogg_page_serialno(_og));
  473. ogg_stream_pagein(&_of->os,_og);
  474. if(OP_LIKELY(ogg_stream_packetout(&_of->os,&op)>0)){
  475. ret=opus_head_parse(_head,op.packet,op.bytes);
  476. /*Found a valid Opus header.
  477. Continue setup.*/
  478. if(OP_LIKELY(ret>=0))_of->ready_state=OP_STREAMSET;
  479. /*If it's just a stream type we don't recognize, ignore it.
  480. Everything else is fatal.*/
  481. else if(ret!=OP_ENOTFORMAT)return ret;
  482. }
  483. /*TODO: Should a BOS page with no packets be an error?*/
  484. }
  485. /*Get the next page.
  486. No need to clamp the boundary offset against _of->end, as all errors
  487. become OP_ENOTFORMAT or OP_EBADHEADER.*/
  488. if(OP_UNLIKELY(op_get_next_page(_of,_og,
  489. OP_ADV_OFFSET(_of->offset,OP_CHUNK_SIZE))<0)){
  490. return _of->ready_state<OP_STREAMSET?OP_ENOTFORMAT:OP_EBADHEADER;
  491. }
  492. }
  493. if(OP_UNLIKELY(_of->ready_state!=OP_STREAMSET))return OP_ENOTFORMAT;
  494. /*If the first non-header page belonged to our Opus stream, submit it.*/
  495. if(_of->os.serialno==ogg_page_serialno(_og))ogg_stream_pagein(&_of->os,_og);
  496. /*Loop getting packets.*/
  497. for(;;){
  498. switch(ogg_stream_packetout(&_of->os,&op)){
  499. case 0:{
  500. /*Loop getting pages.*/
  501. for(;;){
  502. /*No need to clamp the boundary offset against _of->end, as all
  503. errors become OP_EBADHEADER.*/
  504. if(OP_UNLIKELY(op_get_next_page(_of,_og,
  505. OP_ADV_OFFSET(_of->offset,OP_CHUNK_SIZE))<0)){
  506. return OP_EBADHEADER;
  507. }
  508. /*If this page belongs to the correct stream, go parse it.*/
  509. if(_of->os.serialno==ogg_page_serialno(_og)){
  510. ogg_stream_pagein(&_of->os,_og);
  511. break;
  512. }
  513. /*If the link ends before we see the Opus comment header, abort.*/
  514. if(OP_UNLIKELY(ogg_page_bos(_og)))return OP_EBADHEADER;
  515. /*Otherwise, keep looking.*/
  516. }
  517. }break;
  518. /*We shouldn't get a hole in the headers!*/
  519. case -1:return OP_EBADHEADER;
  520. default:{
  521. /*Got a packet.
  522. It should be the comment header.*/
  523. ret=opus_tags_parse(_tags,op.packet,op.bytes);
  524. if(OP_UNLIKELY(ret<0))return ret;
  525. /*Make sure the page terminated at the end of the comment header.
  526. If there is another packet on the page, or part of a packet, then
  527. reject the stream.
  528. Otherwise seekable sources won't be able to seek back to the start
  529. properly.*/
  530. ret=ogg_stream_packetout(&_of->os,&op);
  531. if(OP_UNLIKELY(ret!=0)
  532. ||OP_UNLIKELY(_og->header[_og->header_len-1]==255)){
  533. /*If we fail, the caller assumes our tags are uninitialized.*/
  534. opus_tags_clear(_tags);
  535. return OP_EBADHEADER;
  536. }
  537. return 0;
  538. }
  539. }
  540. }
  541. }
  542. static int op_fetch_headers(OggOpusFile *_of,OpusHead *_head,
  543. OpusTags *_tags,ogg_uint32_t **_serialnos,int *_nserialnos,
  544. int *_cserialnos,ogg_page *_og){
  545. ogg_page og;
  546. int ret;
  547. if(!_og){
  548. /*No need to clamp the boundary offset against _of->end, as all errors
  549. become OP_ENOTFORMAT.*/
  550. if(OP_UNLIKELY(op_get_next_page(_of,&og,
  551. OP_ADV_OFFSET(_of->offset,OP_CHUNK_SIZE))<0)){
  552. return OP_ENOTFORMAT;
  553. }
  554. _og=&og;
  555. }
  556. _of->ready_state=OP_OPENED;
  557. ret=op_fetch_headers_impl(_of,_head,_tags,_serialnos,_nserialnos,
  558. _cserialnos,_og);
  559. /*Revert back from OP_STREAMSET to OP_OPENED on failure, to prevent
  560. double-free of the tags in an unseekable stream.*/
  561. if(OP_UNLIKELY(ret<0))_of->ready_state=OP_OPENED;
  562. return ret;
  563. }
  564. /*Granule position manipulation routines.
  565. A granule position is defined to be an unsigned 64-bit integer, with the
  566. special value -1 in two's complement indicating an unset or invalid granule
  567. position.
  568. We are not guaranteed to have an unsigned 64-bit type, so we construct the
  569. following routines that
  570. a) Properly order negative numbers as larger than positive numbers, and
  571. b) Check for underflow or overflow past the special -1 value.
  572. This lets us operate on the full, valid range of granule positions in a
  573. consistent and safe manner.
  574. This full range is organized into distinct regions:
  575. [ -1 (invalid) ][ 0 ... OP_INT64_MAX ][ OP_INT64_MIN ... -2 ][-1 (invalid) ]
  576. No one should actually use granule positions so large that they're negative,
  577. even if they are technically valid, as very little software handles them
  578. correctly (including most of Xiph.Org's).
  579. This library also refuses to support durations so large they won't fit in a
  580. signed 64-bit integer (to avoid exposing this mess to the application, and
  581. to simplify a good deal of internal arithmetic), so the only way to use them
  582. successfully is if pcm_start is very large.
  583. This means there isn't anything you can do with negative granule positions
  584. that you couldn't have done with purely non-negative ones.
  585. The main purpose of these routines is to allow us to think very explicitly
  586. about the possible failure cases of all granule position manipulations.*/
  587. /*Safely adds a small signed integer to a valid (not -1) granule position.
  588. The result can use the full 64-bit range of values (both positive and
  589. negative), but will fail on overflow (wrapping past -1; wrapping past
  590. OP_INT64_MAX is explicitly okay).
  591. [out] _dst_gp: The resulting granule position.
  592. Only modified on success.
  593. _src_gp: The granule position to add to.
  594. This must not be -1.
  595. _delta: The amount to add.
  596. This is allowed to be up to 32 bits to support the maximum
  597. duration of a single Ogg page (255 packets * 120 ms per
  598. packet == 1,468,800 samples at 48 kHz).
  599. Return: 0 on success, or OP_EINVAL if the result would wrap around past -1.*/
  600. static int op_granpos_add(ogg_int64_t *_dst_gp,ogg_int64_t _src_gp,
  601. opus_int32 _delta){
  602. /*The code below handles this case correctly, but there's no reason we
  603. should ever be called with these values, so make sure we aren't.*/
  604. OP_ASSERT(_src_gp!=-1);
  605. if(_delta>0){
  606. /*Adding this amount to the granule position would overflow its 64-bit
  607. range.*/
  608. if(OP_UNLIKELY(_src_gp<0)&&OP_UNLIKELY(_src_gp>=-1-_delta))return OP_EINVAL;
  609. if(OP_UNLIKELY(_src_gp>OP_INT64_MAX-_delta)){
  610. /*Adding this amount to the granule position would overflow the positive
  611. half of its 64-bit range.
  612. Since signed overflow is undefined in C, do it in a way the compiler
  613. isn't allowed to screw up.*/
  614. _delta-=(opus_int32)(OP_INT64_MAX-_src_gp)+1;
  615. _src_gp=OP_INT64_MIN;
  616. }
  617. }
  618. else if(_delta<0){
  619. /*Subtracting this amount from the granule position would underflow its
  620. 64-bit range.*/
  621. if(_src_gp>=0&&OP_UNLIKELY(_src_gp<-_delta))return OP_EINVAL;
  622. if(OP_UNLIKELY(_src_gp<OP_INT64_MIN-_delta)){
  623. /*Subtracting this amount from the granule position would underflow the
  624. negative half of its 64-bit range.
  625. Since signed underflow is undefined in C, do it in a way the compiler
  626. isn't allowed to screw up.*/
  627. _delta+=(opus_int32)(_src_gp-OP_INT64_MIN)+1;
  628. _src_gp=OP_INT64_MAX;
  629. }
  630. }
  631. *_dst_gp=_src_gp+_delta;
  632. return 0;
  633. }
  634. /*Safely computes the difference between two granule positions.
  635. The difference must fit in a signed 64-bit integer, or the function fails.
  636. It correctly handles the case where the granule position has wrapped around
  637. from positive values to negative ones.
  638. [out] _delta: The difference between the granule positions.
  639. Only modified on success.
  640. _gp_a: The granule position to subtract from.
  641. This must not be -1.
  642. _gp_b: The granule position to subtract.
  643. This must not be -1.
  644. Return: 0 on success, or OP_EINVAL if the result would not fit in a signed
  645. 64-bit integer.*/
  646. static int op_granpos_diff(ogg_int64_t *_delta,
  647. ogg_int64_t _gp_a,ogg_int64_t _gp_b){
  648. int gp_a_negative;
  649. int gp_b_negative;
  650. /*The code below handles these cases correctly, but there's no reason we
  651. should ever be called with these values, so make sure we aren't.*/
  652. OP_ASSERT(_gp_a!=-1);
  653. OP_ASSERT(_gp_b!=-1);
  654. gp_a_negative=OP_UNLIKELY(_gp_a<0);
  655. gp_b_negative=OP_UNLIKELY(_gp_b<0);
  656. if(OP_UNLIKELY(gp_a_negative^gp_b_negative)){
  657. ogg_int64_t da;
  658. ogg_int64_t db;
  659. if(gp_a_negative){
  660. /*_gp_a has wrapped to a negative value but _gp_b hasn't: the difference
  661. should be positive.*/
  662. /*Step 1: Handle wrapping.*/
  663. /*_gp_a < 0 => da < 0.*/
  664. da=(OP_INT64_MIN-_gp_a)-1;
  665. /*_gp_b >= 0 => db >= 0.*/
  666. db=OP_INT64_MAX-_gp_b;
  667. /*Step 2: Check for overflow.*/
  668. if(OP_UNLIKELY(OP_INT64_MAX+da<db))return OP_EINVAL;
  669. *_delta=db-da;
  670. }
  671. else{
  672. /*_gp_b has wrapped to a negative value but _gp_a hasn't: the difference
  673. should be negative.*/
  674. /*Step 1: Handle wrapping.*/
  675. /*_gp_a >= 0 => da <= 0*/
  676. da=_gp_a+OP_INT64_MIN;
  677. /*_gp_b < 0 => db <= 0*/
  678. db=OP_INT64_MIN-_gp_b;
  679. /*Step 2: Check for overflow.*/
  680. if(OP_UNLIKELY(da<OP_INT64_MIN-db))return OP_EINVAL;
  681. *_delta=da+db;
  682. }
  683. }
  684. else *_delta=_gp_a-_gp_b;
  685. return 0;
  686. }
  687. static int op_granpos_cmp(ogg_int64_t _gp_a,ogg_int64_t _gp_b){
  688. /*The invalid granule position -1 should behave like NaN: neither greater
  689. than nor less than any other granule position, nor equal to any other
  690. granule position, including itself.
  691. However, that means there isn't anything we could sensibly return from this
  692. function for it.*/
  693. OP_ASSERT(_gp_a!=-1);
  694. OP_ASSERT(_gp_b!=-1);
  695. /*Handle the wrapping cases.*/
  696. if(OP_UNLIKELY(_gp_a<0)){
  697. if(_gp_b>=0)return 1;
  698. /*Else fall through.*/
  699. }
  700. else if(OP_UNLIKELY(_gp_b<0))return -1;
  701. /*No wrapping case.*/
  702. return (_gp_a>_gp_b)-(_gp_b>_gp_a);
  703. }
  704. /*Returns the duration of the packet (in samples at 48 kHz), or a negative
  705. value on error.*/
  706. static int op_get_packet_duration(const unsigned char *_data,int _len){
  707. int nframes;
  708. int frame_size;
  709. int nsamples;
  710. nframes=opus_packet_get_nb_frames(_data,_len);
  711. if(OP_UNLIKELY(nframes<0))return OP_EBADPACKET;
  712. frame_size=opus_packet_get_samples_per_frame(_data,48000);
  713. nsamples=nframes*frame_size;
  714. if(OP_UNLIKELY(nsamples>120*48))return OP_EBADPACKET;
  715. return nsamples;
  716. }
  717. /*This function more properly belongs in info.c, but we define it here to allow
  718. the static granule position manipulation functions to remain static.*/
  719. ogg_int64_t opus_granule_sample(const OpusHead *_head,ogg_int64_t _gp){
  720. opus_int32 pre_skip;
  721. pre_skip=_head->pre_skip;
  722. if(_gp!=-1&&op_granpos_add(&_gp,_gp,-pre_skip))_gp=-1;
  723. return _gp;
  724. }
  725. /*Grab all the packets currently in the stream state, and compute their
  726. durations.
  727. _of->op_count is set to the number of packets collected.
  728. [out] _durations: Returns the durations of the individual packets.
  729. Return: The total duration of all packets, or OP_HOLE if there was a hole.*/
  730. static opus_int32 op_collect_audio_packets(OggOpusFile *_of,
  731. int _durations[255]){
  732. opus_int32 total_duration;
  733. int op_count;
  734. /*Count the durations of all packets in the page.*/
  735. op_count=0;
  736. total_duration=0;
  737. for(;;){
  738. int ret;
  739. /*This takes advantage of undocumented libogg behavior that returned
  740. ogg_packet buffers are valid at least until the next page is
  741. submitted.
  742. Relying on this is not too terrible, as _none_ of the Ogg memory
  743. ownership/lifetime rules are well-documented.
  744. But I can read its code and know this will work.*/
  745. ret=ogg_stream_packetout(&_of->os,_of->op+op_count);
  746. if(!ret)break;
  747. if(OP_UNLIKELY(ret<0)){
  748. /*We shouldn't get holes in the middle of pages.*/
  749. OP_ASSERT(op_count==0);
  750. /*Set the return value and break out of the loop.
  751. We want to make sure op_count gets set to 0, because we've ingested a
  752. page, so any previously loaded packets are now invalid.*/
  753. total_duration=OP_HOLE;
  754. break;
  755. }
  756. /*Unless libogg is broken, we can't get more than 255 packets from a
  757. single page.*/
  758. OP_ASSERT(op_count<255);
  759. _durations[op_count]=op_get_packet_duration(_of->op[op_count].packet,
  760. _of->op[op_count].bytes);
  761. if(OP_LIKELY(_durations[op_count]>0)){
  762. /*With at most 255 packets on a page, this can't overflow.*/
  763. total_duration+=_durations[op_count++];
  764. }
  765. /*Ignore packets with an invalid TOC sequence.*/
  766. else if(op_count>0){
  767. /*But save the granule position, if there was one.*/
  768. _of->op[op_count-1].granulepos=_of->op[op_count].granulepos;
  769. }
  770. }
  771. _of->op_pos=0;
  772. _of->op_count=op_count;
  773. return total_duration;
  774. }
  775. /*Starting from current cursor position, get the initial PCM offset of the next
  776. page.
  777. This also validates the granule position on the first page with a completed
  778. audio data packet, as required by the spec.
  779. If this link is completely empty (no pages with completed packets), then this
  780. function sets pcm_start=pcm_end=0 and returns the BOS page of the next link
  781. (if any).
  782. In the seekable case, we initialize pcm_end=-1 before calling this function,
  783. so that later we can detect that the link was empty before calling
  784. op_find_final_pcm_offset().
  785. [inout] _link: The link for which to find pcm_start.
  786. [out] _og: Returns the BOS page of the next link if this link was empty.
  787. In the unseekable case, we can then feed this to
  788. op_fetch_headers() to start the next link.
  789. The caller may pass NULL (e.g., for seekable streams), in
  790. which case this page will be discarded.
  791. Return: 0 on success, 1 if there is a buffered BOS page available, or a
  792. negative value on unrecoverable error.*/
  793. static int op_find_initial_pcm_offset(OggOpusFile *_of,
  794. OggOpusLink *_link,ogg_page *_og){
  795. ogg_page og;
  796. opus_int64 page_offset;
  797. ogg_int64_t pcm_start;
  798. ogg_int64_t prev_packet_gp;
  799. ogg_int64_t cur_page_gp;
  800. ogg_uint32_t serialno;
  801. opus_int32 total_duration;
  802. int durations[255];
  803. int cur_page_eos;
  804. int op_count;
  805. int pi;
  806. if(_og==NULL)_og=&og;
  807. serialno=_of->os.serialno;
  808. op_count=0;
  809. /*We shouldn't have to initialize total_duration, but gcc is too dumb to
  810. figure out that op_count>0 implies we've been through the whole loop at
  811. least once.*/
  812. total_duration=0;
  813. do{
  814. page_offset=op_get_next_page(_of,_og,_of->end);
  815. /*We should get a page unless the file is truncated or mangled.
  816. Otherwise there are no audio data packets in the whole logical stream.*/
  817. if(OP_UNLIKELY(page_offset<0)){
  818. /*Fail if there was a read error.*/
  819. if(page_offset<OP_FALSE)return (int)page_offset;
  820. /*Fail if the pre-skip is non-zero, since it's asking us to skip more
  821. samples than exist.*/
  822. if(_link->head.pre_skip>0)return OP_EBADTIMESTAMP;
  823. /*Set pcm_end and end_offset so we can skip the call to
  824. op_find_final_pcm_offset().*/
  825. _link->pcm_start=_link->pcm_end=0;
  826. _link->end_offset=_link->data_offset;
  827. return 0;
  828. }
  829. /*Similarly, if we hit the next link in the chain, we've gone too far.*/
  830. if(OP_UNLIKELY(ogg_page_bos(_og))){
  831. if(_link->head.pre_skip>0)return OP_EBADTIMESTAMP;
  832. /*Set pcm_end and end_offset so we can skip the call to
  833. op_find_final_pcm_offset().*/
  834. _link->pcm_end=_link->pcm_start=0;
  835. _link->end_offset=_link->data_offset;
  836. /*Tell the caller we've got a buffered page for them.*/
  837. return 1;
  838. }
  839. /*Ignore pages from other streams (not strictly necessary, because of the
  840. checks in ogg_stream_pagein(), but saves some work).*/
  841. if(serialno!=(ogg_uint32_t)ogg_page_serialno(_og))continue;
  842. ogg_stream_pagein(&_of->os,_og);
  843. /*Bitrate tracking: add the header's bytes here.
  844. The body bytes are counted when we consume the packets.*/
  845. _of->bytes_tracked+=_og->header_len;
  846. /*Count the durations of all packets in the page.*/
  847. do total_duration=op_collect_audio_packets(_of,durations);
  848. /*Ignore holes.*/
  849. while(OP_UNLIKELY(total_duration<0));
  850. op_count=_of->op_count;
  851. }
  852. while(op_count<=0);
  853. /*We found the first page with a completed audio data packet: actually look
  854. at the granule position.
  855. RFC 3533 says, "A special value of -1 (in two's complement) indicates that
  856. no packets finish on this page," which does not say that a granule
  857. position that is NOT -1 indicates that some packets DO finish on that page
  858. (even though this was the intention, libogg itself violated this intention
  859. for years before we fixed it).
  860. The Ogg Opus specification only imposes its start-time requirements
  861. on the granule position of the first page with completed packets,
  862. so we ignore any set granule positions until then.*/
  863. cur_page_gp=_of->op[op_count-1].granulepos;
  864. /*But getting a packet without a valid granule position on the page is not
  865. okay.*/
  866. if(cur_page_gp==-1)return OP_EBADTIMESTAMP;
  867. cur_page_eos=_of->op[op_count-1].e_o_s;
  868. if(OP_LIKELY(!cur_page_eos)){
  869. /*The EOS flag wasn't set.
  870. Work backwards from the provided granule position to get the starting PCM
  871. offset.*/
  872. if(OP_UNLIKELY(op_granpos_add(&pcm_start,cur_page_gp,-total_duration)<0)){
  873. /*The starting granule position MUST not be smaller than the amount of
  874. audio on the first page with completed packets.*/
  875. return OP_EBADTIMESTAMP;
  876. }
  877. }
  878. else{
  879. /*The first page with completed packets was also the last.*/
  880. if(OP_LIKELY(op_granpos_add(&pcm_start,cur_page_gp,-total_duration)<0)){
  881. /*If there's less audio on the page than indicated by the granule
  882. position, then we're doing end-trimming, and the starting PCM offset
  883. is zero by spec mandate.*/
  884. pcm_start=0;
  885. /*However, the end-trimming MUST not ask us to trim more samples than
  886. exist after applying the pre-skip.*/
  887. if(OP_UNLIKELY(op_granpos_cmp(cur_page_gp,_link->head.pre_skip)<0)){
  888. return OP_EBADTIMESTAMP;
  889. }
  890. }
  891. }
  892. /*Timestamp the individual packets.*/
  893. prev_packet_gp=pcm_start;
  894. for(pi=0;pi<op_count;pi++){
  895. if(cur_page_eos){
  896. ogg_int64_t diff;
  897. OP_ALWAYS_TRUE(!op_granpos_diff(&diff,cur_page_gp,prev_packet_gp));
  898. diff=durations[pi]-diff;
  899. /*If we have samples to trim...*/
  900. if(diff>0){
  901. /*If we trimmed the entire packet, stop (the spec says encoders
  902. shouldn't do this, but we support it anyway).*/
  903. if(OP_UNLIKELY(diff>durations[pi]))break;
  904. _of->op[pi].granulepos=prev_packet_gp=cur_page_gp;
  905. /*Move the EOS flag to this packet, if necessary, so we'll trim the
  906. samples.*/
  907. _of->op[pi].e_o_s=1;
  908. continue;
  909. }
  910. }
  911. /*Update the granule position as normal.*/
  912. OP_ALWAYS_TRUE(!op_granpos_add(&_of->op[pi].granulepos,
  913. prev_packet_gp,durations[pi]));
  914. prev_packet_gp=_of->op[pi].granulepos;
  915. }
  916. /*Update the packet count after end-trimming.*/
  917. _of->op_count=pi;
  918. _of->cur_discard_count=_link->head.pre_skip;
  919. _of->prev_packet_gp=_link->pcm_start=pcm_start;
  920. _of->prev_page_offset=page_offset;
  921. return 0;
  922. }
  923. /*Starting from current cursor position, get the final PCM offset of the
  924. previous page.
  925. This also validates the duration of the link, which, while not strictly
  926. required by the spec, we need to ensure duration calculations don't
  927. overflow.
  928. This is only done for seekable sources.
  929. We must validate that op_find_initial_pcm_offset() succeeded for this link
  930. before calling this function, otherwise it will scan the entire stream
  931. backwards until it reaches the start, and then fail.*/
  932. static int op_find_final_pcm_offset(OggOpusFile *_of,
  933. const ogg_uint32_t *_serialnos,int _nserialnos,OggOpusLink *_link,
  934. opus_int64 _offset,ogg_uint32_t _end_serialno,ogg_int64_t _end_gp,
  935. ogg_int64_t *_total_duration){
  936. ogg_int64_t total_duration;
  937. ogg_int64_t duration;
  938. ogg_uint32_t cur_serialno;
  939. /*For the time being, fetch end PCM offset the simple way.*/
  940. cur_serialno=_link->serialno;
  941. if(_end_serialno!=cur_serialno||_end_gp==-1){
  942. _offset=op_get_last_page(_of,&_end_gp,_offset,
  943. cur_serialno,_serialnos,_nserialnos);
  944. if(OP_UNLIKELY(_offset<0))return (int)_offset;
  945. }
  946. /*At worst we should have found the first page with completed packets.*/
  947. if(OP_UNLIKELY(_offset<_link->data_offset))return OP_EBADLINK;
  948. /*This implementation requires that the difference between the first and last
  949. granule positions in each link be representable in a signed, 64-bit
  950. number, and that each link also have at least as many samples as the
  951. pre-skip requires.*/
  952. if(OP_UNLIKELY(op_granpos_diff(&duration,_end_gp,_link->pcm_start)<0)
  953. ||OP_UNLIKELY(duration<_link->head.pre_skip)){
  954. return OP_EBADTIMESTAMP;
  955. }
  956. /*We also require that the total duration be representable in a signed,
  957. 64-bit number.*/
  958. duration-=_link->head.pre_skip;
  959. total_duration=*_total_duration;
  960. if(OP_UNLIKELY(OP_INT64_MAX-duration<total_duration))return OP_EBADTIMESTAMP;
  961. *_total_duration=total_duration+duration;
  962. _link->pcm_end=_end_gp;
  963. _link->end_offset=_offset;
  964. return 0;
  965. }
  966. /*Rescale the number _x from the range [0,_from] to [0,_to].
  967. _from and _to must be positive.*/
  968. static opus_int64 op_rescale64(opus_int64 _x,opus_int64 _from,opus_int64 _to){
  969. opus_int64 frac;
  970. opus_int64 ret;
  971. int i;
  972. if(_x>=_from)return _to;
  973. if(_x<=0)return 0;
  974. frac=0;
  975. for(i=0;i<63;i++){
  976. frac<<=1;
  977. OP_ASSERT(_x<=_from);
  978. if(_x>=_from>>1){
  979. _x-=_from-_x;
  980. frac|=1;
  981. }
  982. else _x<<=1;
  983. }
  984. ret=0;
  985. for(i=0;i<63;i++){
  986. if(frac&1)ret=(ret&_to&1)+(ret>>1)+(_to>>1);
  987. else ret>>=1;
  988. frac>>=1;
  989. }
  990. return ret;
  991. }
  992. /*The minimum granule position spacing allowed for making predictions.
  993. This corresponds to about 1 second of audio at 48 kHz for both Opus and
  994. Vorbis, or one keyframe interval in Theora with the default keyframe spacing
  995. of 256.*/
  996. #define OP_GP_SPACING_MIN (48000)
  997. /*Try to estimate the location of the next link using the current seek
  998. records, assuming the initial granule position of any streams we've found is
  999. 0.*/
  1000. static opus_int64 op_predict_link_start(const OpusSeekRecord *_sr,int _nsr,
  1001. opus_int64 _searched,opus_int64 _end_searched,opus_int32 _bias){
  1002. opus_int64 bisect;
  1003. int sri;
  1004. int srj;
  1005. /*Require that we be at least OP_CHUNK_SIZE from the end.
  1006. We don't require that we be at least OP_CHUNK_SIZE from the beginning,
  1007. because if we are we'll just scan forward without seeking.*/
  1008. _end_searched-=OP_CHUNK_SIZE;
  1009. if(_searched>=_end_searched)return -1;
  1010. bisect=_end_searched;
  1011. for(sri=0;sri<_nsr;sri++){
  1012. ogg_int64_t gp1;
  1013. ogg_int64_t gp2_min;
  1014. ogg_uint32_t serialno1;
  1015. opus_int64 offset1;
  1016. /*If the granule position is negative, either it's invalid or we'd cause
  1017. overflow.*/
  1018. gp1=_sr[sri].gp;
  1019. if(gp1<0)continue;
  1020. /*We require some minimum distance between granule positions to make an
  1021. estimate.
  1022. We don't actually know what granule position scheme is being used,
  1023. because we have no idea what kind of stream these came from.
  1024. Therefore we require a minimum spacing between them, with the
  1025. expectation that while bitrates and granule position increments might
  1026. vary locally in quite complex ways, they are globally smooth.*/
  1027. if(OP_UNLIKELY(op_granpos_add(&gp2_min,gp1,OP_GP_SPACING_MIN)<0)){
  1028. /*No granule position would satisfy us.*/
  1029. continue;
  1030. }
  1031. offset1=_sr[sri].offset;
  1032. serialno1=_sr[sri].serialno;
  1033. for(srj=sri;srj-->0;){
  1034. ogg_int64_t gp2;
  1035. opus_int64 offset2;
  1036. opus_int64 num;
  1037. ogg_int64_t den;
  1038. ogg_int64_t ipart;
  1039. gp2=_sr[srj].gp;
  1040. if(gp2<gp2_min)continue;
  1041. /*Oh, and also make sure these came from the same stream.*/
  1042. if(_sr[srj].serialno!=serialno1)continue;
  1043. offset2=_sr[srj].offset;
  1044. /*For once, we can subtract with impunity.*/
  1045. den=gp2-gp1;
  1046. ipart=gp2/den;
  1047. num=offset2-offset1;
  1048. OP_ASSERT(num>0);
  1049. if(ipart>0&&(offset2-_searched)/ipart<num)continue;
  1050. offset2-=ipart*num;
  1051. gp2-=ipart*den;
  1052. offset2-=op_rescale64(gp2,den,num)-_bias;
  1053. if(offset2<_searched)continue;
  1054. bisect=OP_MIN(bisect,offset2);
  1055. break;
  1056. }
  1057. }
  1058. return bisect>=_end_searched?-1:bisect;
  1059. }
  1060. /*Finds each bitstream link, one at a time, using a bisection search.
  1061. This has to begin by knowing the offset of the first link's initial page.*/
  1062. static int op_bisect_forward_serialno(OggOpusFile *_of,
  1063. opus_int64 _searched,OpusSeekRecord *_sr,int _csr,
  1064. ogg_uint32_t **_serialnos,int *_nserialnos,int *_cserialnos){
  1065. ogg_page og;
  1066. OggOpusLink *links;
  1067. int nlinks;
  1068. int clinks;
  1069. ogg_uint32_t *serialnos;
  1070. int nserialnos;
  1071. ogg_int64_t total_duration;
  1072. int nsr;
  1073. int ret;
  1074. links=_of->links;
  1075. nlinks=clinks=_of->nlinks;
  1076. total_duration=0;
  1077. /*We start with one seek record, for the last page in the file.
  1078. We build up a list of records for places we seek to during link
  1079. enumeration.
  1080. This list is kept sorted in reverse order.
  1081. We only care about seek locations that were _not_ in the current link,
  1082. therefore we can add them one at a time to the end of the list as we
  1083. improve the lower bound on the location where the next link starts.*/
  1084. nsr=1;
  1085. for(;;){
  1086. opus_int64 end_searched;
  1087. opus_int64 bisect;
  1088. opus_int64 next;
  1089. opus_int64 last;
  1090. ogg_int64_t end_offset;
  1091. ogg_int64_t end_gp;
  1092. int sri;
  1093. serialnos=*_serialnos;
  1094. nserialnos=*_nserialnos;
  1095. if(OP_UNLIKELY(nlinks>=clinks)){
  1096. if(OP_UNLIKELY(clinks>INT_MAX-1>>1))return OP_EFAULT;
  1097. clinks=2*clinks+1;
  1098. OP_ASSERT(nlinks<clinks);
  1099. links=(OggOpusLink *)_ogg_realloc(links,sizeof(*links)*clinks);
  1100. if(OP_UNLIKELY(links==NULL))return OP_EFAULT;
  1101. _of->links=links;
  1102. }
  1103. /*Invariants:
  1104. We have the headers and serial numbers for the link beginning at 'begin'.
  1105. We have the offset and granule position of the last page in the file
  1106. (potentially not a page we care about).*/
  1107. /*Scan the seek records we already have to save us some bisection.*/
  1108. for(sri=0;sri<nsr;sri++){
  1109. if(op_lookup_serialno(_sr[sri].serialno,serialnos,nserialnos))break;
  1110. }
  1111. /*Is the last page in our current list of serial numbers?*/
  1112. if(sri<=0)break;
  1113. /*Last page wasn't found.
  1114. We have at least one more link.*/
  1115. last=-1;
  1116. end_searched=_sr[sri-1].search_start;
  1117. next=_sr[sri-1].offset;
  1118. end_gp=-1;
  1119. if(sri<nsr){
  1120. _searched=_sr[sri].offset+_sr[sri].size;
  1121. if(_sr[sri].serialno==links[nlinks-1].serialno){
  1122. end_gp=_sr[sri].gp;
  1123. end_offset=_sr[sri].offset;
  1124. }
  1125. }
  1126. nsr=sri;
  1127. bisect=-1;
  1128. /*If we've already found the end of at least one link, try to pick the
  1129. first bisection point at twice the average link size.
  1130. This is a good choice for files with lots of links that are all about the
  1131. same size.*/
  1132. if(nlinks>1){
  1133. opus_int64 last_offset;
  1134. opus_int64 avg_link_size;
  1135. opus_int64 upper_limit;
  1136. last_offset=links[nlinks-1].offset;
  1137. avg_link_size=last_offset/(nlinks-1);
  1138. upper_limit=end_searched-OP_CHUNK_SIZE-avg_link_size;
  1139. if(OP_LIKELY(last_offset>_searched-avg_link_size)
  1140. &&OP_LIKELY(last_offset<upper_limit)){
  1141. bisect=last_offset+avg_link_size;
  1142. if(OP_LIKELY(bisect<upper_limit))bisect+=avg_link_size;
  1143. }
  1144. }
  1145. /*We guard against garbage separating the last and first pages of two
  1146. links below.*/
  1147. while(_searched<end_searched){
  1148. opus_int32 next_bias;
  1149. /*If we don't have a better estimate, use simple bisection.*/
  1150. if(bisect==-1)bisect=_searched+(end_searched-_searched>>1);
  1151. /*If we're within OP_CHUNK_SIZE of the start, scan forward.*/
  1152. if(bisect-_searched<OP_CHUNK_SIZE)bisect=_searched;
  1153. /*Otherwise we're skipping data.
  1154. Forget the end page, if we saw one, as we might miss a later one.*/
  1155. else end_gp=-1;
  1156. ret=op_seek_helper(_of,bisect);
  1157. if(OP_UNLIKELY(ret<0))return ret;
  1158. last=op_get_next_page(_of,&og,_sr[nsr-1].offset);
  1159. if(OP_UNLIKELY(last<OP_FALSE))return (int)last;
  1160. next_bias=0;
  1161. if(last==OP_FALSE)end_searched=bisect;
  1162. else{
  1163. ogg_uint32_t serialno;
  1164. ogg_int64_t gp;
  1165. serialno=ogg_page_serialno(&og);
  1166. gp=ogg_page_granulepos(&og);
  1167. if(!op_lookup_serialno(serialno,serialnos,nserialnos)){
  1168. end_searched=bisect;
  1169. next=last;
  1170. /*In reality we should always have enough room, but be paranoid.*/
  1171. if(OP_LIKELY(nsr<_csr)){
  1172. _sr[nsr].search_start=bisect;
  1173. _sr[nsr].offset=last;
  1174. OP_ASSERT(_of->offset-last>=0);
  1175. OP_ASSERT(_of->offset-last<=OP_PAGE_SIZE_MAX);
  1176. _sr[nsr].size=(opus_int32)(_of->offset-last);
  1177. _sr[nsr].serialno=serialno;
  1178. _sr[nsr].gp=gp;
  1179. nsr++;
  1180. }
  1181. }
  1182. else{
  1183. _searched=_of->offset;
  1184. next_bias=OP_CHUNK_SIZE;
  1185. if(serialno==links[nlinks-1].serialno){
  1186. /*This page was from the stream we want, remember it.
  1187. If it's the last such page in the link, we won't have to go back
  1188. looking for it later.*/
  1189. end_gp=gp;
  1190. end_offset=last;
  1191. }
  1192. }
  1193. }
  1194. bisect=op_predict_link_start(_sr,nsr,_searched,end_searched,next_bias);
  1195. }
  1196. /*Bisection point found.
  1197. Get the final granule position of the previous link, assuming
  1198. op_find_initial_pcm_offset() didn't already determine the link was
  1199. empty.*/
  1200. if(OP_LIKELY(links[nlinks-1].pcm_end==-1)){
  1201. if(end_gp==-1){
  1202. /*If we don't know where the end page is, we'll have to seek back and
  1203. look for it, starting from the end of the link.*/
  1204. end_offset=next;
  1205. /*Also forget the last page we read.
  1206. It won't be available after the seek.*/
  1207. last=-1;
  1208. }
  1209. ret=op_find_final_pcm_offset(_of,serialnos,nserialnos,
  1210. links+nlinks-1,end_offset,links[nlinks-1].serialno,end_gp,
  1211. &total_duration);
  1212. if(OP_UNLIKELY(ret<0))return ret;
  1213. }
  1214. if(last!=next){
  1215. /*The last page we read was not the first page the next link.
  1216. Move the cursor position to the offset of that first page.
  1217. This only performs an actual seek if the first page of the next link
  1218. does not start at the end of the last page from the current Opus
  1219. stream with a valid granule position.*/
  1220. ret=op_seek_helper(_of,next);
  1221. if(OP_UNLIKELY(ret<0))return ret;
  1222. }
  1223. ret=op_fetch_headers(_of,&links[nlinks].head,&links[nlinks].tags,
  1224. _serialnos,_nserialnos,_cserialnos,last!=next?NULL:&og);
  1225. if(OP_UNLIKELY(ret<0))return ret;
  1226. links[nlinks].offset=next;
  1227. links[nlinks].data_offset=_of->offset;
  1228. links[nlinks].serialno=_of->os.serialno;
  1229. links[nlinks].pcm_end=-1;
  1230. /*This might consume a page from the next link, however the next bisection
  1231. always starts with a seek.*/
  1232. ret=op_find_initial_pcm_offset(_of,links+nlinks,NULL);
  1233. if(OP_UNLIKELY(ret<0))return ret;
  1234. _searched=_of->offset;
  1235. /*Mark the current link count so it can be cleaned up on error.*/
  1236. _of->nlinks=++nlinks;
  1237. }
  1238. /*Last page is in the starting serialno list, so we've reached the last link.
  1239. Now find the last granule position for it (if we didn't the first time we
  1240. looked at the end of the stream, and if op_find_initial_pcm_offset()
  1241. didn't already determine the link was empty).*/
  1242. if(OP_LIKELY(links[nlinks-1].pcm_end==-1)){
  1243. ret=op_find_final_pcm_offset(_of,serialnos,nserialnos,
  1244. links+nlinks-1,_sr[0].offset,_sr[0].serialno,_sr[0].gp,&total_duration);
  1245. if(OP_UNLIKELY(ret<0))return ret;
  1246. }
  1247. /*Trim back the links array if necessary.*/
  1248. links=(OggOpusLink *)_ogg_realloc(links,sizeof(*links)*nlinks);
  1249. if(OP_LIKELY(links!=NULL))_of->links=links;
  1250. /*We also don't need these anymore.*/
  1251. _ogg_free(*_serialnos);
  1252. *_serialnos=NULL;
  1253. *_cserialnos=*_nserialnos=0;
  1254. return 0;
  1255. }
  1256. static void op_update_gain(OggOpusFile *_of){
  1257. OpusHead *head;
  1258. opus_int32 gain_q8;
  1259. int li;
  1260. /*If decode isn't ready, then we'll apply the gain when we initialize the
  1261. decoder.*/
  1262. if(_of->ready_state<OP_INITSET)return;
  1263. gain_q8=_of->gain_offset_q8;
  1264. li=_of->seekable?_of->cur_link:0;
  1265. head=&_of->links[li].head;
  1266. /*We don't have to worry about overflow here because the header gain and
  1267. track gain must lie in the range [-32768,32767], and the user-supplied
  1268. offset has been pre-clamped to [-98302,98303].*/
  1269. switch(_of->gain_type){
  1270. case OP_ALBUM_GAIN:{
  1271. int album_gain_q8;
  1272. album_gain_q8=0;
  1273. opus_tags_get_album_gain(&_of->links[li].tags,&album_gain_q8);
  1274. gain_q8+=album_gain_q8;
  1275. gain_q8+=head->output_gain;
  1276. }break;
  1277. case OP_TRACK_GAIN:{
  1278. int track_gain_q8;
  1279. track_gain_q8=0;
  1280. opus_tags_get_track_gain(&_of->links[li].tags,&track_gain_q8);
  1281. gain_q8+=track_gain_q8;
  1282. gain_q8+=head->output_gain;
  1283. }break;
  1284. case OP_HEADER_GAIN:gain_q8+=head->output_gain;break;
  1285. case OP_ABSOLUTE_GAIN:break;
  1286. default:OP_ASSERT(0);
  1287. }
  1288. gain_q8=OP_CLAMP(-32768,gain_q8,32767);
  1289. OP_ASSERT(_of->od!=NULL);
  1290. #if defined(OPUS_SET_GAIN)
  1291. opus_multistream_decoder_ctl(_of->od,OPUS_SET_GAIN(gain_q8));
  1292. #else
  1293. /*A fallback that works with both float and fixed-point is a bunch of work,
  1294. so just force people to use a sufficiently new version.
  1295. This is deployed well enough at this point that this shouldn't be a burden.*/
  1296. # error "libopus 1.0.1 or later required"
  1297. #endif
  1298. }
  1299. static int op_make_decode_ready(OggOpusFile *_of){
  1300. const OpusHead *head;
  1301. int li;
  1302. int stream_count;
  1303. int coupled_count;
  1304. int channel_count;
  1305. if(_of->ready_state>OP_STREAMSET)return 0;
  1306. if(OP_UNLIKELY(_of->ready_state<OP_STREAMSET))return OP_EFAULT;
  1307. li=_of->seekable?_of->cur_link:0;
  1308. head=&_of->links[li].head;
  1309. stream_count=head->stream_count;
  1310. coupled_count=head->coupled_count;
  1311. channel_count=head->channel_count;
  1312. /*Check to see if the current decoder is compatible with the current link.*/
  1313. if(_of->od!=NULL&&_of->od_stream_count==stream_count
  1314. &&_of->od_coupled_count==coupled_count&&_of->od_channel_count==channel_count
  1315. &&memcmp(_of->od_mapping,head->mapping,
  1316. sizeof(*head->mapping)*channel_count)==0){
  1317. opus_multistream_decoder_ctl(_of->od,OPUS_RESET_STATE);
  1318. }
  1319. else{
  1320. int err;
  1321. opus_multistream_decoder_destroy(_of->od);
  1322. _of->od=opus_multistream_decoder_create(48000,channel_count,
  1323. stream_count,coupled_count,head->mapping,&err);
  1324. if(_of->od==NULL)return OP_EFAULT;
  1325. _of->od_stream_count=stream_count;
  1326. _of->od_coupled_count=coupled_count;
  1327. _of->od_channel_count=channel_count;
  1328. memcpy(_of->od_mapping,head->mapping,sizeof(*head->mapping)*channel_count);
  1329. }
  1330. _of->ready_state=OP_INITSET;
  1331. _of->bytes_tracked=0;
  1332. _of->samples_tracked=0;
  1333. #if !defined(OP_FIXED_POINT)
  1334. _of->state_channel_count=0;
  1335. /*Use the serial number for the PRNG seed to get repeatable output for
  1336. straight play-throughs.*/
  1337. _of->dither_seed=_of->links[li].serialno;
  1338. #endif
  1339. op_update_gain(_of);
  1340. return 0;
  1341. }
  1342. static int op_open_seekable2_impl(OggOpusFile *_of){
  1343. /*64 seek records should be enough for anybody.
  1344. Actually, with a bisection search in a 63-bit range down to OP_CHUNK_SIZE
  1345. granularity, much more than enough.*/
  1346. OpusSeekRecord sr[64];
  1347. opus_int64 data_offset;
  1348. int ret;
  1349. /*We can seek, so set out learning all about this file.*/
  1350. (*_of->callbacks.seek)(_of->source,0,SEEK_END);
  1351. _of->offset=_of->end=(*_of->callbacks.tell)(_of->source);
  1352. if(OP_UNLIKELY(_of->end<0))return OP_EREAD;
  1353. data_offset=_of->links[0].data_offset;
  1354. if(OP_UNLIKELY(_of->end<data_offset))return OP_EBADLINK;
  1355. /*Get the offset of the last page of the physical bitstream, or, if we're
  1356. lucky, the last Opus page of the first link, as most Ogg Opus files will
  1357. contain a single logical bitstream.*/
  1358. ret=op_get_prev_page_serial(_of,sr,_of->end,
  1359. _of->links[0].serialno,_of->serialnos,_of->nserialnos);
  1360. if(OP_UNLIKELY(ret<0))return ret;
  1361. /*If there's any trailing junk, forget about it.*/
  1362. _of->end=sr[0].offset+sr[0].size;
  1363. if(OP_UNLIKELY(_of->end<data_offset))return OP_EBADLINK;
  1364. /*Now enumerate the bitstream structure.*/
  1365. return op_bisect_forward_serialno(_of,data_offset,sr,sizeof(sr)/sizeof(*sr),
  1366. &_of->serialnos,&_of->nserialnos,&_of->cserialnos);
  1367. }
  1368. static int op_open_seekable2(OggOpusFile *_of){
  1369. ogg_sync_state oy_start;
  1370. ogg_stream_state os_start;
  1371. ogg_packet *op_start;
  1372. opus_int64 prev_page_offset;
  1373. opus_int64 start_offset;
  1374. int start_op_count;
  1375. int ret;
  1376. /*We're partially open and have a first link header state in storage in _of.
  1377. Save off that stream state so we can come back to it.
  1378. It would be simpler to just dump all this state and seek back to
  1379. links[0].data_offset when we're done.
  1380. But we do the extra work to allow us to seek back to _exactly_ the same
  1381. stream position we're at now.
  1382. This allows, e.g., the HTTP backend to continue reading from the original
  1383. connection (if it's still available), instead of opening a new one.
  1384. This means we can open and start playing a normal Opus file with a single
  1385. link and reasonable packet sizes using only two HTTP requests.*/
  1386. start_op_count=_of->op_count;
  1387. /*This is a bit too large to put on the stack unconditionally.*/
  1388. op_start=(ogg_packet *)_ogg_malloc(sizeof(*op_start)*start_op_count);
  1389. if(op_start==NULL)return OP_EFAULT;
  1390. *&oy_start=_of->oy;
  1391. *&os_start=_of->os;
  1392. prev_page_offset=_of->prev_page_offset;
  1393. start_offset=_of->offset;
  1394. memcpy(op_start,_of->op,sizeof(*op_start)*start_op_count);
  1395. OP_ASSERT((*_of->callbacks.tell)(_of->source)==op_position(_of));
  1396. ogg_sync_init(&_of->oy);
  1397. ogg_stream_init(&_of->os,-1);
  1398. ret=op_open_seekable2_impl(_of);
  1399. /*Restore the old stream state.*/
  1400. ogg_stream_clear(&_of->os);
  1401. ogg_sync_clear(&_of->oy);
  1402. *&_of->oy=*&oy_start;
  1403. *&_of->os=*&os_start;
  1404. _of->offset=start_offset;
  1405. _of->op_count=start_op_count;
  1406. memcpy(_of->op,op_start,sizeof(*_of->op)*start_op_count);
  1407. _ogg_free(op_start);
  1408. _of->prev_packet_gp=_of->links[0].pcm_start;
  1409. _of->prev_page_offset=prev_page_offset;
  1410. _of->cur_discard_count=_of->links[0].head.pre_skip;
  1411. if(OP_UNLIKELY(ret<0))return ret;
  1412. /*And restore the position indicator.*/
  1413. ret=(*_of->callbacks.seek)(_of->source,op_position(_of),SEEK_SET);
  1414. return OP_UNLIKELY(ret<0)?OP_EREAD:0;
  1415. }
  1416. /*Clear out the current logical bitstream decoder.*/
  1417. static void op_decode_clear(OggOpusFile *_of){
  1418. /*We don't actually free the decoder.
  1419. We might be able to re-use it for the next link.*/
  1420. _of->op_count=0;
  1421. _of->od_buffer_size=0;
  1422. _of->prev_packet_gp=-1;
  1423. _of->prev_page_offset=-1;
  1424. if(!_of->seekable){
  1425. OP_ASSERT(_of->ready_state>=OP_INITSET);
  1426. opus_tags_clear(&_of->links[0].tags);
  1427. }
  1428. _of->ready_state=OP_OPENED;
  1429. }
  1430. static void op_clear(OggOpusFile *_of){
  1431. OggOpusLink *links;
  1432. _ogg_free(_of->od_buffer);
  1433. if(_of->od!=NULL)opus_multistream_decoder_destroy(_of->od);
  1434. links=_of->links;
  1435. if(!_of->seekable){
  1436. if(_of->ready_state>OP_OPENED||_of->ready_state==OP_PARTOPEN){
  1437. opus_tags_clear(&links[0].tags);
  1438. }
  1439. }
  1440. else if(OP_LIKELY(links!=NULL)){
  1441. int nlinks;
  1442. int link;
  1443. nlinks=_of->nlinks;
  1444. for(link=0;link<nlinks;link++)opus_tags_clear(&links[link].tags);
  1445. }
  1446. _ogg_free(links);
  1447. _ogg_free(_of->serialnos);
  1448. ogg_stream_clear(&_of->os);
  1449. ogg_sync_clear(&_of->oy);
  1450. if(_of->callbacks.close!=NULL)(*_of->callbacks.close)(_of->source);
  1451. }
  1452. static int op_open1(OggOpusFile *_of,
  1453. void *_source,const OpusFileCallbacks *_cb,
  1454. const unsigned char *_initial_data,size_t _initial_bytes){
  1455. ogg_page og;
  1456. ogg_page *pog;
  1457. int seekable;
  1458. int ret;
  1459. memset(_of,0,sizeof(*_of));
  1460. _of->end=-1;
  1461. _of->source=_source;
  1462. *&_of->callbacks=*_cb;
  1463. /*At a minimum, we need to be able to read data.*/
  1464. if(OP_UNLIKELY(_of->callbacks.read==NULL))return OP_EREAD;
  1465. /*Initialize the framing state.*/
  1466. ogg_sync_init(&_of->oy);
  1467. /*Perhaps some data was previously read into a buffer for testing against
  1468. other stream types.
  1469. Allow initialization from this previously read data (especially as we may
  1470. be reading from a non-seekable stream).
  1471. This requires copying it into a buffer allocated by ogg_sync_buffer() and
  1472. doesn't support seeking, so this is not a good mechanism to use for
  1473. decoding entire files from RAM.*/
  1474. if(_initial_bytes>0){
  1475. char *buffer;
  1476. buffer=ogg_sync_buffer(&_of->oy,_initial_bytes);
  1477. memcpy(buffer,_initial_data,_initial_bytes*sizeof(*buffer));
  1478. ogg_sync_wrote(&_of->oy,_initial_bytes);
  1479. }
  1480. /*Can we seek?
  1481. Stevens suggests the seek test is portable.*/
  1482. seekable=_cb->seek!=NULL&&(*_cb->seek)(_source,0,SEEK_CUR)!=-1;
  1483. /*If seek is implemented, tell must also be implemented.*/
  1484. if(seekable){
  1485. opus_int64 pos;
  1486. if(OP_UNLIKELY(_of->callbacks.tell==NULL))return OP_EINVAL;
  1487. pos=(*_of->callbacks.tell)(_of->source);
  1488. /*If the current position is not equal to the initial bytes consumed,
  1489. absolute seeking will not work.*/
  1490. if(OP_UNLIKELY(pos!=(opus_int64)_initial_bytes))return OP_EINVAL;
  1491. }
  1492. _of->seekable=seekable;
  1493. /*Don't seek yet.
  1494. Set up a 'single' (current) logical bitstream entry for partial open.*/
  1495. _of->links=(OggOpusLink *)_ogg_malloc(sizeof(*_of->links));
  1496. /*The serialno gets filled in later by op_fetch_headers().*/
  1497. ogg_stream_init(&_of->os,-1);
  1498. pog=NULL;
  1499. for(;;){
  1500. /*Fetch all BOS pages, store the Opus header and all seen serial numbers,
  1501. and load subsequent Opus setup headers.*/
  1502. ret=op_fetch_headers(_of,&_of->links[0].head,&_of->links[0].tags,
  1503. &_of->serialnos,&_of->nserialnos,&_of->cserialnos,pog);
  1504. if(OP_UNLIKELY(ret<0))break;
  1505. _of->nlinks=1;
  1506. _of->links[0].offset=0;
  1507. _of->links[0].data_offset=_of->offset;
  1508. _of->links[0].pcm_end=-1;
  1509. _of->links[0].serialno=_of->os.serialno;
  1510. /*Fetch the initial PCM offset.*/
  1511. ret=op_find_initial_pcm_offset(_of,_of->links,&og);
  1512. if(seekable||OP_LIKELY(ret<=0))break;
  1513. /*This link was empty, but we already have the BOS page for the next one in
  1514. og.
  1515. We can't seek, so start processing the next link right now.*/
  1516. opus_tags_clear(&_of->links[0].tags);
  1517. _of->nlinks=0;
  1518. if(!seekable)_of->cur_link++;
  1519. pog=&og;
  1520. }
  1521. if(OP_LIKELY(ret>=0))_of->ready_state=OP_PARTOPEN;
  1522. return ret;
  1523. }
  1524. static int op_open2(OggOpusFile *_of){
  1525. int ret;
  1526. OP_ASSERT(_of->ready_state==OP_PARTOPEN);
  1527. if(_of->seekable){
  1528. _of->ready_state=OP_OPENED;
  1529. ret=op_open_seekable2(_of);
  1530. }
  1531. else ret=0;
  1532. if(OP_LIKELY(ret>=0)){
  1533. /*We have buffered packets from op_find_initial_pcm_offset().
  1534. Move to OP_INITSET so we can use them.*/
  1535. _of->ready_state=OP_STREAMSET;
  1536. ret=op_make_decode_ready(_of);
  1537. if(OP_LIKELY(ret>=0))return 0;
  1538. }
  1539. /*Don't auto-close the stream on failure.*/
  1540. _of->callbacks.close=NULL;
  1541. op_clear(_of);
  1542. return ret;
  1543. }
  1544. OggOpusFile *op_test_callbacks(void *_source,const OpusFileCallbacks *_cb,
  1545. const unsigned char *_initial_data,size_t _initial_bytes,int *_error){
  1546. OggOpusFile *of;
  1547. int ret;
  1548. of=(OggOpusFile *)_ogg_malloc(sizeof(*of));
  1549. ret=OP_EFAULT;
  1550. if(OP_LIKELY(of!=NULL)){
  1551. ret=op_open1(of,_source,_cb,_initial_data,_initial_bytes);
  1552. if(OP_LIKELY(ret>=0)){
  1553. if(_error!=NULL)*_error=0;
  1554. return of;
  1555. }
  1556. /*Don't auto-close the stream on failure.*/
  1557. of->callbacks.close=NULL;
  1558. op_clear(of);
  1559. _ogg_free(of);
  1560. }
  1561. if(_error!=NULL)*_error=ret;
  1562. return NULL;
  1563. }
  1564. OggOpusFile *op_open_callbacks(void *_source,const OpusFileCallbacks *_cb,
  1565. const unsigned char *_initial_data,size_t _initial_bytes,int *_error){
  1566. OggOpusFile *of;
  1567. of=op_test_callbacks(_source,_cb,_initial_data,_initial_bytes,_error);
  1568. if(OP_LIKELY(of!=NULL)){
  1569. int ret;
  1570. ret=op_open2(of);
  1571. if(OP_LIKELY(ret>=0))return of;
  1572. if(_error!=NULL)*_error=ret;
  1573. _ogg_free(of);
  1574. }
  1575. return NULL;
  1576. }
  1577. /*Convenience routine to clean up from failure for the open functions that
  1578. create their own streams.*/
  1579. static OggOpusFile *op_open_close_on_failure(void *_source,
  1580. const OpusFileCallbacks *_cb,int *_error){
  1581. OggOpusFile *of;
  1582. if(OP_UNLIKELY(_source==NULL)){
  1583. if(_error!=NULL)*_error=OP_EFAULT;
  1584. return NULL;
  1585. }
  1586. of=op_open_callbacks(_source,_cb,NULL,0,_error);
  1587. if(OP_UNLIKELY(of==NULL))(*_cb->close)(_source);
  1588. return of;
  1589. }
  1590. OggOpusFile *op_open_file(const char *_path,int *_error){
  1591. OpusFileCallbacks cb;
  1592. return op_open_close_on_failure(op_fopen(&cb,_path,"rb"),&cb,_error);
  1593. }
  1594. OggOpusFile *op_open_memory(const unsigned char *_data,size_t _size,
  1595. int *_error){
  1596. OpusFileCallbacks cb;
  1597. return op_open_close_on_failure(op_mem_stream_create(&cb,_data,_size),&cb,
  1598. _error);
  1599. }
  1600. /*Convenience routine to clean up from failure for the open functions that
  1601. create their own streams.*/
  1602. static OggOpusFile *op_test_close_on_failure(void *_source,
  1603. const OpusFileCallbacks *_cb,int *_error){
  1604. OggOpusFile *of;
  1605. if(OP_UNLIKELY(_source==NULL)){
  1606. if(_error!=NULL)*_error=OP_EFAULT;
  1607. return NULL;
  1608. }
  1609. of=op_test_callbacks(_source,_cb,NULL,0,_error);
  1610. if(OP_UNLIKELY(of==NULL))(*_cb->close)(_source);
  1611. return of;
  1612. }
  1613. OggOpusFile *op_test_file(const char *_path,int *_error){
  1614. OpusFileCallbacks cb;
  1615. return op_test_close_on_failure(op_fopen(&cb,_path,"rb"),&cb,_error);
  1616. }
  1617. OggOpusFile *op_test_memory(const unsigned char *_data,size_t _size,
  1618. int *_error){
  1619. OpusFileCallbacks cb;
  1620. return op_test_close_on_failure(op_mem_stream_create(&cb,_data,_size),&cb,
  1621. _error);
  1622. }
  1623. int op_test_open(OggOpusFile *_of){
  1624. int ret;
  1625. if(OP_UNLIKELY(_of->ready_state!=OP_PARTOPEN))return OP_EINVAL;
  1626. ret=op_open2(_of);
  1627. /*op_open2() will clear this structure on failure.
  1628. Reset its contents to prevent double-frees in op_free().*/
  1629. if(OP_UNLIKELY(ret<0))memset(_of,0,sizeof(*_of));
  1630. return ret;
  1631. }
  1632. void op_free(OggOpusFile *_of){
  1633. if(OP_LIKELY(_of!=NULL)){
  1634. op_clear(_of);
  1635. _ogg_free(_of);
  1636. }
  1637. }
  1638. int op_seekable(const OggOpusFile *_of){
  1639. return _of->seekable;
  1640. }
  1641. int op_link_count(const OggOpusFile *_of){
  1642. return _of->nlinks;
  1643. }
  1644. ogg_uint32_t op_serialno(const OggOpusFile *_of,int _li){
  1645. if(OP_UNLIKELY(_li>=_of->nlinks))_li=_of->nlinks-1;
  1646. if(!_of->seekable)_li=0;
  1647. return _of->links[_li<0?_of->cur_link:_li].serialno;
  1648. }
  1649. int op_channel_count(const OggOpusFile *_of,int _li){
  1650. return op_head(_of,_li)->channel_count;
  1651. }
  1652. opus_int64 op_raw_total(const OggOpusFile *_of,int _li){
  1653. if(OP_UNLIKELY(_of->ready_state<OP_OPENED)
  1654. ||OP_UNLIKELY(!_of->seekable)
  1655. ||OP_UNLIKELY(_li>=_of->nlinks)){
  1656. return OP_EINVAL;
  1657. }
  1658. if(_li<0)return _of->end-_of->links[0].offset;
  1659. return (_li+1>=_of->nlinks?_of->end:_of->links[_li+1].offset)
  1660. -_of->links[_li].offset;
  1661. }
  1662. ogg_int64_t op_pcm_total(const OggOpusFile *_of,int _li){
  1663. OggOpusLink *links;
  1664. ogg_int64_t diff;
  1665. int nlinks;
  1666. nlinks=_of->nlinks;
  1667. if(OP_UNLIKELY(_of->ready_state<OP_OPENED)
  1668. ||OP_UNLIKELY(!_of->seekable)
  1669. ||OP_UNLIKELY(_li>=nlinks)){
  1670. return OP_EINVAL;
  1671. }
  1672. links=_of->links;
  1673. /*We verify that the granule position differences are larger than the
  1674. pre-skip and that the total duration does not overflow during link
  1675. enumeration, so we don't have to check here.*/
  1676. if(_li<0){
  1677. ogg_int64_t pcm_total;
  1678. int li;
  1679. pcm_total=0;
  1680. for(li=0;li<nlinks;li++){
  1681. OP_ALWAYS_TRUE(!op_granpos_diff(&diff,
  1682. links[li].pcm_end,links[li].pcm_start));
  1683. pcm_total+=diff-links[li].head.pre_skip;
  1684. }
  1685. return pcm_total;
  1686. }
  1687. OP_ALWAYS_TRUE(!op_granpos_diff(&diff,
  1688. links[_li].pcm_end,links[_li].pcm_start));
  1689. return diff-links[_li].head.pre_skip;
  1690. }
  1691. const OpusHead *op_head(const OggOpusFile *_of,int _li){
  1692. if(OP_UNLIKELY(_li>=_of->nlinks))_li=_of->nlinks-1;
  1693. if(!_of->seekable)_li=0;
  1694. return &_of->links[_li<0?_of->cur_link:_li].head;
  1695. }
  1696. const OpusTags *op_tags(const OggOpusFile *_of,int _li){
  1697. if(OP_UNLIKELY(_li>=_of->nlinks))_li=_of->nlinks-1;
  1698. if(!_of->seekable){
  1699. if(_of->ready_state<OP_STREAMSET&&_of->ready_state!=OP_PARTOPEN){
  1700. return NULL;
  1701. }
  1702. _li=0;
  1703. }
  1704. else if(_li<0)_li=_of->ready_state>=OP_STREAMSET?_of->cur_link:0;
  1705. return &_of->links[_li].tags;
  1706. }
  1707. int op_current_link(const OggOpusFile *_of){
  1708. if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL;
  1709. return _of->cur_link;
  1710. }
  1711. /*Compute an average bitrate given a byte and sample count.
  1712. Return: The bitrate in bits per second.*/
  1713. static opus_int32 op_calc_bitrate(opus_int64 _bytes,ogg_int64_t _samples){
  1714. /*These rates are absurd, but let's handle them anyway.*/
  1715. if(OP_UNLIKELY(_bytes>(OP_INT64_MAX-(_samples>>1))/(48000*8))){
  1716. ogg_int64_t den;
  1717. if(OP_UNLIKELY(_bytes/(OP_INT32_MAX/(48000*8))>=_samples)){
  1718. return OP_INT32_MAX;
  1719. }
  1720. den=_samples/(48000*8);
  1721. return (opus_int32)((_bytes+(den>>1))/den);
  1722. }
  1723. if(OP_UNLIKELY(_samples<=0))return OP_INT32_MAX;
  1724. /*This can't actually overflow in normal operation: even with a pre-skip of
  1725. 545 2.5 ms frames with 8 streams running at 1282*8+1 bytes per packet
  1726. (1275 byte frames + Opus framing overhead + Ogg lacing values), that all
  1727. produce a single sample of decoded output, we still don't top 45 Mbps.
  1728. The only way to get bitrates larger than that is with excessive Opus
  1729. padding, more encoded streams than output channels, or lots and lots of
  1730. Ogg pages with no packets on them.*/
  1731. return (opus_int32)OP_MIN((_bytes*48000*8+(_samples>>1))/_samples,
  1732. OP_INT32_MAX);
  1733. }
  1734. opus_int32 op_bitrate(const OggOpusFile *_of,int _li){
  1735. if(OP_UNLIKELY(_of->ready_state<OP_OPENED)||OP_UNLIKELY(!_of->seekable)
  1736. ||OP_UNLIKELY(_li>=_of->nlinks)){
  1737. return OP_EINVAL;
  1738. }
  1739. return op_calc_bitrate(op_raw_total(_of,_li),op_pcm_total(_of,_li));
  1740. }
  1741. opus_int32 op_bitrate_instant(OggOpusFile *_of){
  1742. ogg_int64_t samples_tracked;
  1743. opus_int32 ret;
  1744. if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL;
  1745. samples_tracked=_of->samples_tracked;
  1746. if(OP_UNLIKELY(samples_tracked==0))return OP_FALSE;
  1747. ret=op_calc_bitrate(_of->bytes_tracked,samples_tracked);
  1748. _of->bytes_tracked=0;
  1749. _of->samples_tracked=0;
  1750. return ret;
  1751. }
  1752. /*Fetch and process a page.
  1753. This handles the case where we're at a bitstream boundary and dumps the
  1754. decoding machine.
  1755. If the decoding machine is unloaded, it loads it.
  1756. It also keeps prev_packet_gp up to date (seek and read both use this).
  1757. Return: <0) Error, OP_HOLE (lost packet), or OP_EOF.
  1758. 0) Got at least one audio data packet.*/
  1759. static int op_fetch_and_process_page(OggOpusFile *_of,
  1760. ogg_page *_og,opus_int64 _page_offset,int _spanp,int _ignore_holes){
  1761. OggOpusLink *links;
  1762. ogg_uint32_t cur_serialno;
  1763. int seekable;
  1764. int cur_link;
  1765. int ret;
  1766. /*We shouldn't get here if we have unprocessed packets.*/
  1767. OP_ASSERT(_of->ready_state<OP_INITSET||_of->op_pos>=_of->op_count);
  1768. seekable=_of->seekable;
  1769. links=_of->links;
  1770. cur_link=seekable?_of->cur_link:0;
  1771. cur_serialno=links[cur_link].serialno;
  1772. /*Handle one page.*/
  1773. for(;;){
  1774. ogg_page og;
  1775. OP_ASSERT(_of->ready_state>=OP_OPENED);
  1776. /*If we were given a page to use, use it.*/
  1777. if(_og!=NULL){
  1778. *&og=*_og;
  1779. _og=NULL;
  1780. }
  1781. /*Keep reading until we get a page with the correct serialno.*/
  1782. else _page_offset=op_get_next_page(_of,&og,_of->end);
  1783. /*EOF: Leave uninitialized.*/
  1784. if(_page_offset<0)return _page_offset<OP_FALSE?(int)_page_offset:OP_EOF;
  1785. if(OP_LIKELY(_of->ready_state>=OP_STREAMSET)
  1786. &&cur_serialno!=(ogg_uint32_t)ogg_page_serialno(&og)){
  1787. /*Two possibilities:
  1788. 1) Another stream is multiplexed into this logical section, or*/
  1789. if(OP_LIKELY(!ogg_page_bos(&og)))continue;
  1790. /* 2) Our decoding just traversed a bitstream boundary.*/
  1791. if(!_spanp)return OP_EOF;
  1792. if(OP_LIKELY(_of->ready_state>=OP_INITSET))op_decode_clear(_of);
  1793. }
  1794. /*Bitrate tracking: add the header's bytes here.
  1795. The body bytes are counted when we consume the packets.*/
  1796. else _of->bytes_tracked+=og.header_len;
  1797. /*Do we need to load a new machine before submitting the page?
  1798. This is different in the seekable and non-seekable cases.
  1799. In the seekable case, we already have all the header information loaded
  1800. and cached.
  1801. We just initialize the machine with it and continue on our merry way.
  1802. In the non-seekable (streaming) case, we'll only be at a boundary if we
  1803. just left the previous logical bitstream, and we're now nominally at the
  1804. header of the next bitstream.*/
  1805. if(OP_UNLIKELY(_of->ready_state<OP_STREAMSET)){
  1806. if(seekable){
  1807. ogg_uint32_t serialno;
  1808. int nlinks;
  1809. int li;
  1810. serialno=ogg_page_serialno(&og);
  1811. /*Match the serialno to bitstream section.
  1812. We use this rather than offset positions to avoid problems near
  1813. logical bitstream boundaries.*/
  1814. nlinks=_of->nlinks;
  1815. for(li=0;li<nlinks&&links[li].serialno!=serialno;li++);
  1816. /*Not a desired Opus bitstream section.
  1817. Keep trying.*/
  1818. if(li>=nlinks)continue;
  1819. cur_serialno=serialno;
  1820. _of->cur_link=cur_link=li;
  1821. ogg_stream_reset_serialno(&_of->os,serialno);
  1822. _of->ready_state=OP_STREAMSET;
  1823. /*If we're at the start of this link, initialize the granule position
  1824. and pre-skip tracking.*/
  1825. if(_page_offset<=links[cur_link].data_offset){
  1826. _of->prev_packet_gp=links[cur_link].pcm_start;
  1827. _of->prev_page_offset=-1;
  1828. _of->cur_discard_count=links[cur_link].head.pre_skip;
  1829. /*Ignore a hole at the start of a new link (this is common for
  1830. streams joined in the middle) or after seeking.*/
  1831. _ignore_holes=1;
  1832. }
  1833. }
  1834. else{
  1835. do{
  1836. /*We're streaming.
  1837. Fetch the two header packets, build the info struct.*/
  1838. ret=op_fetch_headers(_of,&links[0].head,&links[0].tags,
  1839. NULL,NULL,NULL,&og);
  1840. if(OP_UNLIKELY(ret<0))return ret;
  1841. /*op_find_initial_pcm_offset() will suppress any initial hole for us,
  1842. so no need to set _ignore_holes.*/
  1843. ret=op_find_initial_pcm_offset(_of,links,&og);
  1844. if(OP_UNLIKELY(ret<0))return ret;
  1845. _of->links[0].serialno=cur_serialno=_of->os.serialno;
  1846. _of->cur_link++;
  1847. }
  1848. /*If the link was empty, keep going, because we already have the
  1849. BOS page of the next one in og.*/
  1850. while(OP_UNLIKELY(ret>0));
  1851. /*If we didn't get any packets out of op_find_initial_pcm_offset(),
  1852. keep going (this is possible if end-trimming trimmed them all).*/
  1853. if(_of->op_count<=0)continue;
  1854. /*Otherwise, we're done.
  1855. TODO: This resets bytes_tracked, which misses the header bytes
  1856. already processed by op_find_initial_pcm_offset().*/
  1857. ret=op_make_decode_ready(_of);
  1858. if(OP_UNLIKELY(ret<0))return ret;
  1859. return 0;
  1860. }
  1861. }
  1862. /*The buffered page is the data we want, and we're ready for it.
  1863. Add it to the stream state.*/
  1864. if(OP_UNLIKELY(_of->ready_state==OP_STREAMSET)){
  1865. ret=op_make_decode_ready(_of);
  1866. if(OP_UNLIKELY(ret<0))return ret;
  1867. }
  1868. /*Extract all the packets from the current page.*/
  1869. ogg_stream_pagein(&_of->os,&og);
  1870. if(OP_LIKELY(_of->ready_state>=OP_INITSET)){
  1871. opus_int32 total_duration;
  1872. int durations[255];
  1873. int op_count;
  1874. total_duration=op_collect_audio_packets(_of,durations);
  1875. if(OP_UNLIKELY(total_duration<0)){
  1876. /*Drain the packets from the page anyway.*/
  1877. total_duration=op_collect_audio_packets(_of,durations);
  1878. OP_ASSERT(total_duration>=0);
  1879. /*Report holes to the caller.*/
  1880. if(!_ignore_holes)return OP_HOLE;
  1881. }
  1882. op_count=_of->op_count;
  1883. /*If we found at least one audio data packet, compute per-packet granule
  1884. positions for them.*/
  1885. if(op_count>0){
  1886. ogg_int64_t diff;
  1887. ogg_int64_t prev_packet_gp;
  1888. ogg_int64_t cur_packet_gp;
  1889. ogg_int64_t cur_page_gp;
  1890. int cur_page_eos;
  1891. int pi;
  1892. cur_page_gp=_of->op[op_count-1].granulepos;
  1893. cur_page_eos=_of->op[op_count-1].e_o_s;
  1894. prev_packet_gp=_of->prev_packet_gp;
  1895. if(OP_UNLIKELY(prev_packet_gp==-1)){
  1896. opus_int32 cur_discard_count;
  1897. /*This is the first call after a raw seek.
  1898. Try to reconstruct prev_packet_gp from scratch.*/
  1899. OP_ASSERT(seekable);
  1900. if(OP_UNLIKELY(cur_page_eos)){
  1901. /*If the first page we hit after our seek was the EOS page, and
  1902. we didn't start from data_offset or before, we don't have
  1903. enough information to do end-trimming.
  1904. Proceed to the next link, rather than risk playing back some
  1905. samples that shouldn't have been played.*/
  1906. _of->op_count=0;
  1907. continue;
  1908. }
  1909. /*By default discard 80 ms of data after a seek, unless we seek
  1910. into the pre-skip region.*/
  1911. cur_discard_count=80*48;
  1912. cur_page_gp=_of->op[op_count-1].granulepos;
  1913. /*Try to initialize prev_packet_gp.
  1914. If the current page had packets but didn't have a granule
  1915. position, or the granule position it had was too small (both
  1916. illegal), just use the starting granule position for the link.*/
  1917. prev_packet_gp=links[cur_link].pcm_start;
  1918. if(OP_LIKELY(cur_page_gp!=-1)){
  1919. op_granpos_add(&prev_packet_gp,cur_page_gp,-total_duration);
  1920. }
  1921. if(OP_LIKELY(!op_granpos_diff(&diff,
  1922. prev_packet_gp,links[cur_link].pcm_start))){
  1923. opus_int32 pre_skip;
  1924. /*If we start at the beginning of the pre-skip region, or we're
  1925. at least 80 ms from the end of the pre-skip region, we discard
  1926. to the end of the pre-skip region.
  1927. Otherwise, we still use the 80 ms default, which will discard
  1928. past the end of the pre-skip region.*/
  1929. pre_skip=links[cur_link].head.pre_skip;
  1930. if(diff>=0&&diff<=OP_MAX(0,pre_skip-80*48)){
  1931. cur_discard_count=pre_skip-(int)diff;
  1932. }
  1933. }
  1934. _of->cur_discard_count=cur_discard_count;
  1935. }
  1936. if(OP_UNLIKELY(cur_page_gp==-1)){
  1937. /*This page had completed packets but didn't have a valid granule
  1938. position.
  1939. This is illegal, but we'll try to handle it by continuing to count
  1940. forwards from the previous page.*/
  1941. if(op_granpos_add(&cur_page_gp,prev_packet_gp,total_duration)<0){
  1942. /*The timestamp for this page overflowed.*/
  1943. cur_page_gp=links[cur_link].pcm_end;
  1944. }
  1945. }
  1946. /*If we hit the last page, handle end-trimming.*/
  1947. if(OP_UNLIKELY(cur_page_eos)
  1948. &&OP_LIKELY(!op_granpos_diff(&diff,cur_page_gp,prev_packet_gp))
  1949. &&OP_LIKELY(diff<total_duration)){
  1950. cur_packet_gp=prev_packet_gp;
  1951. for(pi=0;pi<op_count;pi++){
  1952. diff=durations[pi]-diff;
  1953. /*If we have samples to trim...*/
  1954. if(diff>0){
  1955. /*If we trimmed the entire packet, stop (the spec says encoders
  1956. shouldn't do this, but we support it anyway).*/
  1957. if(OP_UNLIKELY(diff>durations[pi]))break;
  1958. cur_packet_gp=cur_page_gp;
  1959. /*Move the EOS flag to this packet, if necessary, so we'll trim
  1960. the samples during decode.*/
  1961. _of->op[pi].e_o_s=1;
  1962. }
  1963. else{
  1964. /*Update the granule position as normal.*/
  1965. OP_ALWAYS_TRUE(!op_granpos_add(&cur_packet_gp,
  1966. cur_packet_gp,durations[pi]));
  1967. }
  1968. _of->op[pi].granulepos=cur_packet_gp;
  1969. OP_ALWAYS_TRUE(!op_granpos_diff(&diff,cur_page_gp,cur_packet_gp));
  1970. }
  1971. }
  1972. else{
  1973. /*Propagate timestamps to earlier packets.
  1974. op_granpos_add(&prev_packet_gp,prev_packet_gp,total_duration)
  1975. should succeed and give prev_packet_gp==cur_page_gp.
  1976. But we don't bother to check that, as there isn't much we can do
  1977. if it's not true, and it actually will not be true on the first
  1978. page after a seek, if there was a continued packet.
  1979. The only thing we guarantee is that the start and end granule
  1980. positions of the packets are valid, and that they are monotonic
  1981. within a page.
  1982. They might be completely out of range for this link (we'll check
  1983. that elsewhere), or non-monotonic between pages.*/
  1984. if(OP_UNLIKELY(op_granpos_add(&prev_packet_gp,
  1985. cur_page_gp,-total_duration)<0)){
  1986. /*The starting timestamp for the first packet on this page
  1987. underflowed.
  1988. This is illegal, but we ignore it.*/
  1989. prev_packet_gp=0;
  1990. }
  1991. for(pi=0;pi<op_count;pi++){
  1992. if(OP_UNLIKELY(op_granpos_add(&cur_packet_gp,
  1993. cur_page_gp,-total_duration)<0)){
  1994. /*The start timestamp for this packet underflowed.
  1995. This is illegal, but we ignore it.*/
  1996. cur_packet_gp=0;
  1997. }
  1998. total_duration-=durations[pi];
  1999. OP_ASSERT(total_duration>=0);
  2000. OP_ALWAYS_TRUE(!op_granpos_add(&cur_packet_gp,
  2001. cur_packet_gp,durations[pi]));
  2002. _of->op[pi].granulepos=cur_packet_gp;
  2003. }
  2004. OP_ASSERT(total_duration==0);
  2005. }
  2006. _of->prev_packet_gp=prev_packet_gp;
  2007. _of->prev_page_offset=_page_offset;
  2008. _of->op_count=pi;
  2009. /*If end-trimming didn't trim all the packets, we're done.*/
  2010. if(OP_LIKELY(pi>0))return 0;
  2011. }
  2012. }
  2013. }
  2014. }
  2015. int op_raw_seek(OggOpusFile *_of,opus_int64 _pos){
  2016. int ret;
  2017. if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL;
  2018. /*Don't dump the decoder state if we can't seek.*/
  2019. if(OP_UNLIKELY(!_of->seekable))return OP_ENOSEEK;
  2020. if(OP_UNLIKELY(_pos<0)||OP_UNLIKELY(_pos>_of->end))return OP_EINVAL;
  2021. /*Clear out any buffered, decoded data.*/
  2022. op_decode_clear(_of);
  2023. _of->bytes_tracked=0;
  2024. _of->samples_tracked=0;
  2025. ret=op_seek_helper(_of,_pos);
  2026. if(OP_UNLIKELY(ret<0))return OP_EREAD;
  2027. ret=op_fetch_and_process_page(_of,NULL,-1,1,1);
  2028. /*If we hit EOF, op_fetch_and_process_page() leaves us uninitialized.
  2029. Instead, jump to the end.*/
  2030. if(ret==OP_EOF){
  2031. int cur_link;
  2032. op_decode_clear(_of);
  2033. cur_link=_of->nlinks-1;
  2034. _of->cur_link=cur_link;
  2035. _of->prev_packet_gp=_of->links[cur_link].pcm_end;
  2036. _of->cur_discard_count=0;
  2037. ret=0;
  2038. }
  2039. return ret;
  2040. }
  2041. /*Convert a PCM offset relative to the start of the whole stream to a granule
  2042. position in an individual link.*/
  2043. static ogg_int64_t op_get_granulepos(const OggOpusFile *_of,
  2044. ogg_int64_t _pcm_offset,int *_li){
  2045. const OggOpusLink *links;
  2046. ogg_int64_t duration;
  2047. int nlinks;
  2048. int li;
  2049. OP_ASSERT(_pcm_offset>=0);
  2050. nlinks=_of->nlinks;
  2051. links=_of->links;
  2052. for(li=0;OP_LIKELY(li<nlinks);li++){
  2053. ogg_int64_t pcm_start;
  2054. opus_int32 pre_skip;
  2055. pcm_start=links[li].pcm_start;
  2056. pre_skip=links[li].head.pre_skip;
  2057. OP_ALWAYS_TRUE(!op_granpos_diff(&duration,links[li].pcm_end,pcm_start));
  2058. duration-=pre_skip;
  2059. if(_pcm_offset<duration){
  2060. _pcm_offset+=pre_skip;
  2061. if(OP_UNLIKELY(pcm_start>OP_INT64_MAX-_pcm_offset)){
  2062. /*Adding this amount to the granule position would overflow the positive
  2063. half of its 64-bit range.
  2064. Since signed overflow is undefined in C, do it in a way the compiler
  2065. isn't allowed to screw up.*/
  2066. _pcm_offset-=OP_INT64_MAX-pcm_start+1;
  2067. pcm_start=OP_INT64_MIN;
  2068. }
  2069. pcm_start+=_pcm_offset;
  2070. *_li=li;
  2071. return pcm_start;
  2072. }
  2073. _pcm_offset-=duration;
  2074. }
  2075. return -1;
  2076. }
  2077. /*A small helper to determine if an Ogg page contains data that continues onto
  2078. a subsequent page.*/
  2079. static int op_page_continues(const ogg_page *_og){
  2080. int nlacing;
  2081. OP_ASSERT(_og->header_len>=27);
  2082. nlacing=_og->header[26];
  2083. OP_ASSERT(_og->header_len>=27+nlacing);
  2084. /*This also correctly handles the (unlikely) case of nlacing==0, because
  2085. 0!=255.*/
  2086. return _og->header[27+nlacing-1]==255;
  2087. }
  2088. /*A small helper to buffer the continued packet data from a page.*/
  2089. static void op_buffer_continued_data(OggOpusFile *_of,ogg_page *_og){
  2090. ogg_packet op;
  2091. ogg_stream_pagein(&_of->os,_og);
  2092. /*Drain any packets that did end on this page (and ignore holes).
  2093. We only care about the continued packet data.*/
  2094. while(ogg_stream_packetout(&_of->os,&op));
  2095. }
  2096. /*This controls how close the target has to be to use the current stream
  2097. position to subdivide the initial range.
  2098. Two minutes seems to be a good default.*/
  2099. #define OP_CUR_TIME_THRESH (120*48*(opus_int32)1000)
  2100. /*Note: The OP_SMALL_FOOTPRINT #define doesn't (currently) save much code size,
  2101. but it's meant to serve as documentation for portions of the seeking
  2102. algorithm that are purely optional, to aid others learning from/porting this
  2103. code to other contexts.*/
  2104. /*#define OP_SMALL_FOOTPRINT (1)*/
  2105. /*Search within link _li for the page with the highest granule position
  2106. preceding (or equal to) _target_gp.
  2107. There is a danger here: missing pages or incorrect frame number information
  2108. in the bitstream could make our task impossible.
  2109. Account for that (and report it as an error condition).*/
  2110. static int op_pcm_seek_page(OggOpusFile *_of,
  2111. ogg_int64_t _target_gp,int _li){
  2112. const OggOpusLink *link;
  2113. ogg_page og;
  2114. ogg_int64_t pcm_pre_skip;
  2115. ogg_int64_t pcm_start;
  2116. ogg_int64_t pcm_end;
  2117. ogg_int64_t best_gp;
  2118. ogg_int64_t diff;
  2119. ogg_uint32_t serialno;
  2120. opus_int32 pre_skip;
  2121. opus_int64 begin;
  2122. opus_int64 end;
  2123. opus_int64 boundary;
  2124. opus_int64 best;
  2125. opus_int64 best_start;
  2126. opus_int64 page_offset;
  2127. opus_int64 d0;
  2128. opus_int64 d1;
  2129. opus_int64 d2;
  2130. int force_bisect;
  2131. int buffering;
  2132. int ret;
  2133. _of->bytes_tracked=0;
  2134. _of->samples_tracked=0;
  2135. link=_of->links+_li;
  2136. best_gp=pcm_start=link->pcm_start;
  2137. pcm_end=link->pcm_end;
  2138. serialno=link->serialno;
  2139. best=best_start=begin=link->data_offset;
  2140. page_offset=-1;
  2141. buffering=0;
  2142. /*We discard the first 80 ms of data after a seek, so seek back that much
  2143. farther.
  2144. If we can't, simply seek to the beginning of the link.*/
  2145. if(OP_UNLIKELY(op_granpos_add(&_target_gp,_target_gp,-80*48)<0)
  2146. ||OP_UNLIKELY(op_granpos_cmp(_target_gp,pcm_start)<0)){
  2147. _target_gp=pcm_start;
  2148. }
  2149. /*Special case seeking to the start of the link.*/
  2150. pre_skip=link->head.pre_skip;
  2151. OP_ALWAYS_TRUE(!op_granpos_add(&pcm_pre_skip,pcm_start,pre_skip));
  2152. if(op_granpos_cmp(_target_gp,pcm_pre_skip)<0)end=boundary=begin;
  2153. else{
  2154. end=boundary=link->end_offset;
  2155. #if !defined(OP_SMALL_FOOTPRINT)
  2156. /*If we were decoding from this link, we can narrow the range a bit.*/
  2157. if(_li==_of->cur_link&&_of->ready_state>=OP_INITSET){
  2158. opus_int64 offset;
  2159. int op_count;
  2160. op_count=_of->op_count;
  2161. /*The only way the offset can be invalid _and_ we can fail the granule
  2162. position checks below is if someone changed the contents of the last
  2163. page since we read it.
  2164. We'd be within our rights to just return OP_EBADLINK in that case, but
  2165. we'll simply ignore the current position instead.*/
  2166. offset=_of->offset;
  2167. if(op_count>0&&OP_LIKELY(offset<=end)){
  2168. ogg_int64_t gp;
  2169. /*Make sure the timestamp is valid.
  2170. The granule position might be -1 if we collected the packets from a
  2171. page without a granule position after reporting a hole.*/
  2172. gp=_of->op[op_count-1].granulepos;
  2173. if(OP_LIKELY(gp!=-1)&&OP_LIKELY(op_granpos_cmp(pcm_start,gp)<0)
  2174. &&OP_LIKELY(op_granpos_cmp(pcm_end,gp)>0)){
  2175. OP_ALWAYS_TRUE(!op_granpos_diff(&diff,gp,_target_gp));
  2176. /*We only actually use the current time if either
  2177. a) We can cut off at least half the range, or
  2178. b) We're seeking sufficiently close to the current position that
  2179. it's likely to be informative.
  2180. Otherwise it appears using the whole link range to estimate the
  2181. first seek location gives better results, on average.*/
  2182. if(diff<0){
  2183. OP_ASSERT(offset>=begin);
  2184. if(offset-begin>=end-begin>>1||diff>-OP_CUR_TIME_THRESH){
  2185. best=begin=offset;
  2186. best_gp=pcm_start=gp;
  2187. /*If we have buffered data from a continued packet, remember the
  2188. offset of the previous page's start, so that if we do wind up
  2189. having to seek back here later, we can prime the stream with
  2190. the continued packet data.
  2191. With no continued packet, we remember the end of the page.*/
  2192. best_start=_of->os.body_returned<_of->os.body_fill?
  2193. _of->prev_page_offset:best;
  2194. /*If there's completed packets and data in the stream state,
  2195. prev_page_offset should always be set.*/
  2196. OP_ASSERT(best_start>=0);
  2197. /*Buffer any continued packet data starting from here.*/
  2198. buffering=1;
  2199. }
  2200. }
  2201. else{
  2202. ogg_int64_t prev_page_gp;
  2203. /*We might get lucky and already have the packet with the target
  2204. buffered.
  2205. Worth checking.
  2206. For very small files (with all of the data in a single page,
  2207. generally 1 second or less), we can loop them continuously
  2208. without seeking at all.*/
  2209. OP_ALWAYS_TRUE(!op_granpos_add(&prev_page_gp,_of->op[0].granulepos,
  2210. -op_get_packet_duration(_of->op[0].packet,_of->op[0].bytes)));
  2211. if(op_granpos_cmp(prev_page_gp,_target_gp)<=0){
  2212. /*Don't call op_decode_clear(), because it will dump our
  2213. packets.*/
  2214. _of->op_pos=0;
  2215. _of->od_buffer_size=0;
  2216. _of->prev_packet_gp=prev_page_gp;
  2217. /*_of->prev_page_offset already points to the right place.*/
  2218. _of->ready_state=OP_STREAMSET;
  2219. return op_make_decode_ready(_of);
  2220. }
  2221. /*No such luck.
  2222. Check if we can cut off at least half the range, though.*/
  2223. if(offset-begin<=end-begin>>1||diff<OP_CUR_TIME_THRESH){
  2224. /*We really want the page start here, but this will do.*/
  2225. end=boundary=offset;
  2226. pcm_end=gp;
  2227. }
  2228. }
  2229. }
  2230. }
  2231. }
  2232. #endif
  2233. }
  2234. /*This code was originally based on the "new search algorithm by HB (Nicholas
  2235. Vinen)" from libvorbisfile.
  2236. It has been modified substantially since.*/
  2237. op_decode_clear(_of);
  2238. if(!buffering)ogg_stream_reset_serialno(&_of->os,serialno);
  2239. _of->cur_link=_li;
  2240. _of->ready_state=OP_STREAMSET;
  2241. /*Initialize the interval size history.*/
  2242. d2=d1=d0=end-begin;
  2243. force_bisect=0;
  2244. while(begin<end){
  2245. opus_int64 bisect;
  2246. opus_int64 next_boundary;
  2247. opus_int32 chunk_size;
  2248. if(end-begin<OP_CHUNK_SIZE)bisect=begin;
  2249. else{
  2250. /*Update the interval size history.*/
  2251. d0=d1>>1;
  2252. d1=d2>>1;
  2253. d2=end-begin>>1;
  2254. if(force_bisect)bisect=begin+(end-begin>>1);
  2255. else{
  2256. ogg_int64_t diff2;
  2257. OP_ALWAYS_TRUE(!op_granpos_diff(&diff,_target_gp,pcm_start));
  2258. OP_ALWAYS_TRUE(!op_granpos_diff(&diff2,pcm_end,pcm_start));
  2259. /*Take a (pretty decent) guess.*/
  2260. bisect=begin+op_rescale64(diff,diff2,end-begin)-OP_CHUNK_SIZE;
  2261. }
  2262. if(bisect-OP_CHUNK_SIZE<begin)bisect=begin;
  2263. force_bisect=0;
  2264. }
  2265. if(bisect!=_of->offset){
  2266. /*Discard any buffered continued packet data.*/
  2267. if(buffering)ogg_stream_reset(&_of->os);
  2268. buffering=0;
  2269. page_offset=-1;
  2270. ret=op_seek_helper(_of,bisect);
  2271. if(OP_UNLIKELY(ret<0))return ret;
  2272. }
  2273. chunk_size=OP_CHUNK_SIZE;
  2274. next_boundary=boundary;
  2275. /*Now scan forward and figure out where we landed.
  2276. In the ideal case, we will see a page with a granule position at or
  2277. before our target, followed by a page with a granule position after our
  2278. target (or the end of the search interval).
  2279. Then we can just drop out and will have all of the data we need with no
  2280. additional seeking.
  2281. If we landed too far before, or after, we'll break out and do another
  2282. bisection.*/
  2283. while(begin<end){
  2284. page_offset=op_get_next_page(_of,&og,boundary);
  2285. if(page_offset<0){
  2286. if(page_offset<OP_FALSE)return (int)page_offset;
  2287. /*There are no more pages in our interval from our stream with a valid
  2288. timestamp that start at position bisect or later.*/
  2289. /*If we scanned the whole interval, we're done.*/
  2290. if(bisect<=begin+1)end=begin;
  2291. else{
  2292. /*Otherwise, back up one chunk.
  2293. First, discard any data from a continued packet.*/
  2294. if(buffering)ogg_stream_reset(&_of->os);
  2295. buffering=0;
  2296. bisect=OP_MAX(bisect-chunk_size,begin);
  2297. ret=op_seek_helper(_of,bisect);
  2298. if(OP_UNLIKELY(ret<0))return ret;
  2299. /*Bump up the chunk size.*/
  2300. chunk_size=OP_MIN(2*chunk_size,OP_CHUNK_SIZE_MAX);
  2301. /*If we did find a page from another stream or without a timestamp,
  2302. don't read past it.*/
  2303. boundary=next_boundary;
  2304. }
  2305. }
  2306. else{
  2307. ogg_int64_t gp;
  2308. int has_packets;
  2309. /*Save the offset of the first page we found after the seek, regardless
  2310. of the stream it came from or whether or not it has a timestamp.*/
  2311. next_boundary=OP_MIN(page_offset,next_boundary);
  2312. if(serialno!=(ogg_uint32_t)ogg_page_serialno(&og))continue;
  2313. has_packets=ogg_page_packets(&og)>0;
  2314. /*Force the gp to -1 (as it should be per spec) if no packets end on
  2315. this page.
  2316. Otherwise we might get confused when we try to pull out a packet
  2317. with that timestamp and can't find it.*/
  2318. gp=has_packets?ogg_page_granulepos(&og):-1;
  2319. if(gp==-1){
  2320. if(buffering){
  2321. if(OP_LIKELY(!has_packets))ogg_stream_pagein(&_of->os,&og);
  2322. else{
  2323. /*If packets did end on this page, but we still didn't have a
  2324. valid granule position (in violation of the spec!), stop
  2325. buffering continued packet data.
  2326. Otherwise we might continue past the packet we actually
  2327. wanted.*/
  2328. ogg_stream_reset(&_of->os);
  2329. buffering=0;
  2330. }
  2331. }
  2332. continue;
  2333. }
  2334. if(op_granpos_cmp(gp,_target_gp)<0){
  2335. /*We found a page that ends before our target.
  2336. Advance to the raw offset of the next page.*/
  2337. begin=_of->offset;
  2338. if(OP_UNLIKELY(op_granpos_cmp(pcm_start,gp)>0)
  2339. ||OP_UNLIKELY(op_granpos_cmp(pcm_end,gp)<0)){
  2340. /*Don't let pcm_start get out of range!
  2341. That could happen with an invalid timestamp.*/
  2342. break;
  2343. }
  2344. /*Save the byte offset of the end of the page with this granule
  2345. position.*/
  2346. best=best_start=begin;
  2347. /*Buffer any data from a continued packet, if necessary.
  2348. This avoids the need to seek back here if the next timestamp we
  2349. encounter while scanning forward lies after our target.*/
  2350. if(buffering)ogg_stream_reset(&_of->os);
  2351. if(op_page_continues(&og)){
  2352. op_buffer_continued_data(_of,&og);
  2353. /*If we have a continued packet, remember the offset of this
  2354. page's start, so that if we do wind up having to seek back here
  2355. later, we can prime the stream with the continued packet data.
  2356. With no continued packet, we remember the end of the page.*/
  2357. best_start=page_offset;
  2358. }
  2359. /*Then force buffering on, so that if a packet starts (but does not
  2360. end) on the next page, we still avoid the extra seek back.*/
  2361. buffering=1;
  2362. best_gp=pcm_start=gp;
  2363. OP_ALWAYS_TRUE(!op_granpos_diff(&diff,_target_gp,pcm_start));
  2364. /*If we're more than a second away from our target, break out and
  2365. do another bisection.*/
  2366. if(diff>48000)break;
  2367. /*Otherwise, keep scanning forward (do NOT use begin+1).*/
  2368. bisect=begin;
  2369. }
  2370. else{
  2371. /*We found a page that ends after our target.*/
  2372. /*If we scanned the whole interval before we found it, we're done.*/
  2373. if(bisect<=begin+1)end=begin;
  2374. else{
  2375. end=bisect;
  2376. /*In later iterations, don't read past the first page we found.*/
  2377. boundary=next_boundary;
  2378. /*If we're not making much progress shrinking the interval size,
  2379. start forcing straight bisection to limit the worst case.*/
  2380. force_bisect=end-begin>d0*2;
  2381. /*Don't let pcm_end get out of range!
  2382. That could happen with an invalid timestamp.*/
  2383. if(OP_LIKELY(op_granpos_cmp(pcm_end,gp)>0)
  2384. &&OP_LIKELY(op_granpos_cmp(pcm_start,gp)<=0)){
  2385. pcm_end=gp;
  2386. }
  2387. break;
  2388. }
  2389. }
  2390. }
  2391. }
  2392. }
  2393. /*Found our page.*/
  2394. OP_ASSERT(op_granpos_cmp(best_gp,pcm_start)>=0);
  2395. /*Seek, if necessary.
  2396. If we were buffering data from a continued packet, we should be able to
  2397. continue to scan forward to get the rest of the data (even if
  2398. page_offset==-1).
  2399. Otherwise, we need to seek back to best_start.*/
  2400. if(!buffering){
  2401. if(best_start!=page_offset){
  2402. page_offset=-1;
  2403. ret=op_seek_helper(_of,best_start);
  2404. if(OP_UNLIKELY(ret<0))return ret;
  2405. }
  2406. if(best_start<best){
  2407. /*Retrieve the page at best_start, if we do not already have it.*/
  2408. if(page_offset<0){
  2409. page_offset=op_get_next_page(_of,&og,link->end_offset);
  2410. if(OP_UNLIKELY(page_offset<OP_FALSE))return (int)page_offset;
  2411. if(OP_UNLIKELY(page_offset!=best_start))return OP_EBADLINK;
  2412. }
  2413. op_buffer_continued_data(_of,&og);
  2414. page_offset=-1;
  2415. }
  2416. }
  2417. /*Update prev_packet_gp to allow per-packet granule position assignment.*/
  2418. _of->prev_packet_gp=best_gp;
  2419. _of->prev_page_offset=best_start;
  2420. ret=op_fetch_and_process_page(_of,page_offset<0?NULL:&og,page_offset,0,1);
  2421. if(OP_UNLIKELY(ret<0))return OP_EBADLINK;
  2422. /*Verify result.*/
  2423. if(OP_UNLIKELY(op_granpos_cmp(_of->prev_packet_gp,_target_gp)>0)){
  2424. return OP_EBADLINK;
  2425. }
  2426. /*Our caller will set cur_discard_count to handle pre-roll.*/
  2427. return 0;
  2428. }
  2429. int op_pcm_seek(OggOpusFile *_of,ogg_int64_t _pcm_offset){
  2430. const OggOpusLink *link;
  2431. ogg_int64_t pcm_start;
  2432. ogg_int64_t target_gp;
  2433. ogg_int64_t prev_packet_gp;
  2434. ogg_int64_t skip;
  2435. ogg_int64_t diff;
  2436. int op_count;
  2437. int op_pos;
  2438. int ret;
  2439. int li;
  2440. if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL;
  2441. if(OP_UNLIKELY(!_of->seekable))return OP_ENOSEEK;
  2442. if(OP_UNLIKELY(_pcm_offset<0))return OP_EINVAL;
  2443. target_gp=op_get_granulepos(_of,_pcm_offset,&li);
  2444. if(OP_UNLIKELY(target_gp==-1))return OP_EINVAL;
  2445. link=_of->links+li;
  2446. pcm_start=link->pcm_start;
  2447. OP_ALWAYS_TRUE(!op_granpos_diff(&_pcm_offset,target_gp,pcm_start));
  2448. #if !defined(OP_SMALL_FOOTPRINT)
  2449. /*For small (90 ms or less) forward seeks within the same link, just decode
  2450. forward.
  2451. This also optimizes the case of seeking to the current position.*/
  2452. if(li==_of->cur_link&&_of->ready_state>=OP_INITSET){
  2453. ogg_int64_t gp;
  2454. gp=_of->prev_packet_gp;
  2455. if(OP_LIKELY(gp!=-1)){
  2456. int nbuffered;
  2457. nbuffered=OP_MAX(_of->od_buffer_size-_of->od_buffer_pos,0);
  2458. OP_ALWAYS_TRUE(!op_granpos_add(&gp,gp,-nbuffered));
  2459. /*We do _not_ add cur_discard_count to gp.
  2460. Otherwise the total amount to discard could grow without bound, and it
  2461. would be better just to do a full seek.*/
  2462. if(OP_LIKELY(!op_granpos_diff(&diff,gp,pcm_start))){
  2463. ogg_int64_t discard_count;
  2464. discard_count=_pcm_offset-diff;
  2465. /*We use a threshold of 90 ms instead of 80, since 80 ms is the
  2466. _minimum_ we would have discarded after a full seek.
  2467. Assuming 20 ms frames (the default), we'd discard 90 ms on average.*/
  2468. if(discard_count>=0&&OP_UNLIKELY(discard_count<90*48)){
  2469. _of->cur_discard_count=(opus_int32)discard_count;
  2470. return 0;
  2471. }
  2472. }
  2473. }
  2474. }
  2475. #endif
  2476. ret=op_pcm_seek_page(_of,target_gp,li);
  2477. if(OP_UNLIKELY(ret<0))return ret;
  2478. /*Now skip samples until we actually get to our target.*/
  2479. /*Figure out where we should skip to.*/
  2480. if(_pcm_offset<=link->head.pre_skip)skip=0;
  2481. else skip=OP_MAX(_pcm_offset-80*48,0);
  2482. OP_ASSERT(_pcm_offset-skip>=0);
  2483. OP_ASSERT(_pcm_offset-skip<OP_INT32_MAX-120*48);
  2484. /*Skip packets until we find one with samples past our skip target.*/
  2485. for(;;){
  2486. op_count=_of->op_count;
  2487. prev_packet_gp=_of->prev_packet_gp;
  2488. for(op_pos=_of->op_pos;op_pos<op_count;op_pos++){
  2489. ogg_int64_t cur_packet_gp;
  2490. cur_packet_gp=_of->op[op_pos].granulepos;
  2491. if(OP_LIKELY(!op_granpos_diff(&diff,cur_packet_gp,pcm_start))
  2492. &&diff>skip){
  2493. break;
  2494. }
  2495. prev_packet_gp=cur_packet_gp;
  2496. }
  2497. _of->prev_packet_gp=prev_packet_gp;
  2498. _of->op_pos=op_pos;
  2499. if(op_pos<op_count)break;
  2500. /*We skipped all the packets on this page.
  2501. Fetch another.*/
  2502. ret=op_fetch_and_process_page(_of,NULL,-1,0,1);
  2503. if(OP_UNLIKELY(ret<0))return OP_EBADLINK;
  2504. }
  2505. OP_ALWAYS_TRUE(!op_granpos_diff(&diff,prev_packet_gp,pcm_start));
  2506. /*We skipped too far.
  2507. Either the timestamps were illegal or there was a hole in the data.*/
  2508. if(diff>skip)return OP_EBADLINK;
  2509. OP_ASSERT(_pcm_offset-diff<OP_INT32_MAX);
  2510. /*TODO: If there are further holes/illegal timestamps, we still won't decode
  2511. to the correct sample.
  2512. However, at least op_pcm_tell() will report the correct value immediately
  2513. after returning.*/
  2514. _of->cur_discard_count=(opus_int32)(_pcm_offset-diff);
  2515. return 0;
  2516. }
  2517. opus_int64 op_raw_tell(const OggOpusFile *_of){
  2518. if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL;
  2519. return _of->offset;
  2520. }
  2521. /*Convert a granule position from a given link to a PCM offset relative to the
  2522. start of the whole stream.
  2523. For unseekable sources, this gets reset to 0 at the beginning of each link.*/
  2524. static ogg_int64_t op_get_pcm_offset(const OggOpusFile *_of,
  2525. ogg_int64_t _gp,int _li){
  2526. const OggOpusLink *links;
  2527. ogg_int64_t pcm_offset;
  2528. ogg_int64_t delta;
  2529. int li;
  2530. links=_of->links;
  2531. pcm_offset=0;
  2532. OP_ASSERT(_li<_of->nlinks);
  2533. for(li=0;li<_li;li++){
  2534. OP_ALWAYS_TRUE(!op_granpos_diff(&delta,
  2535. links[li].pcm_end,links[li].pcm_start));
  2536. delta-=links[li].head.pre_skip;
  2537. pcm_offset+=delta;
  2538. }
  2539. OP_ASSERT(_li>=0);
  2540. if(_of->seekable&&OP_UNLIKELY(op_granpos_cmp(_gp,links[_li].pcm_end)>0)){
  2541. _gp=links[_li].pcm_end;
  2542. }
  2543. if(OP_LIKELY(op_granpos_cmp(_gp,links[_li].pcm_start)>0)){
  2544. if(OP_UNLIKELY(op_granpos_diff(&delta,_gp,links[_li].pcm_start)<0)){
  2545. /*This means an unseekable stream claimed to have a page from more than
  2546. 2 billion days after we joined.*/
  2547. OP_ASSERT(!_of->seekable);
  2548. return OP_INT64_MAX;
  2549. }
  2550. if(delta<links[_li].head.pre_skip)delta=0;
  2551. else delta-=links[_li].head.pre_skip;
  2552. /*In the seekable case, _gp was limited by pcm_end.
  2553. In the unseekable case, pcm_offset should be 0.*/
  2554. OP_ASSERT(pcm_offset<=OP_INT64_MAX-delta);
  2555. pcm_offset+=delta;
  2556. }
  2557. return pcm_offset;
  2558. }
  2559. ogg_int64_t op_pcm_tell(const OggOpusFile *_of){
  2560. ogg_int64_t gp;
  2561. int nbuffered;
  2562. int li;
  2563. if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL;
  2564. gp=_of->prev_packet_gp;
  2565. if(gp==-1)return 0;
  2566. nbuffered=OP_MAX(_of->od_buffer_size-_of->od_buffer_pos,0);
  2567. OP_ALWAYS_TRUE(!op_granpos_add(&gp,gp,-nbuffered));
  2568. li=_of->seekable?_of->cur_link:0;
  2569. if(op_granpos_add(&gp,gp,_of->cur_discard_count)<0){
  2570. gp=_of->links[li].pcm_end;
  2571. }
  2572. return op_get_pcm_offset(_of,gp,li);
  2573. }
  2574. void op_set_decode_callback(OggOpusFile *_of,
  2575. op_decode_cb_func _decode_cb,void *_ctx){
  2576. _of->decode_cb=_decode_cb;
  2577. _of->decode_cb_ctx=_ctx;
  2578. }
  2579. int op_set_gain_offset(OggOpusFile *_of,
  2580. int _gain_type,opus_int32 _gain_offset_q8){
  2581. if(_gain_type!=OP_HEADER_GAIN&&_gain_type!=OP_ALBUM_GAIN
  2582. &&_gain_type!=OP_TRACK_GAIN&&_gain_type!=OP_ABSOLUTE_GAIN){
  2583. return OP_EINVAL;
  2584. }
  2585. _of->gain_type=_gain_type;
  2586. /*The sum of header gain and track gain lies in the range [-65536,65534].
  2587. These bounds allow the offset to set the final value to anywhere in the
  2588. range [-32768,32767], which is what we'll clamp it to before applying.*/
  2589. _of->gain_offset_q8=OP_CLAMP(-98302,_gain_offset_q8,98303);
  2590. op_update_gain(_of);
  2591. return 0;
  2592. }
  2593. void op_set_dither_enabled(OggOpusFile *_of,int _enabled){
  2594. #if !defined(OP_FIXED_POINT)
  2595. _of->dither_disabled=!_enabled;
  2596. if(!_enabled)_of->dither_mute=65;
  2597. #endif
  2598. }
  2599. /*Allocate the decoder scratch buffer.
  2600. This is done lazily, since if the user provides large enough buffers, we'll
  2601. never need it.*/
  2602. static int op_init_buffer(OggOpusFile *_of){
  2603. int nchannels_max;
  2604. if(_of->seekable){
  2605. const OggOpusLink *links;
  2606. int nlinks;
  2607. int li;
  2608. links=_of->links;
  2609. nlinks=_of->nlinks;
  2610. nchannels_max=1;
  2611. for(li=0;li<nlinks;li++){
  2612. nchannels_max=OP_MAX(nchannels_max,links[li].head.channel_count);
  2613. }
  2614. }
  2615. else nchannels_max=OP_NCHANNELS_MAX;
  2616. _of->od_buffer=(op_sample *)_ogg_malloc(
  2617. sizeof(*_of->od_buffer)*nchannels_max*120*48);
  2618. if(_of->od_buffer==NULL)return OP_EFAULT;
  2619. return 0;
  2620. }
  2621. /*Decode a single packet into the target buffer.*/
  2622. static int op_decode(OggOpusFile *_of,op_sample *_pcm,
  2623. const ogg_packet *_op,int _nsamples,int _nchannels){
  2624. int ret;
  2625. /*First we try using the application-provided decode callback.*/
  2626. if(_of->decode_cb!=NULL){
  2627. #if defined(OP_FIXED_POINT)
  2628. ret=(*_of->decode_cb)(_of->decode_cb_ctx,_of->od,_pcm,_op,
  2629. _nsamples,_nchannels,OP_DEC_FORMAT_SHORT,_of->cur_link);
  2630. #else
  2631. ret=(*_of->decode_cb)(_of->decode_cb_ctx,_of->od,_pcm,_op,
  2632. _nsamples,_nchannels,OP_DEC_FORMAT_FLOAT,_of->cur_link);
  2633. #endif
  2634. }
  2635. else ret=OP_DEC_USE_DEFAULT;
  2636. /*If the application didn't want to handle decoding, do it ourselves.*/
  2637. if(ret==OP_DEC_USE_DEFAULT){
  2638. #if defined(OP_FIXED_POINT)
  2639. ret=opus_multistream_decode(_of->od,
  2640. _op->packet,_op->bytes,_pcm,_nsamples,0);
  2641. #else
  2642. ret=opus_multistream_decode_float(_of->od,
  2643. _op->packet,_op->bytes,_pcm,_nsamples,0);
  2644. #endif
  2645. OP_ASSERT(ret<0||ret==_nsamples);
  2646. }
  2647. /*If the application returned a positive value other than 0 or
  2648. OP_DEC_USE_DEFAULT, fail.*/
  2649. else if(OP_UNLIKELY(ret>0))return OP_EBADPACKET;
  2650. if(OP_UNLIKELY(ret<0))return OP_EBADPACKET;
  2651. return ret;
  2652. }
  2653. /*Read more samples from the stream, using the same API as op_read() or
  2654. op_read_float().*/
  2655. static int op_read_native(OggOpusFile *_of,
  2656. op_sample *_pcm,int _buf_size,int *_li){
  2657. if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL;
  2658. for(;;){
  2659. int ret;
  2660. if(OP_LIKELY(_of->ready_state>=OP_INITSET)){
  2661. int nchannels;
  2662. int od_buffer_pos;
  2663. int nsamples;
  2664. int op_pos;
  2665. nchannels=_of->links[_of->seekable?_of->cur_link:0].head.channel_count;
  2666. od_buffer_pos=_of->od_buffer_pos;
  2667. nsamples=_of->od_buffer_size-od_buffer_pos;
  2668. /*If we have buffered samples, return them.*/
  2669. if(nsamples>0){
  2670. if(nsamples*nchannels>_buf_size)nsamples=_buf_size/nchannels;
  2671. memcpy(_pcm,_of->od_buffer+nchannels*od_buffer_pos,
  2672. sizeof(*_pcm)*nchannels*nsamples);
  2673. od_buffer_pos+=nsamples;
  2674. _of->od_buffer_pos=od_buffer_pos;
  2675. if(_li!=NULL)*_li=_of->cur_link;
  2676. return nsamples;
  2677. }
  2678. /*If we have buffered packets, decode one.*/
  2679. op_pos=_of->op_pos;
  2680. if(OP_LIKELY(op_pos<_of->op_count)){
  2681. const ogg_packet *pop;
  2682. ogg_int64_t diff;
  2683. opus_int32 cur_discard_count;
  2684. int duration;
  2685. int trimmed_duration;
  2686. pop=_of->op+op_pos++;
  2687. _of->op_pos=op_pos;
  2688. cur_discard_count=_of->cur_discard_count;
  2689. duration=op_get_packet_duration(pop->packet,pop->bytes);
  2690. /*We don't buffer packets with an invalid TOC sequence.*/
  2691. OP_ASSERT(duration>0);
  2692. trimmed_duration=duration;
  2693. /*Perform end-trimming.*/
  2694. if(OP_UNLIKELY(pop->e_o_s)){
  2695. if(OP_UNLIKELY(op_granpos_cmp(pop->granulepos,
  2696. _of->prev_packet_gp)<=0)){
  2697. trimmed_duration=0;
  2698. }
  2699. else if(OP_LIKELY(!op_granpos_diff(&diff,
  2700. pop->granulepos,_of->prev_packet_gp))){
  2701. trimmed_duration=(int)OP_MIN(diff,trimmed_duration);
  2702. }
  2703. }
  2704. _of->prev_packet_gp=pop->granulepos;
  2705. if(OP_UNLIKELY(duration*nchannels>_buf_size)){
  2706. op_sample *buf;
  2707. /*If the user's buffer is too small, decode into a scratch buffer.*/
  2708. buf=_of->od_buffer;
  2709. if(OP_UNLIKELY(buf==NULL)){
  2710. ret=op_init_buffer(_of);
  2711. if(OP_UNLIKELY(ret<0))return ret;
  2712. buf=_of->od_buffer;
  2713. }
  2714. ret=op_decode(_of,buf,pop,duration,nchannels);
  2715. if(OP_UNLIKELY(ret<0))return ret;
  2716. /*Perform pre-skip/pre-roll.*/
  2717. od_buffer_pos=(int)OP_MIN(trimmed_duration,cur_discard_count);
  2718. cur_discard_count-=od_buffer_pos;
  2719. _of->cur_discard_count=cur_discard_count;
  2720. _of->od_buffer_pos=od_buffer_pos;
  2721. _of->od_buffer_size=trimmed_duration;
  2722. /*Update bitrate tracking based on the actual samples we used from
  2723. what was decoded.*/
  2724. _of->bytes_tracked+=pop->bytes;
  2725. _of->samples_tracked+=trimmed_duration-od_buffer_pos;
  2726. }
  2727. else{
  2728. /*Otherwise decode directly into the user's buffer.*/
  2729. ret=op_decode(_of,_pcm,pop,duration,nchannels);
  2730. if(OP_UNLIKELY(ret<0))return ret;
  2731. if(OP_LIKELY(trimmed_duration>0)){
  2732. /*Perform pre-skip/pre-roll.*/
  2733. od_buffer_pos=(int)OP_MIN(trimmed_duration,cur_discard_count);
  2734. cur_discard_count-=od_buffer_pos;
  2735. _of->cur_discard_count=cur_discard_count;
  2736. trimmed_duration-=od_buffer_pos;
  2737. if(OP_LIKELY(trimmed_duration>0)
  2738. &&OP_UNLIKELY(od_buffer_pos>0)){
  2739. memmove(_pcm,_pcm+od_buffer_pos*nchannels,
  2740. sizeof(*_pcm)*trimmed_duration*nchannels);
  2741. }
  2742. /*Update bitrate tracking based on the actual samples we used from
  2743. what was decoded.*/
  2744. _of->bytes_tracked+=pop->bytes;
  2745. _of->samples_tracked+=trimmed_duration;
  2746. if(OP_LIKELY(trimmed_duration>0)){
  2747. if(_li!=NULL)*_li=_of->cur_link;
  2748. return trimmed_duration;
  2749. }
  2750. }
  2751. }
  2752. /*Don't grab another page yet.
  2753. This one might have more packets, or might have buffered data now.*/
  2754. continue;
  2755. }
  2756. }
  2757. /*Suck in another page.*/
  2758. ret=op_fetch_and_process_page(_of,NULL,-1,1,0);
  2759. if(OP_UNLIKELY(ret==OP_EOF)){
  2760. if(_li!=NULL)*_li=_of->cur_link;
  2761. return 0;
  2762. }
  2763. if(OP_UNLIKELY(ret<0))return ret;
  2764. }
  2765. }
  2766. /*A generic filter to apply to the decoded audio data.
  2767. _src is non-const because we will destructively modify the contents of the
  2768. source buffer that we consume in some cases.*/
  2769. typedef int (*op_read_filter_func)(OggOpusFile *_of,void *_dst,int _dst_sz,
  2770. op_sample *_src,int _nsamples,int _nchannels);
  2771. /*Decode some samples and then apply a custom filter to them.
  2772. This is used to convert to different output formats.*/
  2773. static int op_filter_read_native(OggOpusFile *_of,void *_dst,int _dst_sz,
  2774. op_read_filter_func _filter,int *_li){
  2775. int ret;
  2776. /*Ensure we have some decoded samples in our buffer.*/
  2777. ret=op_read_native(_of,NULL,0,_li);
  2778. /*Now apply the filter to them.*/
  2779. if(OP_LIKELY(ret>=0)&&OP_LIKELY(_of->ready_state>=OP_INITSET)){
  2780. int od_buffer_pos;
  2781. od_buffer_pos=_of->od_buffer_pos;
  2782. ret=_of->od_buffer_size-od_buffer_pos;
  2783. if(OP_LIKELY(ret>0)){
  2784. int nchannels;
  2785. nchannels=_of->links[_of->seekable?_of->cur_link:0].head.channel_count;
  2786. ret=(*_filter)(_of,_dst,_dst_sz,
  2787. _of->od_buffer+nchannels*od_buffer_pos,ret,nchannels);
  2788. OP_ASSERT(ret>=0);
  2789. OP_ASSERT(ret<=_of->od_buffer_size-od_buffer_pos);
  2790. od_buffer_pos+=ret;
  2791. _of->od_buffer_pos=od_buffer_pos;
  2792. }
  2793. }
  2794. return ret;
  2795. }
  2796. #if !defined(OP_FIXED_POINT)||!defined(OP_DISABLE_FLOAT_API)
  2797. /*Matrices for downmixing from the supported channel counts to stereo.
  2798. The matrices with 5 or more channels are normalized to a total volume of 2.0,
  2799. since most mixes sound too quiet if normalized to 1.0 (as there is generally
  2800. little volume in the side/rear channels).*/
  2801. static const float OP_STEREO_DOWNMIX[OP_NCHANNELS_MAX-2][OP_NCHANNELS_MAX][2]={
  2802. /*3.0*/
  2803. {
  2804. {0.5858F,0.0F},{0.4142F,0.4142F},{0.0F,0.5858F}
  2805. },
  2806. /*quadrophonic*/
  2807. {
  2808. {0.4226F,0.0F},{0.0F,0.4226F},{0.366F,0.2114F},{0.2114F,0.336F}
  2809. },
  2810. /*5.0*/
  2811. {
  2812. {0.651F,0.0F},{0.46F,0.46F},{0.0F,0.651F},{0.5636F,0.3254F},
  2813. {0.3254F,0.5636F}
  2814. },
  2815. /*5.1*/
  2816. {
  2817. {0.529F,0.0F},{0.3741F,0.3741F},{0.0F,0.529F},{0.4582F,0.2645F},
  2818. {0.2645F,0.4582F},{0.3741F,0.3741F}
  2819. },
  2820. /*6.1*/
  2821. {
  2822. {0.4553F,0.0F},{0.322F,0.322F},{0.0F,0.4553F},{0.3943F,0.2277F},
  2823. {0.2277F,0.3943F},{0.2788F,0.2788F},{0.322F,0.322F}
  2824. },
  2825. /*7.1*/
  2826. {
  2827. {0.3886F,0.0F},{0.2748F,0.2748F},{0.0F,0.3886F},{0.3366F,0.1943F},
  2828. {0.1943F,0.3366F},{0.3366F,0.1943F},{0.1943F,0.3366F},{0.2748F,0.2748F}
  2829. }
  2830. };
  2831. #endif
  2832. #if defined(OP_FIXED_POINT)
  2833. /*Matrices for downmixing from the supported channel counts to stereo.
  2834. The matrices with 5 or more channels are normalized to a total volume of 2.0,
  2835. since most mixes sound too quiet if normalized to 1.0 (as there is generally
  2836. little volume in the side/rear channels).
  2837. Hence we keep the coefficients in Q14, so the downmix values won't overflow a
  2838. 32-bit number.*/
  2839. static const opus_int16 OP_STEREO_DOWNMIX_Q14
  2840. [OP_NCHANNELS_MAX-2][OP_NCHANNELS_MAX][2]={
  2841. /*3.0*/
  2842. {
  2843. {9598,0},{6786,6786},{0,9598}
  2844. },
  2845. /*quadrophonic*/
  2846. {
  2847. {6924,0},{0,6924},{5996,3464},{3464,5996}
  2848. },
  2849. /*5.0*/
  2850. {
  2851. {10666,0},{7537,7537},{0,10666},{9234,5331},{5331,9234}
  2852. },
  2853. /*5.1*/
  2854. {
  2855. {8668,0},{6129,6129},{0,8668},{7507,4335},{4335,7507},{6129,6129}
  2856. },
  2857. /*6.1*/
  2858. {
  2859. {7459,0},{5275,5275},{0,7459},{6460,3731},{3731,6460},{4568,4568},
  2860. {5275,5275}
  2861. },
  2862. /*7.1*/
  2863. {
  2864. {6368,0},{4502,4502},{0,6368},{5515,3183},{3183,5515},{5515,3183},
  2865. {3183,5515},{4502,4502}
  2866. }
  2867. };
  2868. int op_read(OggOpusFile *_of,opus_int16 *_pcm,int _buf_size,int *_li){
  2869. return op_read_native(_of,_pcm,_buf_size,_li);
  2870. }
  2871. static int op_stereo_filter(OggOpusFile *_of,void *_dst,int _dst_sz,
  2872. op_sample *_src,int _nsamples,int _nchannels){
  2873. (void)_of;
  2874. _nsamples=OP_MIN(_nsamples,_dst_sz>>1);
  2875. if(_nchannels==2)memcpy(_dst,_src,_nsamples*2*sizeof(*_src));
  2876. else{
  2877. opus_int16 *dst;
  2878. int i;
  2879. dst=(opus_int16 *)_dst;
  2880. if(_nchannels==1){
  2881. for(i=0;i<_nsamples;i++)dst[2*i+0]=dst[2*i+1]=_src[i];
  2882. }
  2883. else{
  2884. for(i=0;i<_nsamples;i++){
  2885. opus_int32 l;
  2886. opus_int32 r;
  2887. int ci;
  2888. l=r=0;
  2889. for(ci=0;ci<_nchannels;ci++){
  2890. opus_int32 s;
  2891. s=_src[_nchannels*i+ci];
  2892. l+=OP_STEREO_DOWNMIX_Q14[_nchannels-3][ci][0]*s;
  2893. r+=OP_STEREO_DOWNMIX_Q14[_nchannels-3][ci][1]*s;
  2894. }
  2895. /*TODO: For 5 or more channels, we should do soft clipping here.*/
  2896. dst[2*i+0]=(opus_int16)OP_CLAMP(-32768,l+8192>>14,32767);
  2897. dst[2*i+1]=(opus_int16)OP_CLAMP(-32768,r+8192>>14,32767);
  2898. }
  2899. }
  2900. }
  2901. return _nsamples;
  2902. }
  2903. int op_read_stereo(OggOpusFile *_of,opus_int16 *_pcm,int _buf_size){
  2904. return op_filter_read_native(_of,_pcm,_buf_size,op_stereo_filter,NULL);
  2905. }
  2906. # if !defined(OP_DISABLE_FLOAT_API)
  2907. static int op_short2float_filter(OggOpusFile *_of,void *_dst,int _dst_sz,
  2908. op_sample *_src,int _nsamples,int _nchannels){
  2909. float *dst;
  2910. int i;
  2911. (void)_of;
  2912. dst=(float *)_dst;
  2913. if(OP_UNLIKELY(_nsamples*_nchannels>_dst_sz))_nsamples=_dst_sz/_nchannels;
  2914. _dst_sz=_nsamples*_nchannels;
  2915. for(i=0;i<_dst_sz;i++)dst[i]=(1.0F/32768)*_src[i];
  2916. return _nsamples;
  2917. }
  2918. int op_read_float(OggOpusFile *_of,float *_pcm,int _buf_size,int *_li){
  2919. return op_filter_read_native(_of,_pcm,_buf_size,op_short2float_filter,_li);
  2920. }
  2921. static int op_short2float_stereo_filter(OggOpusFile *_of,
  2922. void *_dst,int _dst_sz,op_sample *_src,int _nsamples,int _nchannels){
  2923. float *dst;
  2924. int i;
  2925. dst=(float *)_dst;
  2926. _nsamples=OP_MIN(_nsamples,_dst_sz>>1);
  2927. if(_nchannels==1){
  2928. _nsamples=op_short2float_filter(_of,dst,_nsamples,_src,_nsamples,1);
  2929. for(i=_nsamples;i-->0;)dst[2*i+0]=dst[2*i+1]=dst[i];
  2930. }
  2931. else if(_nchannels<5){
  2932. /*For 3 or 4 channels, we can downmix in fixed point without risk of
  2933. clipping.*/
  2934. if(_nchannels>2){
  2935. _nsamples=op_stereo_filter(_of,_src,_nsamples*2,
  2936. _src,_nsamples,_nchannels);
  2937. }
  2938. return op_short2float_filter(_of,dst,_dst_sz,_src,_nsamples,2);
  2939. }
  2940. else{
  2941. /*For 5 or more channels, we convert to floats and then downmix (so that we
  2942. don't risk clipping).*/
  2943. for(i=0;i<_nsamples;i++){
  2944. float l;
  2945. float r;
  2946. int ci;
  2947. l=r=0;
  2948. for(ci=0;ci<_nchannels;ci++){
  2949. float s;
  2950. s=(1.0F/32768)*_src[_nchannels*i+ci];
  2951. l+=OP_STEREO_DOWNMIX[_nchannels-3][ci][0]*s;
  2952. r+=OP_STEREO_DOWNMIX[_nchannels-3][ci][1]*s;
  2953. }
  2954. dst[2*i+0]=l;
  2955. dst[2*i+1]=r;
  2956. }
  2957. }
  2958. return _nsamples;
  2959. }
  2960. int op_read_float_stereo(OggOpusFile *_of,float *_pcm,int _buf_size){
  2961. return op_filter_read_native(_of,_pcm,_buf_size,
  2962. op_short2float_stereo_filter,NULL);
  2963. }
  2964. # endif
  2965. #else
  2966. # if defined(OP_HAVE_LRINTF)
  2967. # include <math.h>
  2968. # define op_float2int(_x) (lrintf(_x))
  2969. # else
  2970. # define op_float2int(_x) ((int)((_x)+((_x)<0?-0.5F:0.5F)))
  2971. # endif
  2972. /*The dithering code here is adapted from opusdec, part of opus-tools.
  2973. It was originally written by Greg Maxwell.*/
  2974. static opus_uint32 op_rand(opus_uint32 _seed){
  2975. return _seed*96314165+907633515&0xFFFFFFFFU;
  2976. }
  2977. /*This implements 16-bit quantization with full triangular dither and IIR noise
  2978. shaping.
  2979. The noise shaping filters were designed by Sebastian Gesemann, and are based
  2980. on the LAME ATH curves with flattening to limit their peak gain to 20 dB.
  2981. Everyone else's noise shaping filters are mildly crazy.
  2982. The 48 kHz version of this filter is just a warped version of the 44.1 kHz
  2983. filter and probably could be improved by shifting the HF shelf up in
  2984. frequency a little bit, since 48 kHz has a bit more room and being more
  2985. conservative against bat-ears is probably more important than more noise
  2986. suppression.
  2987. This process can increase the peak level of the signal (in theory by the peak
  2988. error of 1.5 +20 dB, though that is unobservably rare).
  2989. To avoid clipping, the signal is attenuated by a couple thousandths of a dB.
  2990. Initially, the approach taken here was to only attenuate by the 99.9th
  2991. percentile, making clipping rare but not impossible (like SoX), but the
  2992. limited gain of the filter means that the worst case was only two
  2993. thousandths of a dB more, so this just uses the worst case.
  2994. The attenuation is probably also helpful to prevent clipping in the DAC
  2995. reconstruction filters or downstream resampling, in any case.*/
  2996. # define OP_GAIN (32753.0F)
  2997. # define OP_PRNG_GAIN (1.0F/0xFFFFFFFF)
  2998. /*48 kHz noise shaping filter, sd=2.34.*/
  2999. static const float OP_FCOEF_B[4]={
  3000. 2.2374F,-0.7339F,-0.1251F,-0.6033F
  3001. };
  3002. static const float OP_FCOEF_A[4]={
  3003. 0.9030F,0.0116F,-0.5853F,-0.2571F
  3004. };
  3005. static int op_float2short_filter(OggOpusFile *_of,void *_dst,int _dst_sz,
  3006. float *_src,int _nsamples,int _nchannels){
  3007. opus_int16 *dst;
  3008. int ci;
  3009. int i;
  3010. dst=(opus_int16 *)_dst;
  3011. if(OP_UNLIKELY(_nsamples*_nchannels>_dst_sz))_nsamples=_dst_sz/_nchannels;
  3012. # if defined(OP_SOFT_CLIP)
  3013. if(_of->state_channel_count!=_nchannels){
  3014. for(ci=0;ci<_nchannels;ci++)_of->clip_state[ci]=0;
  3015. }
  3016. opus_pcm_soft_clip(_src,_nsamples,_nchannels,_of->clip_state);
  3017. # endif
  3018. if(_of->dither_disabled){
  3019. for(i=0;i<_nchannels*_nsamples;i++){
  3020. dst[i]=op_float2int(OP_CLAMP(-32768,32768.0F*_src[i],32767));
  3021. }
  3022. }
  3023. else{
  3024. opus_uint32 seed;
  3025. int mute;
  3026. seed=_of->dither_seed;
  3027. mute=_of->dither_mute;
  3028. if(_of->state_channel_count!=_nchannels)mute=65;
  3029. /*In order to avoid replacing digital silence with quiet dither noise, we
  3030. mute if the output has been silent for a while.*/
  3031. if(mute>64)memset(_of->dither_a,0,sizeof(*_of->dither_a)*4*_nchannels);
  3032. for(i=0;i<_nsamples;i++){
  3033. int silent;
  3034. silent=1;
  3035. for(ci=0;ci<_nchannels;ci++){
  3036. float r;
  3037. float s;
  3038. float err;
  3039. int si;
  3040. int j;
  3041. s=_src[_nchannels*i+ci];
  3042. silent&=s==0;
  3043. s*=OP_GAIN;
  3044. err=0;
  3045. for(j=0;j<4;j++){
  3046. err+=OP_FCOEF_B[j]*_of->dither_b[ci*4+j]
  3047. -OP_FCOEF_A[j]*_of->dither_a[ci*4+j];
  3048. }
  3049. for(j=3;j-->0;)_of->dither_a[ci*4+j+1]=_of->dither_a[ci*4+j];
  3050. for(j=3;j-->0;)_of->dither_b[ci*4+j+1]=_of->dither_b[ci*4+j];
  3051. _of->dither_a[ci*4]=err;
  3052. s-=err;
  3053. if(mute>16)r=0;
  3054. else{
  3055. seed=op_rand(seed);
  3056. r=seed*OP_PRNG_GAIN;
  3057. seed=op_rand(seed);
  3058. r-=seed*OP_PRNG_GAIN;
  3059. }
  3060. /*Clamp in float out of paranoia that the input will be > 96 dBFS and
  3061. wrap if the integer is clamped.*/
  3062. si=op_float2int(OP_CLAMP(-32768,s+r,32767));
  3063. dst[_nchannels*i+ci]=(opus_int16)si;
  3064. /*Including clipping in the noise shaping is generally disastrous: the
  3065. futile effort to restore the clipped energy results in more clipping.
  3066. However, small amounts---at the level which could normally be created
  3067. by dither and rounding---are harmless and can even reduce clipping
  3068. somewhat due to the clipping sometimes reducing the dither + rounding
  3069. error.*/
  3070. _of->dither_b[ci*4]=mute>16?0:OP_CLAMP(-1.5F,si-s,1.5F);
  3071. }
  3072. mute++;
  3073. if(!silent)mute=0;
  3074. }
  3075. _of->dither_mute=OP_MIN(mute,65);
  3076. _of->dither_seed=seed;
  3077. }
  3078. _of->state_channel_count=_nchannels;
  3079. return _nsamples;
  3080. }
  3081. int op_read(OggOpusFile *_of,opus_int16 *_pcm,int _buf_size,int *_li){
  3082. return op_filter_read_native(_of,_pcm,_buf_size,op_float2short_filter,_li);
  3083. }
  3084. int op_read_float(OggOpusFile *_of,float *_pcm,int _buf_size,int *_li){
  3085. _of->state_channel_count=0;
  3086. return op_read_native(_of,_pcm,_buf_size,_li);
  3087. }
  3088. static int op_stereo_filter(OggOpusFile *_of,void *_dst,int _dst_sz,
  3089. op_sample *_src,int _nsamples,int _nchannels){
  3090. (void)_of;
  3091. _nsamples=OP_MIN(_nsamples,_dst_sz>>1);
  3092. if(_nchannels==2)memcpy(_dst,_src,_nsamples*2*sizeof(*_src));
  3093. else{
  3094. float *dst;
  3095. int i;
  3096. dst=(float *)_dst;
  3097. if(_nchannels==1){
  3098. for(i=0;i<_nsamples;i++)dst[2*i+0]=dst[2*i+1]=_src[i];
  3099. }
  3100. else{
  3101. for(i=0;i<_nsamples;i++){
  3102. float l;
  3103. float r;
  3104. int ci;
  3105. l=r=0;
  3106. for(ci=0;ci<_nchannels;ci++){
  3107. l+=OP_STEREO_DOWNMIX[_nchannels-3][ci][0]*_src[_nchannels*i+ci];
  3108. r+=OP_STEREO_DOWNMIX[_nchannels-3][ci][1]*_src[_nchannels*i+ci];
  3109. }
  3110. dst[2*i+0]=l;
  3111. dst[2*i+1]=r;
  3112. }
  3113. }
  3114. }
  3115. return _nsamples;
  3116. }
  3117. static int op_float2short_stereo_filter(OggOpusFile *_of,
  3118. void *_dst,int _dst_sz,op_sample *_src,int _nsamples,int _nchannels){
  3119. opus_int16 *dst;
  3120. dst=(opus_int16 *)_dst;
  3121. if(_nchannels==1){
  3122. int i;
  3123. _nsamples=op_float2short_filter(_of,dst,_dst_sz>>1,_src,_nsamples,1);
  3124. for(i=_nsamples;i-->0;)dst[2*i+0]=dst[2*i+1]=dst[i];
  3125. }
  3126. else{
  3127. if(_nchannels>2){
  3128. _nsamples=OP_MIN(_nsamples,_dst_sz>>1);
  3129. _nsamples=op_stereo_filter(_of,_src,_nsamples*2,
  3130. _src,_nsamples,_nchannels);
  3131. }
  3132. _nsamples=op_float2short_filter(_of,dst,_dst_sz,_src,_nsamples,2);
  3133. }
  3134. return _nsamples;
  3135. }
  3136. int op_read_stereo(OggOpusFile *_of,opus_int16 *_pcm,int _buf_size){
  3137. return op_filter_read_native(_of,_pcm,_buf_size,
  3138. op_float2short_stereo_filter,NULL);
  3139. }
  3140. int op_read_float_stereo(OggOpusFile *_of,float *_pcm,int _buf_size){
  3141. _of->state_channel_count=0;
  3142. return op_filter_read_native(_of,_pcm,_buf_size,op_stereo_filter,NULL);
  3143. }
  3144. #endif