player_example.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE OggTheora SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  5. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  6. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  7. * *
  8. * THE Theora SOURCE CODE IS COPYRIGHT (C) 2002-2003 *
  9. * by the Xiph.Org Foundation http://www.xiph.org/ *
  10. * *
  11. ********************************************************************
  12. function: example SDL player application; plays Ogg Theora files (with
  13. optional Vorbis audio second stream)
  14. last mod: $Id: player_example.c,v 1.29 2004/03/08 06:44:26 giles Exp $
  15. ********************************************************************/
  16. /* far more complex than most Ogg 'example' programs. The complexity
  17. of maintaining A/V sync is pretty much unavoidable. It's necessary
  18. to actually have audio/video playback to make the hard audio clock
  19. sync actually work. If there's audio playback, there might as well
  20. be simple video playback as well...
  21. A simple 'demux and write back streams' would have been easier,
  22. it's true. */
  23. #define _GNU_SOURCE
  24. #define _LARGEFILE_SOURCE
  25. #define _LARGEFILE64_SOURCE
  26. #define _FILE_OFFSET_BITS 64
  27. #ifdef HAVE_CONFIG_H
  28. # include <config.h>
  29. #endif
  30. #ifndef _REENTRANT
  31. # define _REENTRANT
  32. #endif
  33. #include <stdio.h>
  34. #include <unistd.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <sys/time.h>
  38. #include <sys/types.h>
  39. #include <sys/stat.h>
  40. #include <fcntl.h>
  41. #include <math.h>
  42. #include <signal.h>
  43. #include "theora/theora.h"
  44. #include "vorbis/codec.h"
  45. #include <SDL.h>
  46. /* yes, this makes us OSS-specific for now. None of SDL, libao, libao2
  47. give us any way to determine hardware timing, and since the
  48. hard/kernel buffer is going to be most of or > a second, that's
  49. just a little bit important */
  50. #if defined(__FreeBSD__)
  51. #include <machine/soundcard.h>
  52. #define AUDIO_DEVICE "/dev/audio"
  53. #elif defined(__NetBSD__) || defined(__OpenBSD__)
  54. #include <soundcard.h>
  55. #define AUDIO_DEVICE "/dev/audio"
  56. #else
  57. #include <sys/soundcard.h>
  58. #define AUDIO_DEVICE "/dev/dsp"
  59. #endif
  60. #include <sys/ioctl.h>
  61. /* Helper; just grab some more compressed bitstream and sync it for
  62. page extraction */
  63. int buffer_data(FILE *in,ogg_sync_state *oy){
  64. char *buffer=ogg_sync_buffer(oy,4096);
  65. int bytes=fread(buffer,1,4096,in);
  66. ogg_sync_wrote(oy,bytes);
  67. return(bytes);
  68. }
  69. /* never forget that globals are a one-way ticket to Hell */
  70. /* Ogg and codec state for demux/decode */
  71. ogg_sync_state oy;
  72. ogg_page og;
  73. ogg_stream_state vo;
  74. ogg_stream_state to;
  75. theora_info ti;
  76. theora_comment tc;
  77. theora_state td;
  78. vorbis_info vi;
  79. vorbis_dsp_state vd;
  80. vorbis_block vb;
  81. vorbis_comment vc;
  82. int theora_p=0;
  83. int vorbis_p=0;
  84. int stateflag=0;
  85. /* SDL Video playback structures */
  86. SDL_Surface *screen;
  87. SDL_Overlay *yuv_overlay;
  88. SDL_Rect rect;
  89. /* single frame video buffering */
  90. int videobuf_ready=0;
  91. ogg_int64_t videobuf_granulepos=-1;
  92. double videobuf_time=0;
  93. /* single audio fragment audio buffering */
  94. int audiobuf_fill=0;
  95. int audiobuf_ready=0;
  96. ogg_int16_t *audiobuf;
  97. ogg_int64_t audiobuf_granulepos=0; /* time position of last sample */
  98. /* audio / video synchronization tracking:
  99. Since this will make it to Google at some point and lots of people
  100. search for how to do this, a quick rundown of a practical A/V sync
  101. strategy under Linux [the UNIX where Everything Is Hard]. Naturally,
  102. this works on other platforms using OSS for sound as well.
  103. In OSS, we don't have reliable access to any precise information on
  104. the exact current playback position (that, of course would have been
  105. too easy; the kernel folks like to keep us app people working hard
  106. doing simple things that should have been solved once and abstracted
  107. long ago). Hopefully ALSA solves this a little better; we'll probably
  108. use that once ALSA is the standard in the stable kernel.
  109. We can't use the system clock for a/v sync because audio is hard
  110. synced to its own clock, and both the system and audio clocks suffer
  111. from wobble, drift, and a lack of accuracy that can be guaranteed to
  112. add a reliable percent or so of error. After ten seconds, that's
  113. 100ms. We can't drift by half a second every minute.
  114. Although OSS can't generally tell us where the audio playback pointer
  115. is, we do know that if we work in complete audio fragments and keep
  116. the kernel buffer full, a blocking select on the audio buffer will
  117. give us a writable fragment immediately after playback finishes with
  118. it. We assume at that point that we know the exact number of bytes in
  119. the kernel buffer that have not been played (total fragments minus
  120. one) and calculate clock drift between audio and system then (and only
  121. then). Damp the sync correction fraction, apply, and walla: A
  122. reliable A/V clock that even works if it's interrupted. */
  123. long audiofd_totalsize=-1;
  124. int audiofd_fragsize; /* read and write only complete fragments
  125. so that SNDCTL_DSP_GETOSPACE is
  126. accurate immediately after a bank
  127. switch */
  128. int audiofd=-1;
  129. ogg_int64_t audiofd_timer_calibrate=-1;
  130. static void open_audio(){
  131. audio_buf_info info;
  132. int format=AFMT_S16_NE; /* host endian */
  133. int channels=vi.channels;
  134. int rate=vi.rate;
  135. int ret;
  136. audiofd=open(AUDIO_DEVICE,O_RDWR);
  137. if(audiofd<0){
  138. fprintf(stderr,"Could not open audio device " AUDIO_DEVICE ".\n");
  139. exit(1);
  140. }
  141. ret=ioctl(audiofd,SNDCTL_DSP_SETFMT,&format);
  142. if(ret){
  143. fprintf(stderr,"Could not set 16 bit host-endian playback\n");
  144. exit(1);
  145. }
  146. ret=ioctl(audiofd,SNDCTL_DSP_CHANNELS,&channels);
  147. if(ret){
  148. fprintf(stderr,"Could not set %d channel playback\n",channels);
  149. exit(1);
  150. }
  151. ret=ioctl(audiofd,SNDCTL_DSP_SPEED,&rate);
  152. if(ret){
  153. fprintf(stderr,"Could not set %d Hz playback\n",rate);
  154. exit(1);
  155. }
  156. ioctl(audiofd,SNDCTL_DSP_GETOSPACE,&info);
  157. audiofd_fragsize=info.fragsize;
  158. audiofd_totalsize=info.fragstotal*info.fragsize;
  159. audiobuf=malloc(audiofd_fragsize);
  160. }
  161. static void audio_close(void){
  162. if(audiofd>-1){
  163. ioctl(audiofd,SNDCTL_DSP_RESET,NULL);
  164. close(audiofd);
  165. free(audiobuf);
  166. }
  167. }
  168. /* call this only immediately after unblocking from a full kernel
  169. having a newly empty fragment or at the point of DMA restart */
  170. void audio_calibrate_timer(int restart){
  171. struct timeval tv;
  172. ogg_int64_t current_sample;
  173. ogg_int64_t new_time;
  174. gettimeofday(&tv,0);
  175. new_time=tv.tv_sec*1000+tv.tv_usec/1000;
  176. if(restart){
  177. current_sample=audiobuf_granulepos-audiobuf_fill/2/vi.channels;
  178. }else
  179. current_sample=audiobuf_granulepos-
  180. (audiobuf_fill+audiofd_totalsize-audiofd_fragsize)/2/vi.channels;
  181. new_time-=1000*current_sample/vi.rate;
  182. audiofd_timer_calibrate=new_time;
  183. }
  184. /* get relative time since beginning playback, compensating for A/V
  185. drift */
  186. double get_time(){
  187. static ogg_int64_t last=0;
  188. static ogg_int64_t up=0;
  189. ogg_int64_t now;
  190. struct timeval tv;
  191. gettimeofday(&tv,0);
  192. now=tv.tv_sec*1000+tv.tv_usec/1000;
  193. if(audiofd_timer_calibrate==-1)audiofd_timer_calibrate=last=now;
  194. if(audiofd<0){
  195. /* no audio timer to worry about, we can just use the system clock */
  196. /* only one complication: If the process is suspended, we should
  197. reset timing to account for the gap in play time. Do it the
  198. easy/hack way */
  199. if(now-last>1000)audiofd_timer_calibrate+=(now-last);
  200. last=now;
  201. }
  202. if(now-up>200){
  203. double timebase=(now-audiofd_timer_calibrate)*.001;
  204. int hundredths=timebase*100-(long)timebase*100;
  205. int seconds=(long)timebase%60;
  206. int minutes=((long)timebase/60)%60;
  207. int hours=(long)timebase/3600;
  208. fprintf(stderr," Playing: %d:%02d:%02d.%02d \r",
  209. hours,minutes,seconds,hundredths);
  210. up=now;
  211. }
  212. return (now-audiofd_timer_calibrate)*.001;
  213. }
  214. /* write a fragment to the OSS kernel audio API, but only if we can
  215. stuff in a whole fragment without blocking */
  216. void audio_write_nonblocking(void){
  217. if(audiobuf_ready){
  218. audio_buf_info info;
  219. long bytes;
  220. ioctl(audiofd,SNDCTL_DSP_GETOSPACE,&info);
  221. bytes=info.bytes;
  222. if(bytes>=audiofd_fragsize){
  223. if(bytes==audiofd_totalsize)audio_calibrate_timer(1);
  224. while(1){
  225. bytes=write(audiofd,audiobuf+(audiofd_fragsize-audiobuf_fill),
  226. audiofd_fragsize);
  227. if(bytes>0){
  228. if(bytes!=audiobuf_fill){
  229. /* shouldn't actually be possible... but eh */
  230. audiobuf_fill-=bytes;
  231. }else
  232. break;
  233. }
  234. }
  235. audiobuf_fill=0;
  236. audiobuf_ready=0;
  237. }
  238. }
  239. }
  240. /* clean quit on Ctrl-C for SDL and thread shutdown as per SDL example
  241. (we don't use any threads, but libSDL does) */
  242. int got_sigint=0;
  243. static void sigint_handler (int signal) {
  244. got_sigint = 1;
  245. }
  246. static void open_video(void){
  247. if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
  248. fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
  249. exit(1);
  250. }
  251. screen = SDL_SetVideoMode(ti.frame_width, ti.frame_height, 0, SDL_SWSURFACE);
  252. if ( screen == NULL ) {
  253. fprintf(stderr, "Unable to set %dx%d video: %s\n",
  254. ti.frame_width,ti.frame_height,SDL_GetError());
  255. exit(1);
  256. }
  257. yuv_overlay = SDL_CreateYUVOverlay(ti.frame_width, ti.frame_height,
  258. SDL_YV12_OVERLAY,
  259. screen);
  260. if ( yuv_overlay == NULL ) {
  261. fprintf(stderr, "SDL: Couldn't create SDL_yuv_overlay: %s\n",
  262. SDL_GetError());
  263. exit(1);
  264. }
  265. rect.x = 0;
  266. rect.y = 0;
  267. rect.w = ti.frame_width;
  268. rect.h = ti.frame_height;
  269. SDL_DisplayYUVOverlay(yuv_overlay, &rect);
  270. }
  271. static void video_write(void){
  272. int i;
  273. yuv_buffer yuv;
  274. int crop_offset;
  275. theora_decode_YUVout(&td,&yuv);
  276. /* Lock SDL_yuv_overlay */
  277. if ( SDL_MUSTLOCK(screen) ) {
  278. if ( SDL_LockSurface(screen) < 0 ) return;
  279. }
  280. if (SDL_LockYUVOverlay(yuv_overlay) < 0) return;
  281. /* let's draw the data (*yuv[3]) on a SDL screen (*screen) */
  282. /* deal with border stride */
  283. /* reverse u and v for SDL */
  284. /* and crop input properly, respecting the encoded frame rect */
  285. crop_offset=ti.offset_x+yuv.y_stride*ti.offset_y;
  286. for(i=0;i<yuv_overlay->h;i++)
  287. memcpy(yuv_overlay->pixels[0]+yuv_overlay->pitches[0]*i,
  288. yuv.y+crop_offset+yuv.y_stride*i,
  289. yuv_overlay->w);
  290. crop_offset=(ti.offset_x/2)+(yuv.uv_stride)*(ti.offset_y/2);
  291. for(i=0;i<yuv_overlay->h/2;i++){
  292. memcpy(yuv_overlay->pixels[1]+yuv_overlay->pitches[1]*i,
  293. yuv.v+crop_offset+yuv.uv_stride*i,
  294. yuv_overlay->w/2);
  295. memcpy(yuv_overlay->pixels[2]+yuv_overlay->pitches[2]*i,
  296. yuv.u+crop_offset+yuv.uv_stride*i,
  297. yuv_overlay->w/2);
  298. }
  299. /* Unlock SDL_yuv_overlay */
  300. if ( SDL_MUSTLOCK(screen) ) {
  301. SDL_UnlockSurface(screen);
  302. }
  303. SDL_UnlockYUVOverlay(yuv_overlay);
  304. /* Show, baby, show! */
  305. SDL_DisplayYUVOverlay(yuv_overlay, &rect);
  306. }
  307. /* dump the theora (or vorbis) comment header */
  308. static int dump_comments(theora_comment *tc){
  309. int i, len;
  310. char *value;
  311. FILE *out=stdout;
  312. fprintf(out,"Encoded by %s\n",tc->vendor);
  313. if(tc->comments){
  314. fprintf(out, "theora comment header:\n");
  315. for(i=0;i<tc->comments;i++){
  316. if(tc->user_comments[i]){
  317. len=tc->comment_lengths[i];
  318. value=malloc(len+1);
  319. memcpy(value,tc->user_comments[i],len);
  320. value[len]='\0';
  321. fprintf(out, "\t%s\n", value);
  322. free(value);
  323. }
  324. }
  325. }
  326. return(0);
  327. }
  328. /* Report the encoder-specified colorspace for the video, if any.
  329. We don't actually make use of the information in this example;
  330. a real player should attempt to perform color correction for
  331. whatever display device it supports. */
  332. static void report_colorspace(theora_info *ti)
  333. {
  334. switch(ti->colorspace){
  335. case OC_CS_UNSPECIFIED:
  336. /* nothing to report */
  337. break;;
  338. case OC_CS_ITU_REC_470M:
  339. fprintf(stderr," encoder specified ITU Rec 470M (NTSC) color.\n");
  340. break;;
  341. case OC_CS_ITU_REC_470BG:
  342. fprintf(stderr," encoder specified ITU Rec 470BG (PAL) color.\n");
  343. break;;
  344. default:
  345. fprintf(stderr,"warning: encoder specified unknown colorspace (%d).\n",
  346. ti->colorspace);
  347. break;;
  348. }
  349. }
  350. /* helper: push a page into the appropriate steam */
  351. /* this can be done blindly; a stream won't accept a page
  352. that doesn't belong to it */
  353. static int queue_page(ogg_page *page){
  354. if(theora_p)ogg_stream_pagein(&to,&og);
  355. if(vorbis_p)ogg_stream_pagein(&vo,&og);
  356. return 0;
  357. }
  358. static void usage(void){
  359. fprintf(stderr,
  360. "Usage: player_example <file.ogg>\n"
  361. "input is read from stdin if no file is passed on the command line\n"
  362. "\n"
  363. );
  364. }
  365. int main(int argc,char *argv[]){
  366. int i,j;
  367. ogg_packet op;
  368. FILE *infile = stdin;
  369. #ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */
  370. /* Beware the evil ifdef. We avoid these where we can, but this one we
  371. cannot. Don't add any more, you'll probably go to hell if you do. */
  372. _setmode( _fileno( stdin ), _O_BINARY );
  373. #endif
  374. /* open the input file if any */
  375. if(argc==2){
  376. infile=fopen(argv[1],"rb");
  377. if(infile==NULL){
  378. fprintf(stderr,"Unable to open '%s' for playback.\n", argv[1]);
  379. exit(1);
  380. }
  381. }
  382. if(argc>2){
  383. usage();
  384. exit(1);
  385. }
  386. /* start up Ogg stream synchronization layer */
  387. ogg_sync_init(&oy);
  388. /* init supporting Vorbis structures needed in header parsing */
  389. vorbis_info_init(&vi);
  390. vorbis_comment_init(&vc);
  391. /* init supporting Theora structures needed in header parsing */
  392. theora_comment_init(&tc);
  393. theora_info_init(&ti);
  394. /* Ogg file open; parse the headers */
  395. /* Only interested in Vorbis/Theora streams */
  396. while(!stateflag){
  397. int ret=buffer_data(infile,&oy);
  398. if(ret==0)break;
  399. while(ogg_sync_pageout(&oy,&og)>0){
  400. ogg_stream_state test;
  401. /* is this a mandated initial header? If not, stop parsing */
  402. if(!ogg_page_bos(&og)){
  403. /* don't leak the page; get it into the appropriate stream */
  404. queue_page(&og);
  405. stateflag=1;
  406. break;
  407. }
  408. ogg_stream_init(&test,ogg_page_serialno(&og));
  409. ogg_stream_pagein(&test,&og);
  410. ogg_stream_packetout(&test,&op);
  411. /* identify the codec: try theora */
  412. if(!theora_p && theora_decode_header(&ti,&tc,&op)>=0){
  413. /* it is theora */
  414. memcpy(&to,&test,sizeof(test));
  415. theora_p=1;
  416. }else if(!vorbis_p && vorbis_synthesis_headerin(&vi,&vc,&op)>=0){
  417. /* it is vorbis */
  418. memcpy(&vo,&test,sizeof(test));
  419. vorbis_p=1;
  420. }else{
  421. /* whatever it is, we don't care about it */
  422. ogg_stream_clear(&test);
  423. }
  424. }
  425. /* fall through to non-bos page parsing */
  426. }
  427. /* we're expecting more header packets. */
  428. while((theora_p && theora_p<3) || (vorbis_p && vorbis_p<3)){
  429. int ret;
  430. /* look for further theora headers */
  431. while(theora_p && (theora_p<3) && (ret=ogg_stream_packetout(&to,&op))){
  432. if(ret<0){
  433. fprintf(stderr,"Error parsing Theora stream headers; corrupt stream?\n");
  434. exit(1);
  435. }
  436. if(ret = theora_decode_header(&ti,&tc,&op)){
  437. printf("Error parsing Theora stream headers; corrupt stream?(theora_decode_header) fuck: %d\n",ret);
  438. exit(1);
  439. }
  440. theora_p++;
  441. if(theora_p==3)break;
  442. }
  443. /* look for more vorbis header packets */
  444. while(vorbis_p && (vorbis_p<3) && (ret=ogg_stream_packetout(&vo,&op))){
  445. if(ret<0){
  446. fprintf(stderr,"Error parsing Vorbis stream headers; corrupt stream?\n");
  447. exit(1);
  448. }
  449. if(vorbis_synthesis_headerin(&vi,&vc,&op)){
  450. fprintf(stderr,"Error parsing Vorbis stream headers; corrupt stream?\n");
  451. exit(1);
  452. }
  453. vorbis_p++;
  454. if(vorbis_p==3)break;
  455. }
  456. /* The header pages/packets will arrive before anything else we
  457. care about, or the stream is not obeying spec */
  458. if(ogg_sync_pageout(&oy,&og)>0){
  459. queue_page(&og); /* demux into the appropriate stream */
  460. }else{
  461. int ret=buffer_data(infile,&oy); /* someone needs more data */
  462. if(ret==0){
  463. fprintf(stderr,"End of file while searching for codec headers.\n");
  464. exit(1);
  465. }
  466. }
  467. }
  468. /* and now we have it all. initialize decoders */
  469. if(theora_p){
  470. theora_decode_init(&td,&ti);
  471. printf("Ogg logical stream %x is Theora %dx%d %.02f fps",
  472. (unsigned int)to.serialno,ti.width,ti.height,
  473. (double)ti.fps_numerator/ti.fps_denominator);
  474. switch(ti.pixelformat){
  475. case OC_PF_420: printf(" 4:2:0 video\n"); break;
  476. case OC_PF_422: printf(" 4:2:2 video\n"); break;
  477. case OC_PF_444: printf(" 4:4:4 video\n"); break;
  478. case OC_PF_RSVD:
  479. default:
  480. printf(" video\n (UNKNOWN Chroma sampling!)\n");
  481. break;
  482. }
  483. if(ti.width!=ti.frame_width || ti.height!=ti.frame_height)
  484. printf(" Frame content is %dx%d with offset (%d,%d).\n",
  485. ti.frame_width, ti.frame_height, ti.offset_x, ti.offset_y);
  486. report_colorspace(&ti);
  487. dump_comments(&tc);
  488. }else{
  489. /* tear down the partial theora setup */
  490. theora_info_clear(&ti);
  491. theora_comment_clear(&tc);
  492. }
  493. if(vorbis_p){
  494. vorbis_synthesis_init(&vd,&vi);
  495. vorbis_block_init(&vd,&vb);
  496. fprintf(stderr,"Ogg logical stream %x is Vorbis %d channel %d Hz audio.\n",
  497. (unsigned int)vo.serialno,vi.channels,(int)vi.rate);
  498. }else{
  499. /* tear down the partial vorbis setup */
  500. vorbis_info_clear(&vi);
  501. vorbis_comment_clear(&vc);
  502. }
  503. /* open audio */
  504. if(vorbis_p)open_audio();
  505. /* open video */
  506. if(theora_p)open_video();
  507. /* install signal handler as SDL clobbered the default */
  508. signal (SIGINT, sigint_handler);
  509. /* on to the main decode loop. We assume in this example that audio
  510. and video start roughly together, and don't begin playback until
  511. we have a start frame for both. This is not necessarily a valid
  512. assumption in Ogg A/V streams! It will always be true of the
  513. example_encoder (and most streams) though. */
  514. stateflag=0; /* playback has not begun */
  515. while(!got_sigint){
  516. /* we want a video and audio frame ready to go at all times. If
  517. we have to buffer incoming, buffer the compressed data (ie, let
  518. ogg do the buffering) */
  519. while(vorbis_p && !audiobuf_ready){
  520. int ret;
  521. float **pcm;
  522. /* if there's pending, decoded audio, grab it */
  523. if((ret=vorbis_synthesis_pcmout(&vd,&pcm))>0){
  524. int count=audiobuf_fill/2;
  525. int maxsamples=(audiofd_fragsize-audiobuf_fill)/2/vi.channels;
  526. for(i=0;i<ret && i<maxsamples;i++)
  527. for(j=0;j<vi.channels;j++){
  528. int val=rint(pcm[j][i]*32767.f);
  529. if(val>32767)val=32767;
  530. if(val<-32768)val=-32768;
  531. audiobuf[count++]=val;
  532. }
  533. vorbis_synthesis_read(&vd,i);
  534. audiobuf_fill+=i*vi.channels*2;
  535. if(audiobuf_fill==audiofd_fragsize)audiobuf_ready=1;
  536. if(vd.granulepos>=0)
  537. audiobuf_granulepos=vd.granulepos-ret+i;
  538. else
  539. audiobuf_granulepos+=i;
  540. }else{
  541. /* no pending audio; is there a pending packet to decode? */
  542. if(ogg_stream_packetout(&vo,&op)>0){
  543. if(vorbis_synthesis(&vb,&op)==0) /* test for success! */
  544. vorbis_synthesis_blockin(&vd,&vb);
  545. }else /* we need more data; break out to suck in another page */
  546. break;
  547. }
  548. }
  549. while(theora_p && !videobuf_ready){
  550. /* theora is one in, one out... */
  551. if(ogg_stream_packetout(&to,&op)>0){
  552. theora_decode_packetin(&td,&op);
  553. videobuf_granulepos=td.granulepos;
  554. videobuf_time=theora_granule_time(&td,videobuf_granulepos);
  555. /* is it already too old to be useful? This is only actually
  556. useful cosmetically after a SIGSTOP. Note that we have to
  557. decode the frame even if we don't show it (for now) due to
  558. keyframing. Soon enough libtheora will be able to deal
  559. with non-keyframe seeks. */
  560. if(videobuf_time>=get_time())
  561. videobuf_ready=1;
  562. }else
  563. break;
  564. }
  565. if(!videobuf_ready && !audiobuf_ready && feof(infile))break;
  566. if(!videobuf_ready || !audiobuf_ready){
  567. /* no data yet for somebody. Grab another page */
  568. int bytes=buffer_data(infile,&oy);
  569. while(ogg_sync_pageout(&oy,&og)>0){
  570. queue_page(&og);
  571. }
  572. }
  573. /* If playback has begun, top audio buffer off immediately. */
  574. if(stateflag) audio_write_nonblocking();
  575. /* are we at or past time for this video frame? */
  576. if(stateflag && videobuf_ready && videobuf_time<=get_time()){
  577. video_write();
  578. videobuf_ready=0;
  579. }
  580. if(stateflag &&
  581. (audiobuf_ready || !vorbis_p) &&
  582. (videobuf_ready || !theora_p) &&
  583. !got_sigint){
  584. /* we have an audio frame ready (which means the audio buffer is
  585. full), it's not time to play video, so wait until one of the
  586. audio buffer is ready or it's near time to play video */
  587. /* set up select wait on the audiobuffer and a timeout for video */
  588. struct timeval timeout;
  589. fd_set writefs;
  590. fd_set empty;
  591. int n=0;
  592. FD_ZERO(&writefs);
  593. FD_ZERO(&empty);
  594. if(audiofd>=0){
  595. FD_SET(audiofd,&writefs);
  596. n=audiofd+1;
  597. }
  598. if(theora_p){
  599. long milliseconds=(videobuf_time-get_time())*1000-5;
  600. if(milliseconds>500)milliseconds=500;
  601. if(milliseconds>0){
  602. timeout.tv_sec=milliseconds/1000;
  603. timeout.tv_usec=(milliseconds%1000)*1000;
  604. n=select(n,&empty,&writefs,&empty,&timeout);
  605. if(n)audio_calibrate_timer(0);
  606. }
  607. }else{
  608. select(n,&empty,&writefs,&empty,NULL);
  609. }
  610. }
  611. /* if our buffers either don't exist or are ready to go,
  612. we can begin playback */
  613. if((!theora_p || videobuf_ready) &&
  614. (!vorbis_p || audiobuf_ready))stateflag=1;
  615. /* same if we've run out of input */
  616. if(feof(infile))stateflag=1;
  617. }
  618. /* tear it all down */
  619. audio_close();
  620. SDL_Quit();
  621. if(vorbis_p){
  622. ogg_stream_clear(&vo);
  623. vorbis_block_clear(&vb);
  624. vorbis_dsp_clear(&vd);
  625. vorbis_comment_clear(&vc);
  626. vorbis_info_clear(&vi);
  627. }
  628. if(theora_p){
  629. ogg_stream_clear(&to);
  630. theora_clear(&td);
  631. theora_comment_clear(&tc);
  632. theora_info_clear(&ti);
  633. }
  634. ogg_sync_clear(&oy);
  635. if(infile && infile!=stdin)fclose(infile);
  636. fprintf(stderr,
  637. "\r "
  638. "\nDone.\n");
  639. return(0);
  640. }