vorbisfile.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE Ogg Vorbis SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS SOURCE IS GOVERNED BY *
  5. * THE GNU PUBLIC LICENSE 2, WHICH IS INCLUDED WITH THIS SOURCE. *
  6. * PLEASE READ THESE TERMS DISTRIBUTING. *
  7. * *
  8. * THE OggSQUISH SOURCE CODE IS (C) COPYRIGHT 1994-2000 *
  9. * by Monty <monty@xiph.org> and The XIPHOPHORUS Company *
  10. * http://www.xiph.org/ *
  11. * *
  12. ********************************************************************
  13. function: stdio-based convenience library for opening/seeking/decoding
  14. last mod: $Id: vorbisfile.c,v 1.27.2.2.2.1 2000/09/26 18:45:34 jack Exp $
  15. ********************************************************************/
  16. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <math.h>
  20. #include <assert.h>
  21. #include "vorbis/codec.h"
  22. #include "vorbis/vorbisfile.h"
  23. #include "os.h"
  24. #include "misc.h"
  25. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  26. one logical bitstream arranged end to end (the only form of Ogg
  27. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  28. multiplexing] is not allowed in Vorbis) */
  29. /* A Vorbis file can be played beginning to end (streamed) without
  30. worrying ahead of time about chaining (see decoder_example.c). If
  31. we have the whole file, however, and want random access
  32. (seeking/scrubbing) or desire to know the total length/time of a
  33. file, we need to account for the possibility of chaining. */
  34. /* We can handle things a number of ways; we can determine the entire
  35. bitstream structure right off the bat, or find pieces on demand.
  36. This example determines and caches structure for the entire
  37. bitstream, but builds a virtual decoder on the fly when moving
  38. between links in the chain. */
  39. /* There are also different ways to implement seeking. Enough
  40. information exists in an Ogg bitstream to seek to
  41. sample-granularity positions in the output. Or, one can seek by
  42. picking some portion of the stream roughly in the desired area if
  43. we only want course navigation through the stream. */
  44. /*************************************************************************
  45. * Many, many internal helpers. The intention is not to be confusing;
  46. * rampant duplication and monolithic function implementation would be
  47. * harder to understand anyway. The high level functions are last. Begin
  48. * grokking near the end of the file */
  49. /* read a little more data from the file/pipe into the ogg_sync framer */
  50. #define CHUNKSIZE 4096
  51. static long _get_data(OggVorbis_File *vf){
  52. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  53. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  54. ogg_sync_wrote(&vf->oy,bytes);
  55. return(bytes);
  56. }
  57. /* save a tiny smidge of verbosity to make the code more readable */
  58. static void _seek_helper(OggVorbis_File *vf,long offset){
  59. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  60. vf->offset=offset;
  61. ogg_sync_reset(&vf->oy);
  62. }
  63. /* The read/seek functions track absolute position within the stream */
  64. /* from the head of the stream, get the next page. boundary specifies
  65. if the function is allowed to fetch more data from the stream (and
  66. how much) or only use internally buffered data.
  67. boundary: -1) unbounded search
  68. 0) read no additional data; use cached only
  69. n) search for a new page beginning for n bytes
  70. return: -1) did not find a page
  71. n) found a page at absolute offset n */
  72. static long _get_next_page(OggVorbis_File *vf,ogg_page *og,int boundary){
  73. if(boundary>0)boundary+=vf->offset;
  74. while(1){
  75. long more;
  76. if(boundary>0 && vf->offset>=boundary)return(-1);
  77. more=ogg_sync_pageseek(&vf->oy,og);
  78. if(more<0){
  79. /* skipped n bytes */
  80. vf->offset-=more;
  81. }else{
  82. if(more==0){
  83. /* send more paramedics */
  84. if(!boundary)return(-1);
  85. if(_get_data(vf)<=0)return(-1);
  86. }else{
  87. /* got a page. Return the offset at the page beginning,
  88. advance the internal offset past the page end */
  89. long ret=vf->offset;
  90. vf->offset+=more;
  91. return(ret);
  92. }
  93. }
  94. }
  95. }
  96. /* find the latest page beginning before the current stream cursor
  97. position. Much dirtier than the above as Ogg doesn't have any
  98. backward search linkage. no 'readp' as it will certainly have to
  99. read. */
  100. static long _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  101. long begin=vf->offset;
  102. long ret;
  103. int offset=-1;
  104. while(offset==-1){
  105. begin-=CHUNKSIZE;
  106. _seek_helper(vf,begin);
  107. while(vf->offset<begin+CHUNKSIZE){
  108. ret=_get_next_page(vf,og,begin+CHUNKSIZE-vf->offset);
  109. if(ret==-1){
  110. break;
  111. }else{
  112. offset=ret;
  113. }
  114. }
  115. }
  116. /* we have the offset. Actually snork and hold the page now */
  117. _seek_helper(vf,offset);
  118. ret=_get_next_page(vf,og,CHUNKSIZE);
  119. if(ret==-1){
  120. /* this shouldn't be possible */
  121. fprintf(stderr,"Missed page fencepost at end of logical bitstream. "
  122. "Exiting.\n");
  123. exit(1);
  124. }
  125. return(offset);
  126. }
  127. /* finds each bitstream link one at a time using a bisection search
  128. (has to begin by knowing the offset of the lb's initial page).
  129. Recurses for each link so it can alloc the link storage after
  130. finding them all, then unroll and fill the cache at the same time */
  131. static void _bisect_forward_serialno(OggVorbis_File *vf,
  132. long begin,
  133. long searched,
  134. long end,
  135. long currentno,
  136. long m){
  137. long endsearched=end;
  138. long next=end;
  139. ogg_page og;
  140. long ret;
  141. /* the below guards against garbage seperating the last and
  142. first pages of two links. */
  143. while(searched<endsearched){
  144. long bisect;
  145. if(endsearched-searched<CHUNKSIZE){
  146. bisect=searched;
  147. }else{
  148. bisect=(searched+endsearched)/2;
  149. }
  150. _seek_helper(vf,bisect);
  151. ret=_get_next_page(vf,&og,-1);
  152. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  153. endsearched=bisect;
  154. if(ret>=0)next=ret;
  155. }else{
  156. searched=ret+og.header_len+og.body_len;
  157. }
  158. }
  159. _seek_helper(vf,next);
  160. ret=_get_next_page(vf,&og,-1);
  161. if(searched>=end || ret==-1){
  162. vf->links=m+1;
  163. vf->offsets=malloc((m+2)*sizeof(ogg_int64_t));
  164. vf->offsets[m+1]=searched;
  165. }else{
  166. _bisect_forward_serialno(vf,next,vf->offset,
  167. end,ogg_page_serialno(&og),m+1);
  168. }
  169. vf->offsets[m]=begin;
  170. }
  171. /* uses the local ogg_stream storage in vf; this is important for
  172. non-streaming input sources */
  173. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  174. long *serialno){
  175. ogg_page og;
  176. ogg_packet op;
  177. int i,ret;
  178. ret=_get_next_page(vf,&og,CHUNKSIZE);
  179. if(ret==-1){
  180. fprintf(stderr,"Did not find initial header for bitstream.\n");
  181. return -1;
  182. }
  183. if(serialno)*serialno=ogg_page_serialno(&og);
  184. ogg_stream_init(&vf->os,ogg_page_serialno(&og));
  185. /* extract the initial header from the first page and verify that the
  186. Ogg bitstream is in fact Vorbis data */
  187. vorbis_info_init(vi);
  188. vorbis_comment_init(vc);
  189. i=0;
  190. while(i<3){
  191. ogg_stream_pagein(&vf->os,&og);
  192. while(i<3){
  193. int result=ogg_stream_packetout(&vf->os,&op);
  194. if(result==0)break;
  195. if(result==-1){
  196. fprintf(stderr,"Corrupt header in logical bitstream.\n");
  197. goto bail_header;
  198. }
  199. if(vorbis_synthesis_headerin(vi,vc,&op)){
  200. fprintf(stderr,"Illegal header in logical bitstream.\n");
  201. goto bail_header;
  202. }
  203. i++;
  204. }
  205. if(i<3)
  206. if(_get_next_page(vf,&og,1)<0){
  207. fprintf(stderr,"Missing header in logical bitstream.\n");
  208. goto bail_header;
  209. }
  210. }
  211. return 0;
  212. bail_header:
  213. vorbis_info_clear(vi);
  214. vorbis_comment_clear(vc);
  215. ogg_stream_clear(&vf->os);
  216. return -1;
  217. }
  218. /* last step of the OggVorbis_File initialization; get all the
  219. vorbis_info structs and PCM positions. Only called by the seekable
  220. initialization (local stream storage is hacked slightly; pay
  221. attention to how that's done) */
  222. static void _prefetch_all_headers(OggVorbis_File *vf,vorbis_info *first_i,
  223. vorbis_comment *first_c,
  224. long dataoffset){
  225. ogg_page og;
  226. int i,ret;
  227. vf->vi=calloc(vf->links,sizeof(vorbis_info));
  228. vf->vc=calloc(vf->links,sizeof(vorbis_info));
  229. vf->dataoffsets=malloc(vf->links*sizeof(ogg_int64_t));
  230. vf->pcmlengths=malloc(vf->links*sizeof(ogg_int64_t));
  231. vf->serialnos=malloc(vf->links*sizeof(long));
  232. for(i=0;i<vf->links;i++){
  233. if(first_i && first_c && i==0){
  234. /* we already grabbed the initial header earlier. This just
  235. saves the waste of grabbing it again */
  236. memcpy(vf->vi+i,first_i,sizeof(vorbis_info));
  237. memcpy(vf->vc+i,first_c,sizeof(vorbis_comment));
  238. vf->dataoffsets[i]=dataoffset;
  239. }else{
  240. /* seek to the location of the initial header */
  241. _seek_helper(vf,vf->offsets[i]);
  242. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL)==-1){
  243. fprintf(stderr,"Error opening logical bitstream #%d.\n\n",i+1);
  244. vf->dataoffsets[i]=-1;
  245. }else{
  246. vf->dataoffsets[i]=vf->offset;
  247. ogg_stream_clear(&vf->os);
  248. }
  249. }
  250. /* get the serial number and PCM length of this link. To do this,
  251. get the last page of the stream */
  252. {
  253. long end=vf->offsets[i+1];
  254. _seek_helper(vf,end);
  255. while(1){
  256. ret=_get_prev_page(vf,&og);
  257. if(ret==-1){
  258. /* this should not be possible */
  259. fprintf(stderr,"Could not find last page of logical "
  260. "bitstream #%d\n\n",i);
  261. vorbis_info_clear(vf->vi+i);
  262. vorbis_comment_clear(vf->vc+i);
  263. break;
  264. }
  265. if(ogg_page_granulepos(&og)!=-1){
  266. vf->serialnos[i]=ogg_page_serialno(&og);
  267. vf->pcmlengths[i]=ogg_page_granulepos(&og);
  268. break;
  269. }
  270. }
  271. }
  272. }
  273. }
  274. static int _make_decode_ready(OggVorbis_File *vf){
  275. if(vf->decode_ready)exit(1);
  276. vorbis_synthesis_init(&vf->vd,vf->vi);
  277. vorbis_block_init(&vf->vd,&vf->vb);
  278. vf->decode_ready=1;
  279. return(0);
  280. }
  281. static int _open_seekable(OggVorbis_File *vf){
  282. vorbis_info initial_i;
  283. vorbis_comment initial_c;
  284. long serialno,end;
  285. int ret;
  286. long dataoffset;
  287. ogg_page og;
  288. /* is this even vorbis...? */
  289. ret=_fetch_headers(vf,&initial_i,&initial_c,&serialno);
  290. dataoffset=vf->offset;
  291. ogg_stream_clear(&vf->os);
  292. if(ret==-1)return(-1);
  293. /* we can seek, so set out learning all about this file */
  294. vf->seekable=1;
  295. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  296. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  297. /* We get the offset for the last page of the physical bitstream.
  298. Most OggVorbis files will contain a single logical bitstream */
  299. end=_get_prev_page(vf,&og);
  300. /* moer than one logical bitstream? */
  301. if(ogg_page_serialno(&og)!=serialno){
  302. /* Chained bitstream. Bisect-search each logical bitstream
  303. section. Do so based on serial number only */
  304. _bisect_forward_serialno(vf,0,0,end+1,serialno,0);
  305. }else{
  306. /* Only one logical bitstream */
  307. _bisect_forward_serialno(vf,0,end,end+1,serialno,0);
  308. }
  309. _prefetch_all_headers(vf,&initial_i,&initial_c,dataoffset);
  310. return(ov_raw_seek(vf,0));
  311. }
  312. static int _open_nonseekable(OggVorbis_File *vf){
  313. /* we cannot seek. Set up a 'single' (current) logical bitstream entry */
  314. vf->links=1;
  315. vf->vi=calloc(vf->links,sizeof(vorbis_info));
  316. vf->vc=calloc(vf->links,sizeof(vorbis_info));
  317. /* Try to fetch the headers, maintaining all the storage */
  318. if(_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno)==-1)return(-1);
  319. _make_decode_ready(vf);
  320. return 0;
  321. }
  322. /* clear out the current logical bitstream decoder */
  323. static void _decode_clear(OggVorbis_File *vf){
  324. ogg_stream_clear(&vf->os);
  325. vorbis_dsp_clear(&vf->vd);
  326. vorbis_block_clear(&vf->vb);
  327. vf->decode_ready=0;
  328. vf->bittrack=0.;
  329. vf->samptrack=0.;
  330. }
  331. /* fetch and process a packet. Handles the case where we're at a
  332. bitstream boundary and dumps the decoding machine. If the decoding
  333. machine is unloaded, it loads it. It also keeps pcm_offset up to
  334. date (seek and read both use this. seek uses a special hack with
  335. readp).
  336. return: -1) hole in the data (lost packet)
  337. 0) need more date (only if readp==0)/eof
  338. 1) got a packet
  339. */
  340. static int _process_packet(OggVorbis_File *vf,int readp){
  341. ogg_page og;
  342. /* handle one packet. Try to fetch it from current stream state */
  343. /* extract packets from page */
  344. while(1){
  345. /* process a packet if we can. If the machine isn't loaded,
  346. neither is a page */
  347. if(vf->decode_ready){
  348. ogg_packet op;
  349. int result=ogg_stream_packetout(&vf->os,&op);
  350. ogg_int64_t granulepos;
  351. /* if(result==-1)return(-1); hole in the data. For now, swallow
  352. and go. We'll need to add a real
  353. error code in a bit. */
  354. if(result>0){
  355. /* got a packet. process it */
  356. granulepos=op.granulepos;
  357. if(!vorbis_synthesis(&vf->vb,&op)){ /* lazy check for lazy
  358. header handling. The
  359. header packets aren't
  360. audio, so if/when we
  361. submit them,
  362. vorbis_synthesis will
  363. reject them */
  364. /* suck in the synthesis data and track bitrate */
  365. {
  366. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  367. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  368. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  369. vf->bittrack+=op.bytes*8;
  370. }
  371. /* update the pcm offset. */
  372. if(granulepos!=-1 && !op.e_o_s){
  373. int link=(vf->seekable?vf->current_link:0);
  374. int i,samples;
  375. /* this packet has a pcm_offset on it (the last packet
  376. completed on a page carries the offset) After processing
  377. (above), we know the pcm position of the *last* sample
  378. ready to be returned. Find the offset of the *first*
  379. As an aside, this trick is inaccurate if we begin
  380. reading anew right at the last page; the end-of-stream
  381. granulepos declares the last frame in the stream, and the
  382. last packet of the last page may be a partial frame.
  383. So, we need a previous granulepos from an in-sequence page
  384. to have a reference point. Thus the !op.e_o_s clause
  385. above */
  386. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  387. granulepos-=samples;
  388. for(i=0;i<link;i++)
  389. granulepos+=vf->pcmlengths[i];
  390. vf->pcm_offset=granulepos;
  391. }
  392. return(1);
  393. }
  394. }
  395. }
  396. if(!readp)return(0);
  397. if(_get_next_page(vf,&og,-1)<0)return(0); /* eof. leave unitialized */
  398. /* bitrate tracking; add the header's bytes here, the body bytes
  399. are done by packet above */
  400. vf->bittrack+=og.header_len*8;
  401. /* has our decoding just traversed a bitstream boundary? */
  402. if(vf->decode_ready){
  403. if(vf->current_serialno!=ogg_page_serialno(&og)){
  404. _decode_clear(vf);
  405. }
  406. }
  407. /* Do we need to load a new machine before submitting the page? */
  408. /* This is different in the seekable and non-seekable cases.
  409. In the seekable case, we already have all the header
  410. information loaded and cached; we just initialize the machine
  411. with it and continue on our merry way.
  412. In the non-seekable (streaming) case, we'll only be at a
  413. boundary if we just left the previous logical bitstream and
  414. we're now nominally at the header of the next bitstream
  415. */
  416. if(!vf->decode_ready){
  417. int link;
  418. if(vf->seekable){
  419. vf->current_serialno=ogg_page_serialno(&og);
  420. /* match the serialno to bitstream section. We use this rather than
  421. offset positions to avoid problems near logical bitstream
  422. boundaries */
  423. for(link=0;link<vf->links;link++)
  424. if(vf->serialnos[link]==vf->current_serialno)break;
  425. if(link==vf->links)return(-1); /* sign of a bogus stream. error out,
  426. leave machine uninitialized */
  427. vf->current_link=link;
  428. ogg_stream_init(&vf->os,vf->current_serialno);
  429. ogg_stream_reset(&vf->os);
  430. }else{
  431. /* we're streaming */
  432. /* fetch the three header packets, build the info struct */
  433. _fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno);
  434. vf->current_link++;
  435. link=0;
  436. }
  437. _make_decode_ready(vf);
  438. }
  439. ogg_stream_pagein(&vf->os,&og);
  440. }
  441. }
  442. /**********************************************************************
  443. * The helpers are over; it's all toplevel interface from here on out */
  444. /* clear out the OggVorbis_File struct */
  445. int ov_clear(OggVorbis_File *vf){
  446. if(vf){
  447. vorbis_block_clear(&vf->vb);
  448. vorbis_dsp_clear(&vf->vd);
  449. ogg_stream_clear(&vf->os);
  450. if(vf->vi && vf->links){
  451. int i;
  452. for(i=0;i<vf->links;i++){
  453. vorbis_info_clear(vf->vi+i);
  454. vorbis_comment_clear(vf->vc+i);
  455. }
  456. free(vf->vi);
  457. free(vf->vc);
  458. }
  459. if(vf->dataoffsets)free(vf->dataoffsets);
  460. if(vf->pcmlengths)free(vf->pcmlengths);
  461. if(vf->serialnos)free(vf->serialnos);
  462. if(vf->offsets)free(vf->offsets);
  463. ogg_sync_clear(&vf->oy);
  464. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  465. memset(vf,0,sizeof(OggVorbis_File));
  466. }
  467. #ifdef DEBUG_LEAKS
  468. _VDBG_dump();
  469. #endif
  470. return(0);
  471. }
  472. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  473. return fseek(f,(int)off,whence);
  474. }
  475. /* inspects the OggVorbis file and finds/documents all the logical
  476. bitstreams contained in it. Tries to be tolerant of logical
  477. bitstream sections that are truncated/woogie.
  478. return: -1) error
  479. 0) OK
  480. */
  481. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  482. ov_callbacks callbacks = {
  483. (size_t (*)(void *, size_t, size_t, void *)) fread,
  484. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  485. (int (*)(void *)) fclose,
  486. (long (*)(void *)) ftell
  487. };
  488. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  489. }
  490. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  491. ov_callbacks callbacks)
  492. {
  493. long offset=callbacks.seek_func(f,0,SEEK_CUR);
  494. int ret;
  495. memset(vf,0,sizeof(OggVorbis_File));
  496. vf->datasource=f;
  497. vf->callbacks = callbacks;
  498. /* init the framing state */
  499. ogg_sync_init(&vf->oy);
  500. /* perhaps some data was previously read into a buffer for testing
  501. against other stream types. Allow initialization from this
  502. previously read data (as we may be reading from a non-seekable
  503. stream) */
  504. if(initial){
  505. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  506. memcpy(buffer,initial,ibytes);
  507. ogg_sync_wrote(&vf->oy,ibytes);
  508. }
  509. /* can we seek? Stevens suggests the seek test was portable */
  510. if(offset!=-1){
  511. ret=_open_seekable(vf);
  512. }else{
  513. ret=_open_nonseekable(vf);
  514. }
  515. if(ret){
  516. vf->datasource=NULL;
  517. ov_clear(vf);
  518. }
  519. return(ret);
  520. }
  521. /* How many logical bitstreams in this physical bitstream? */
  522. long ov_streams(OggVorbis_File *vf){
  523. return vf->links;
  524. }
  525. /* Is the FILE * associated with vf seekable? */
  526. long ov_seekable(OggVorbis_File *vf){
  527. return vf->seekable;
  528. }
  529. /* returns the bitrate for a given logical bitstream or the entire
  530. physical bitstream. If the file is open for random access, it will
  531. find the *actual* average bitrate. If the file is streaming, it
  532. returns the nominal bitrate (if set) else the average of the
  533. upper/lower bounds (if set) else -1 (unset).
  534. If you want the actual bitrate field settings, get them from the
  535. vorbis_info structs */
  536. long ov_bitrate(OggVorbis_File *vf,int i){
  537. if(i>=vf->links)return(-1);
  538. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  539. if(i<0){
  540. ogg_int64_t bits=0;
  541. int i;
  542. for(i=0;i<vf->links;i++)
  543. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  544. return(rint(bits/ov_time_total(vf,-1)));
  545. }else{
  546. if(vf->seekable){
  547. /* return the actual bitrate */
  548. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  549. }else{
  550. /* return nominal if set */
  551. if(vf->vi[i].bitrate_nominal>0){
  552. return vf->vi[i].bitrate_nominal;
  553. }else{
  554. if(vf->vi[i].bitrate_upper>0){
  555. if(vf->vi[i].bitrate_lower>0){
  556. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  557. }else{
  558. return vf->vi[i].bitrate_upper;
  559. }
  560. }
  561. return(-1);
  562. }
  563. }
  564. }
  565. }
  566. /* returns the actual bitrate since last call. returns -1 if no
  567. additional data to offer since last call (or at beginning of stream) */
  568. long ov_bitrate_instant(OggVorbis_File *vf){
  569. int link=(vf->seekable?vf->current_link:0);
  570. long ret;
  571. if(vf->samptrack==0)return(-1);
  572. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  573. vf->bittrack=0.;
  574. vf->samptrack=0.;
  575. return(ret);
  576. }
  577. /* Guess */
  578. long ov_serialnumber(OggVorbis_File *vf,int i){
  579. if(i>=vf->links)return(-1);
  580. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  581. if(i<0){
  582. return(vf->current_serialno);
  583. }else{
  584. return(vf->serialnos[i]);
  585. }
  586. }
  587. /* returns: total raw (compressed) length of content if i==-1
  588. raw (compressed) length of that logical bitstream for i==0 to n
  589. -1 if the stream is not seekable (we can't know the length)
  590. */
  591. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  592. if(!vf->seekable || i>=vf->links)return(-1);
  593. if(i<0){
  594. long acc=0;
  595. int i;
  596. for(i=0;i<vf->links;i++)
  597. acc+=ov_raw_total(vf,i);
  598. return(acc);
  599. }else{
  600. return(vf->offsets[i+1]-vf->offsets[i]);
  601. }
  602. }
  603. /* returns: total PCM length (samples) of content if i==-1
  604. PCM length (samples) of that logical bitstream for i==0 to n
  605. -1 if the stream is not seekable (we can't know the length)
  606. */
  607. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  608. if(!vf->seekable || i>=vf->links)return(-1);
  609. if(i<0){
  610. ogg_int64_t acc=0;
  611. int i;
  612. for(i=0;i<vf->links;i++)
  613. acc+=ov_pcm_total(vf,i);
  614. return(acc);
  615. }else{
  616. return(vf->pcmlengths[i]);
  617. }
  618. }
  619. /* returns: total seconds of content if i==-1
  620. seconds in that logical bitstream for i==0 to n
  621. -1 if the stream is not seekable (we can't know the length)
  622. */
  623. double ov_time_total(OggVorbis_File *vf,int i){
  624. if(!vf->seekable || i>=vf->links)return(-1);
  625. if(i<0){
  626. double acc=0;
  627. int i;
  628. for(i=0;i<vf->links;i++)
  629. acc+=ov_time_total(vf,i);
  630. return(acc);
  631. }else{
  632. return((float)(vf->pcmlengths[i])/vf->vi[i].rate);
  633. }
  634. }
  635. /* seek to an offset relative to the *compressed* data. This also
  636. immediately sucks in and decodes pages to update the PCM cursor. It
  637. will cross a logical bitstream boundary, but only if it can't get
  638. any packets out of the tail of the bitstream we seek to (so no
  639. surprises).
  640. returns zero on success, nonzero on failure */
  641. int ov_raw_seek(OggVorbis_File *vf,long pos){
  642. if(!vf->seekable)return(-1); /* don't dump machine if we can't seek */
  643. if(pos<0 || pos>vf->offsets[vf->links])goto seek_error;
  644. /* clear out decoding machine state */
  645. vf->pcm_offset=-1;
  646. _decode_clear(vf);
  647. /* seek */
  648. _seek_helper(vf,pos);
  649. /* we need to make sure the pcm_offset is set. We use the
  650. _fetch_packet helper to process one packet with readp set, then
  651. call it until it returns '0' with readp not set (the last packet
  652. from a page has the 'granulepos' field set, and that's how the
  653. helper updates the offset */
  654. switch(_process_packet(vf,1)){
  655. case 0:
  656. /* oh, eof. There are no packets remaining. Set the pcm offset to
  657. the end of file */
  658. vf->pcm_offset=ov_pcm_total(vf,-1);
  659. return(0);
  660. case -1:
  661. /* error! missing data or invalid bitstream structure */
  662. goto seek_error;
  663. default:
  664. /* all OK */
  665. break;
  666. }
  667. while(1){
  668. switch(_process_packet(vf,0)){
  669. case 0:
  670. /* the offset is set. If it's a bogus bitstream with no offset
  671. information, it's not but that's not our fault. We still run
  672. gracefully, we're just missing the offset */
  673. return(0);
  674. case -1:
  675. /* error! missing data or invalid bitstream structure */
  676. goto seek_error;
  677. default:
  678. /* continue processing packets */
  679. break;
  680. }
  681. }
  682. seek_error:
  683. /* dump the machine so we're in a known state */
  684. vf->pcm_offset=-1;
  685. _decode_clear(vf);
  686. return -1;
  687. }
  688. /* seek to a sample offset relative to the decompressed pcm stream
  689. returns zero on success, nonzero on failure */
  690. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  691. int link=-1;
  692. ogg_int64_t total=ov_pcm_total(vf,-1);
  693. if(!vf->seekable)return(-1); /* don't dump machine if we can't seek */
  694. if(pos<0 || pos>total)goto seek_error;
  695. /* which bitstream section does this pcm offset occur in? */
  696. for(link=vf->links-1;link>=0;link--){
  697. total-=vf->pcmlengths[link];
  698. if(pos>=total)break;
  699. }
  700. /* search within the logical bitstream for the page with the highest
  701. pcm_pos preceeding (or equal to) pos. There is a danger here;
  702. missing pages or incorrect frame number information in the
  703. bitstream could make our task impossible. Account for that (it
  704. would be an error condition) */
  705. {
  706. ogg_int64_t target=pos-total;
  707. long end=vf->offsets[link+1];
  708. long begin=vf->offsets[link];
  709. long best=begin;
  710. ogg_page og;
  711. while(begin<end){
  712. long bisect;
  713. long ret;
  714. if(end-begin<CHUNKSIZE){
  715. bisect=begin;
  716. }else{
  717. bisect=(end+begin)/2;
  718. }
  719. _seek_helper(vf,bisect);
  720. ret=_get_next_page(vf,&og,end-bisect);
  721. if(ret==-1){
  722. end=bisect;
  723. }else{
  724. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  725. if(granulepos<target){
  726. best=ret; /* raw offset of packet with granulepos */
  727. begin=vf->offset; /* raw offset of next packet */
  728. }else{
  729. end=bisect;
  730. }
  731. }
  732. }
  733. /* found our page. seek to it (call raw_seek). */
  734. if(ov_raw_seek(vf,best))goto seek_error;
  735. }
  736. /* verify result */
  737. if(vf->pcm_offset>=pos)goto seek_error;
  738. if(pos>ov_pcm_total(vf,-1))goto seek_error;
  739. /* discard samples until we reach the desired position. Crossing a
  740. logical bitstream boundary with abandon is OK. */
  741. while(vf->pcm_offset<pos){
  742. float **pcm;
  743. long target=pos-vf->pcm_offset;
  744. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  745. if(samples>target)samples=target;
  746. vorbis_synthesis_read(&vf->vd,samples);
  747. vf->pcm_offset+=samples;
  748. if(samples<target)
  749. if(_process_packet(vf,1)==0)
  750. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  751. }
  752. return 0;
  753. seek_error:
  754. /* dump machine so we're in a known state */
  755. vf->pcm_offset=-1;
  756. _decode_clear(vf);
  757. return -1;
  758. }
  759. /* seek to a playback time relative to the decompressed pcm stream
  760. returns zero on success, nonzero on failure */
  761. int ov_time_seek(OggVorbis_File *vf,double seconds){
  762. /* translate time to PCM position and call ov_pcm_seek */
  763. int link=-1;
  764. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  765. double time_total=ov_time_total(vf,-1);
  766. if(!vf->seekable)return(-1); /* don't dump machine if we can't seek */
  767. if(seconds<0 || seconds>time_total)goto seek_error;
  768. /* which bitstream section does this time offset occur in? */
  769. for(link=vf->links-1;link>=0;link--){
  770. pcm_total-=vf->pcmlengths[link];
  771. time_total-=ov_time_total(vf,link);
  772. if(seconds>=time_total)break;
  773. }
  774. /* enough information to convert time offset to pcm offset */
  775. {
  776. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  777. return(ov_pcm_seek(vf,target));
  778. }
  779. seek_error:
  780. /* dump machine so we're in a known state */
  781. vf->pcm_offset=-1;
  782. _decode_clear(vf);
  783. return -1;
  784. }
  785. /* tell the current stream offset cursor. Note that seek followed by
  786. tell will likely not give the set offset due to caching */
  787. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  788. return(vf->offset);
  789. }
  790. /* return PCM offset (sample) of next PCM sample to be read */
  791. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  792. return(vf->pcm_offset);
  793. }
  794. /* return time offset (seconds) of next PCM sample to be read */
  795. double ov_time_tell(OggVorbis_File *vf){
  796. /* translate time to PCM position and call ov_pcm_seek */
  797. int link=-1;
  798. ogg_int64_t pcm_total=0;
  799. double time_total=0.;
  800. if(vf->seekable){
  801. pcm_total=ov_pcm_total(vf,-1);
  802. time_total=ov_time_total(vf,-1);
  803. /* which bitstream section does this time offset occur in? */
  804. for(link=vf->links-1;link>=0;link--){
  805. pcm_total-=vf->pcmlengths[link];
  806. time_total-=ov_time_total(vf,link);
  807. if(vf->pcm_offset>=pcm_total)break;
  808. }
  809. }
  810. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  811. }
  812. /* link: -1) return the vorbis_info struct for the bitstream section
  813. currently being decoded
  814. 0-n) to request information for a specific bitstream section
  815. In the case of a non-seekable bitstream, any call returns the
  816. current bitstream. NULL in the case that the machine is not
  817. initialized */
  818. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  819. if(vf->seekable){
  820. if(link<0)
  821. if(vf->decode_ready)
  822. return vf->vi+vf->current_link;
  823. else
  824. return NULL;
  825. else
  826. if(link>=vf->links)
  827. return NULL;
  828. else
  829. return vf->vi+link;
  830. }else{
  831. if(vf->decode_ready)
  832. return vf->vi;
  833. else
  834. return NULL;
  835. }
  836. }
  837. /* grr, strong typing, grr, no templates/inheritence, grr */
  838. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  839. if(vf->seekable){
  840. if(link<0)
  841. if(vf->decode_ready)
  842. return vf->vc+vf->current_link;
  843. else
  844. return NULL;
  845. else
  846. if(link>=vf->links)
  847. return NULL;
  848. else
  849. return vf->vc+link;
  850. }else{
  851. if(vf->decode_ready)
  852. return vf->vc;
  853. else
  854. return NULL;
  855. }
  856. }
  857. int host_is_big_endian() {
  858. short pattern = 0xbabe;
  859. unsigned char *bytewise = (unsigned char *)&pattern;
  860. if (bytewise[0] == 0xba) return 1;
  861. assert(bytewise[0] == 0xbe);
  862. return 0;
  863. }
  864. /* up to this point, everything could more or less hide the multiple
  865. logical bitstream nature of chaining from the toplevel application
  866. if the toplevel application didn't particularly care. However, at
  867. the point that we actually read audio back, the multiple-section
  868. nature must surface: Multiple bitstream sections do not necessarily
  869. have to have the same number of channels or sampling rate.
  870. ov_read returns the sequential logical bitstream number currently
  871. being decoded along with the PCM data in order that the toplevel
  872. application can take action on channel/sample rate changes. This
  873. number will be incremented even for streamed (non-seekable) streams
  874. (for seekable streams, it represents the actual logical bitstream
  875. index within the physical bitstream. Note that the accessor
  876. functions above are aware of this dichotomy).
  877. input values: buffer) a buffer to hold packed PCM data for return
  878. length) the byte length requested to be placed into buffer
  879. bigendianp) should the data be packed LSB first (0) or
  880. MSB first (1)
  881. word) word size for output. currently 1 (byte) or
  882. 2 (16 bit short)
  883. return values: -1) error/hole in data
  884. 0) EOF
  885. n) number of bytes of PCM actually returned. The
  886. below works on a packet-by-packet basis, so the
  887. return length is not related to the 'length' passed
  888. in, just guaranteed to fit.
  889. *section) set to the logical bitstream number */
  890. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  891. int bigendianp,int word,int sgned,int *bitstream){
  892. int i,j;
  893. int host_endian = host_is_big_endian();
  894. while(1){
  895. if(vf->decode_ready){
  896. float **pcm;
  897. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  898. if(samples){
  899. /* yay! proceed to pack data into the byte buffer */
  900. long channels=ov_info(vf,-1)->channels;
  901. long bytespersample=word * channels;
  902. if(samples>length/bytespersample)samples=length/bytespersample;
  903. /* a tight loop to pack each size */
  904. {
  905. int val;
  906. if(word==1){
  907. int off=(sgned?0:128);
  908. for(j=0;j<samples;j++)
  909. for(i=0;i<channels;i++){
  910. val=(int)(pcm[i][j]*128. + 0.5);
  911. if(val>127)val=127;
  912. else if(val<-128)val=-128;
  913. *buffer++=val+off;
  914. }
  915. }else{
  916. int off=(sgned?0:32768);
  917. if(host_endian==bigendianp){
  918. if(sgned){
  919. for(i=0;i<channels;i++) { /* It's faster in this order */
  920. float *src=pcm[i];
  921. short *dest=((short *)buffer)+i;
  922. for(j=0;j<samples;j++) {
  923. val=(int)(src[j]*32768. + 0.5);
  924. if(val>32767)val=32767;
  925. else if(val<-32768)val=-32768;
  926. *dest=val;
  927. dest+=channels;
  928. }
  929. }
  930. }else{
  931. for(i=0;i<channels;i++) {
  932. float *src=pcm[i];
  933. short *dest=((short *)buffer)+i;
  934. for(j=0;j<samples;j++) {
  935. val=(int)(src[j]*32768. + 0.5);
  936. if(val>32767)val=32767;
  937. else if(val<-32768)val=-32768;
  938. *dest=val+off;
  939. dest+=channels;
  940. }
  941. }
  942. }
  943. }else if(bigendianp){
  944. for(j=0;j<samples;j++)
  945. for(i=0;i<channels;i++){
  946. val=(int)(pcm[i][j]*32768. + 0.5);
  947. if(val>32767)val=32767;
  948. else if(val<-32768)val=-32768;
  949. val+=off;
  950. *buffer++=(val>>8);
  951. *buffer++=(val&0xff);
  952. }
  953. }else{
  954. int val;
  955. for(j=0;j<samples;j++)
  956. for(i=0;i<channels;i++){
  957. val=(int)(pcm[i][j]*32768. + 0.5);
  958. if(val>32767)val=32767;
  959. else if(val<-32768)val=-32768;
  960. val+=off;
  961. *buffer++=(val&0xff);
  962. *buffer++=(val>>8);
  963. }
  964. }
  965. }
  966. }
  967. vorbis_synthesis_read(&vf->vd,samples);
  968. vf->pcm_offset+=samples;
  969. if(bitstream)*bitstream=vf->current_link;
  970. return(samples*bytespersample);
  971. }
  972. }
  973. /* suck in another packet */
  974. switch(_process_packet(vf,1)){
  975. case 0:
  976. return(0);
  977. case -1:
  978. return -1;
  979. default:
  980. break;
  981. }
  982. }
  983. }