vorbisfile.c 30 KB

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