vorbisfile.c 33 KB

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