player_example.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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-2009 *
  9. * by the Xiph.Org Foundation and contributors 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$
  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. #if !defined(_GNU_SOURCE)
  24. #define _GNU_SOURCE
  25. #endif
  26. #if !defined(_LARGEFILE_SOURCE)
  27. #define _LARGEFILE_SOURCE
  28. #endif
  29. #if !defined(_LARGEFILE64_SOURCE)
  30. #define _LARGEFILE64_SOURCE
  31. #endif
  32. #if !defined(_FILE_OFFSET_BITS)
  33. #define _FILE_OFFSET_BITS 64
  34. #endif
  35. #ifdef HAVE_CONFIG_H
  36. # include <config.h>
  37. #endif
  38. #ifndef _REENTRANT
  39. # define _REENTRANT
  40. #endif
  41. #include <stdio.h>
  42. #include <unistd.h>
  43. #include <stdlib.h>
  44. #include <string.h>
  45. #include <sys/time.h>
  46. #include <sys/types.h>
  47. #include <sys/stat.h>
  48. #include <fcntl.h>
  49. #include <math.h>
  50. #include <signal.h>
  51. #include "theora/theoradec.h"
  52. #include "vorbis/codec.h"
  53. #include <SDL.h>
  54. /* yes, this makes us OSS-specific for now. None of SDL, libao, libao2
  55. give us any way to determine hardware timing, and since the
  56. hard/kernel buffer is going to be most of or > a second, that's
  57. just a little bit important */
  58. #if defined(__FreeBSD__)
  59. #include <machine/soundcard.h>
  60. #define AUDIO_DEVICE "/dev/audio"
  61. #elif defined(__NetBSD__) || defined(__OpenBSD__)
  62. #include <soundcard.h>
  63. #define AUDIO_DEVICE "/dev/audio"
  64. #else
  65. #include <sys/soundcard.h>
  66. #define AUDIO_DEVICE "/dev/dsp"
  67. #endif
  68. #include <sys/ioctl.h>
  69. /* Helper; just grab some more compressed bitstream and sync it for
  70. page extraction */
  71. int buffer_data(FILE *in,ogg_sync_state *oy){
  72. char *buffer=ogg_sync_buffer(oy,4096);
  73. int bytes=fread(buffer,1,4096,in);
  74. ogg_sync_wrote(oy,bytes);
  75. return(bytes);
  76. }
  77. /* never forget that globals are a one-way ticket to Hell */
  78. /* Ogg and codec state for demux/decode */
  79. ogg_sync_state oy;
  80. ogg_page og;
  81. ogg_stream_state vo;
  82. ogg_stream_state to;
  83. th_info ti;
  84. th_comment tc;
  85. th_dec_ctx *td = NULL;
  86. th_setup_info *ts = NULL;
  87. vorbis_info vi;
  88. vorbis_dsp_state vd;
  89. vorbis_block vb;
  90. vorbis_comment vc;
  91. th_pixel_fmt px_fmt;
  92. int theora_p=0;
  93. int vorbis_p=0;
  94. int stateflag=0;
  95. /* SDL Video playback structures */
  96. SDL_Surface *screen;
  97. SDL_Overlay *yuv_overlay;
  98. SDL_Rect rect;
  99. unsigned char *RGBbuffer;
  100. #define OC_CLAMP255(_x) ((unsigned char)((((_x)<0)-1)&((_x)|-((_x)>255))))
  101. /* single frame video buffering */
  102. int videobuf_ready=0;
  103. ogg_int64_t videobuf_granulepos=-1;
  104. double videobuf_time=0;
  105. /* single audio fragment audio buffering */
  106. int audiobuf_fill=0;
  107. int audiobuf_ready=0;
  108. ogg_int16_t *audiobuf;
  109. ogg_int64_t audiobuf_granulepos=0; /* time position of last sample */
  110. /* audio / video synchronization tracking:
  111. Since this will make it to Google at some point and lots of people
  112. search for how to do this, a quick rundown of a practical A/V sync
  113. strategy under Linux [the UNIX where Everything Is Hard]. Naturally,
  114. this works on other platforms using OSS for sound as well.
  115. In OSS, we don't have reliable access to any precise information on
  116. the exact current playback position (that, of course would have been
  117. too easy; the kernel folks like to keep us app people working hard
  118. doing simple things that should have been solved once and abstracted
  119. long ago). Hopefully ALSA solves this a little better; we'll probably
  120. use that once ALSA is the standard in the stable kernel.
  121. We can't use the system clock for a/v sync because audio is hard
  122. synced to its own clock, and both the system and audio clocks suffer
  123. from wobble, drift, and a lack of accuracy that can be guaranteed to
  124. add a reliable percent or so of error. After ten seconds, that's
  125. 100ms. We can't drift by half a second every minute.
  126. Although OSS can't generally tell us where the audio playback pointer
  127. is, we do know that if we work in complete audio fragments and keep
  128. the kernel buffer full, a blocking select on the audio buffer will
  129. give us a writable fragment immediately after playback finishes with
  130. it. We assume at that point that we know the exact number of bytes in
  131. the kernel buffer that have not been played (total fragments minus
  132. one) and calculate clock drift between audio and system then (and only
  133. then). Damp the sync correction fraction, apply, and walla: A
  134. reliable A/V clock that even works if it's interrupted. */
  135. long audiofd_totalsize=-1;
  136. int audiofd_fragsize; /* read and write only complete fragments
  137. so that SNDCTL_DSP_GETOSPACE is
  138. accurate immediately after a bank
  139. switch */
  140. int audiofd=-1;
  141. ogg_int64_t audiofd_timer_calibrate=-1;
  142. static void open_audio(){
  143. audio_buf_info info;
  144. int format=AFMT_S16_NE; /* host endian */
  145. int channels=vi.channels;
  146. int rate=vi.rate;
  147. int ret;
  148. audiofd=open(AUDIO_DEVICE,O_RDWR);
  149. if(audiofd<0){
  150. fprintf(stderr,"Could not open audio device " AUDIO_DEVICE ".\n");
  151. exit(1);
  152. }
  153. ret=ioctl(audiofd,SNDCTL_DSP_SETFMT,&format);
  154. if(ret){
  155. fprintf(stderr,"Could not set 16 bit host-endian playback\n");
  156. exit(1);
  157. }
  158. ret=ioctl(audiofd,SNDCTL_DSP_CHANNELS,&channels);
  159. if(ret){
  160. fprintf(stderr,"Could not set %d channel playback\n",channels);
  161. exit(1);
  162. }
  163. ret=ioctl(audiofd,SNDCTL_DSP_SPEED,&rate);
  164. if(ret){
  165. fprintf(stderr,"Could not set %d Hz playback\n",rate);
  166. exit(1);
  167. }
  168. ioctl(audiofd,SNDCTL_DSP_GETOSPACE,&info);
  169. audiofd_fragsize=info.fragsize;
  170. audiofd_totalsize=info.fragstotal*info.fragsize;
  171. audiobuf=malloc(audiofd_fragsize);
  172. }
  173. static void audio_close(void){
  174. if(audiofd>-1){
  175. ioctl(audiofd,SNDCTL_DSP_RESET,NULL);
  176. close(audiofd);
  177. free(audiobuf);
  178. }
  179. }
  180. /* call this only immediately after unblocking from a full kernel
  181. having a newly empty fragment or at the point of DMA restart */
  182. void audio_calibrate_timer(int restart){
  183. struct timeval tv;
  184. ogg_int64_t current_sample;
  185. ogg_int64_t new_time;
  186. gettimeofday(&tv,0);
  187. new_time=tv.tv_sec*1000+tv.tv_usec/1000;
  188. if(restart){
  189. current_sample=audiobuf_granulepos-audiobuf_fill/2/vi.channels;
  190. }else
  191. current_sample=audiobuf_granulepos-
  192. (audiobuf_fill+audiofd_totalsize-audiofd_fragsize)/2/vi.channels;
  193. new_time-=1000*current_sample/vi.rate;
  194. audiofd_timer_calibrate=new_time;
  195. }
  196. /* get relative time since beginning playback, compensating for A/V
  197. drift */
  198. double get_time(){
  199. static ogg_int64_t last=0;
  200. static ogg_int64_t up=0;
  201. ogg_int64_t now;
  202. struct timeval tv;
  203. gettimeofday(&tv,0);
  204. now=tv.tv_sec*1000+tv.tv_usec/1000;
  205. if(audiofd_timer_calibrate==-1)audiofd_timer_calibrate=last=now;
  206. if(audiofd<0){
  207. /* no audio timer to worry about, we can just use the system clock */
  208. /* only one complication: If the process is suspended, we should
  209. reset timing to account for the gap in play time. Do it the
  210. easy/hack way */
  211. if(now-last>1000)audiofd_timer_calibrate+=(now-last);
  212. last=now;
  213. }
  214. if(now-up>200){
  215. double timebase=(now-audiofd_timer_calibrate)*.001;
  216. int hundredths=timebase*100-(long)timebase*100;
  217. int seconds=(long)timebase%60;
  218. int minutes=((long)timebase/60)%60;
  219. int hours=(long)timebase/3600;
  220. fprintf(stderr," Playing: %d:%02d:%02d.%02d \r",
  221. hours,minutes,seconds,hundredths);
  222. up=now;
  223. }
  224. return (now-audiofd_timer_calibrate)*.001;
  225. }
  226. /* write a fragment to the OSS kernel audio API, but only if we can
  227. stuff in a whole fragment without blocking */
  228. void audio_write_nonblocking(void){
  229. if(audiobuf_ready){
  230. audio_buf_info info;
  231. long bytes;
  232. ioctl(audiofd,SNDCTL_DSP_GETOSPACE,&info);
  233. bytes=info.bytes;
  234. if(bytes>=audiofd_fragsize){
  235. if(bytes==audiofd_totalsize)audio_calibrate_timer(1);
  236. while(1){
  237. bytes=write(audiofd,audiobuf+(audiofd_fragsize-audiobuf_fill),
  238. audiofd_fragsize);
  239. if(bytes>0){
  240. if(bytes!=audiobuf_fill){
  241. /* shouldn't actually be possible... but eh */
  242. audiobuf_fill-=bytes;
  243. }else
  244. break;
  245. }
  246. }
  247. audiobuf_fill=0;
  248. audiobuf_ready=0;
  249. }
  250. }
  251. }
  252. /* clean quit on Ctrl-C for SDL and thread shutdown as per SDL example
  253. (we don't use any threads, but libSDL does) */
  254. int got_sigint=0;
  255. static void sigint_handler (int signal) {
  256. got_sigint = 1;
  257. }
  258. static void open_video(void){
  259. int w;
  260. int h;
  261. w=(ti.pic_x+ti.pic_width+1&~1)-(ti.pic_x&~1);
  262. h=(ti.pic_y+ti.pic_height+1&~1)-(ti.pic_y&~1);
  263. if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
  264. fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
  265. exit(1);
  266. }
  267. screen = SDL_SetVideoMode(w, h, 0, SDL_SWSURFACE);
  268. if ( screen == NULL ) {
  269. fprintf(stderr, "Unable to set %dx%d video: %s\n",
  270. w,h,SDL_GetError());
  271. exit(1);
  272. }
  273. if (px_fmt==TH_PF_422)
  274. yuv_overlay = SDL_CreateYUVOverlay(w, h,
  275. SDL_YUY2_OVERLAY,
  276. screen);
  277. else if (px_fmt==TH_PF_444) {
  278. RGBbuffer = calloc(w*h*4,sizeof(*RGBbuffer));
  279. fprintf(stderr,"warning: SDL does not support YUV 4:4:4, using slow software conversion.\n");
  280. } else
  281. yuv_overlay = SDL_CreateYUVOverlay(w, h,
  282. SDL_YV12_OVERLAY,
  283. screen);
  284. if ( (yuv_overlay == NULL && px_fmt!=TH_PF_444) || (screen == NULL && px_fmt==TH_PF_444) ) {
  285. fprintf(stderr, "SDL: xCouldn't create SDL_yuv_overlay: %s\n",
  286. SDL_GetError());
  287. exit(1);
  288. }
  289. rect.x = 0;
  290. rect.y = 0;
  291. rect.w = w;
  292. rect.h = h;
  293. if (px_fmt!=TH_PF_444)
  294. SDL_DisplayYUVOverlay(yuv_overlay, &rect);
  295. }
  296. static void video_write(void){
  297. int i;
  298. th_ycbcr_buffer yuv;
  299. int y_offset, uv_offset;
  300. th_decode_ycbcr_out(td,yuv);
  301. /* Lock SDL_yuv_overlay */
  302. if ( SDL_MUSTLOCK(screen) ) {
  303. if ( SDL_LockSurface(screen) < 0 ) return;
  304. }
  305. if (px_fmt!=TH_PF_444 && SDL_LockYUVOverlay(yuv_overlay) < 0) return;
  306. /* let's draw the data on a SDL screen (*screen) */
  307. /* deal with border stride */
  308. /* reverse u and v for SDL */
  309. /* and crop input properly, respecting the encoded frame rect */
  310. /* problems may exist for odd frame rect for some encodings */
  311. y_offset=(ti.pic_x&~1)+yuv[0].stride*(ti.pic_y&~1);
  312. if (px_fmt==TH_PF_422) {
  313. uv_offset=(ti.pic_x/2)+(yuv[1].stride)*(ti.pic_y);
  314. /* SDL doesn't have a planar 4:2:2 */
  315. for(i=0;i<yuv_overlay->h;i++) {
  316. int j;
  317. char *in_y = (char *)yuv[0].data+y_offset+yuv[0].stride*i;
  318. char *out = (char *)(yuv_overlay->pixels[0]+yuv_overlay->pitches[0]*i);
  319. for (j=0;j<yuv_overlay->w;j++)
  320. out[j*2] = in_y[j];
  321. char *in_u = (char *)yuv[1].data+uv_offset+yuv[1].stride*i;
  322. char *in_v = (char *)yuv[2].data+uv_offset+yuv[2].stride*i;
  323. for (j=0;j<yuv_overlay->w>>1;j++) {
  324. out[j*4+1] = in_u[j];
  325. out[j*4+3] = in_v[j];
  326. }
  327. }
  328. } else if (px_fmt==TH_PF_444){
  329. SDL_Surface *output;
  330. for(i=0;i<screen->h;i++) {
  331. int j;
  332. unsigned char *in_y = (unsigned char *)yuv[0].data+y_offset+yuv[0].stride*i;
  333. unsigned char *in_u = (unsigned char *)yuv[1].data+y_offset+yuv[1].stride*i;
  334. unsigned char *in_v = (unsigned char *)yuv[2].data+y_offset+yuv[2].stride*i;
  335. unsigned char *out = RGBbuffer+(screen->w*i*4);
  336. for (j=0;j<screen->w;j++) {
  337. int r, g, b;
  338. r=(1904000*in_y[j]+2609823*in_v[j]-363703744)/1635200;
  339. g=(3827562*in_y[j]-1287801*in_u[j]
  340. -2672387*in_v[j]+447306710)/3287200;
  341. b=(952000*in_y[j]+1649289*in_u[j]-225932192)/817600;
  342. out[4*j+0]=OC_CLAMP255(b);
  343. out[4*j+1]=OC_CLAMP255(g);
  344. out[4*j+2]=OC_CLAMP255(r);
  345. }
  346. output=SDL_CreateRGBSurfaceFrom(RGBbuffer,screen->w,screen->h,32,4*screen->w,0,0,0,0);
  347. SDL_BlitSurface(output,NULL,screen,NULL);
  348. }
  349. } else {
  350. uv_offset=(ti.pic_x/2)+(yuv[1].stride)*(ti.pic_y/2);
  351. for(i=0;i<yuv_overlay->h;i++)
  352. memcpy(yuv_overlay->pixels[0]+yuv_overlay->pitches[0]*i,
  353. yuv[0].data+y_offset+yuv[0].stride*i,
  354. yuv_overlay->w);
  355. for(i=0;i<yuv_overlay->h/2;i++){
  356. memcpy(yuv_overlay->pixels[1]+yuv_overlay->pitches[1]*i,
  357. yuv[2].data+uv_offset+yuv[2].stride*i,
  358. yuv_overlay->w/2);
  359. memcpy(yuv_overlay->pixels[2]+yuv_overlay->pitches[2]*i,
  360. yuv[1].data+uv_offset+yuv[1].stride*i,
  361. yuv_overlay->w/2);
  362. }
  363. }
  364. /* Unlock SDL_yuv_overlay */
  365. if ( SDL_MUSTLOCK(screen) ) {
  366. SDL_UnlockSurface(screen);
  367. }
  368. if (px_fmt!=TH_PF_444) {
  369. SDL_UnlockYUVOverlay(yuv_overlay);
  370. /* Show, baby, show! */
  371. SDL_DisplayYUVOverlay(yuv_overlay, &rect);
  372. } else {
  373. SDL_Flip(screen);
  374. }
  375. }
  376. /* dump the theora (or vorbis) comment header */
  377. static int dump_comments(th_comment *tc){
  378. int i, len;
  379. char *value;
  380. FILE *out=stdout;
  381. fprintf(out,"Encoded by %s\n",tc->vendor);
  382. if(tc->comments){
  383. fprintf(out, "theora comment header:\n");
  384. for(i=0;i<tc->comments;i++){
  385. if(tc->user_comments[i]){
  386. len=tc->comment_lengths[i];
  387. value=malloc(len+1);
  388. memcpy(value,tc->user_comments[i],len);
  389. value[len]='\0';
  390. fprintf(out, "\t%s\n", value);
  391. free(value);
  392. }
  393. }
  394. }
  395. return(0);
  396. }
  397. /* Report the encoder-specified colorspace for the video, if any.
  398. We don't actually make use of the information in this example;
  399. a real player should attempt to perform color correction for
  400. whatever display device it supports. */
  401. static void report_colorspace(th_info *ti)
  402. {
  403. switch(ti->colorspace){
  404. case TH_CS_UNSPECIFIED:
  405. /* nothing to report */
  406. break;;
  407. case TH_CS_ITU_REC_470M:
  408. fprintf(stderr," encoder specified ITU Rec 470M (NTSC) color.\n");
  409. break;;
  410. case TH_CS_ITU_REC_470BG:
  411. fprintf(stderr," encoder specified ITU Rec 470BG (PAL) color.\n");
  412. break;;
  413. default:
  414. fprintf(stderr,"warning: encoder specified unknown colorspace (%d).\n",
  415. ti->colorspace);
  416. break;;
  417. }
  418. }
  419. /* helper: push a page into the appropriate steam */
  420. /* this can be done blindly; a stream won't accept a page
  421. that doesn't belong to it */
  422. static int queue_page(ogg_page *page){
  423. if(theora_p)ogg_stream_pagein(&to,page);
  424. if(vorbis_p)ogg_stream_pagein(&vo,page);
  425. return 0;
  426. }
  427. static void usage(void){
  428. fprintf(stderr,
  429. "Usage: player_example <file.ogv>\n"
  430. "input is read from stdin if no file is passed on the command line\n"
  431. "\n"
  432. );
  433. }
  434. int main(int argc,char *const *argv){
  435. int pp_level_max;
  436. int pp_level;
  437. int pp_inc;
  438. int i,j;
  439. ogg_packet op;
  440. FILE *infile = stdin;
  441. int frames = 0;
  442. int dropped = 0;
  443. #ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */
  444. /* Beware the evil ifdef. We avoid these where we can, but this one we
  445. cannot. Don't add any more, you'll probably go to hell if you do. */
  446. _setmode( _fileno( stdin ), _O_BINARY );
  447. #endif
  448. /* open the input file if any */
  449. if(argc==2){
  450. infile=fopen(argv[1],"rb");
  451. if(infile==NULL){
  452. fprintf(stderr,"Unable to open '%s' for playback.\n", argv[1]);
  453. exit(1);
  454. }
  455. }
  456. if(argc>2){
  457. usage();
  458. exit(1);
  459. }
  460. /* start up Ogg stream synchronization layer */
  461. ogg_sync_init(&oy);
  462. /* init supporting Vorbis structures needed in header parsing */
  463. vorbis_info_init(&vi);
  464. vorbis_comment_init(&vc);
  465. /* init supporting Theora structures needed in header parsing */
  466. th_comment_init(&tc);
  467. th_info_init(&ti);
  468. /* Ogg file open; parse the headers */
  469. /* Only interested in Vorbis/Theora streams */
  470. while(!stateflag){
  471. int ret=buffer_data(infile,&oy);
  472. if(ret==0)break;
  473. while(ogg_sync_pageout(&oy,&og)>0){
  474. ogg_stream_state test;
  475. /* is this a mandated initial header? If not, stop parsing */
  476. if(!ogg_page_bos(&og)){
  477. /* don't leak the page; get it into the appropriate stream */
  478. queue_page(&og);
  479. stateflag=1;
  480. break;
  481. }
  482. ogg_stream_init(&test,ogg_page_serialno(&og));
  483. ogg_stream_pagein(&test,&og);
  484. ogg_stream_packetout(&test,&op);
  485. /* identify the codec: try theora */
  486. if(!theora_p && th_decode_headerin(&ti,&tc,&ts,&op)>=0){
  487. /* it is theora */
  488. memcpy(&to,&test,sizeof(test));
  489. theora_p=1;
  490. }else if(!vorbis_p && vorbis_synthesis_headerin(&vi,&vc,&op)>=0){
  491. /* it is vorbis */
  492. memcpy(&vo,&test,sizeof(test));
  493. vorbis_p=1;
  494. }else{
  495. /* whatever it is, we don't care about it */
  496. ogg_stream_clear(&test);
  497. }
  498. }
  499. /* fall through to non-bos page parsing */
  500. }
  501. /* we're expecting more header packets. */
  502. while((theora_p && theora_p<3) || (vorbis_p && vorbis_p<3)){
  503. int ret;
  504. /* look for further theora headers */
  505. while(theora_p && (theora_p<3) && (ret=ogg_stream_packetout(&to,&op))){
  506. if(ret<0){
  507. fprintf(stderr,"Error parsing Theora stream headers; "
  508. "corrupt stream?\n");
  509. exit(1);
  510. }
  511. if(!th_decode_headerin(&ti,&tc,&ts,&op)){
  512. fprintf(stderr,"Error parsing Theora stream headers; "
  513. "corrupt stream?\n");
  514. exit(1);
  515. }
  516. theora_p++;
  517. }
  518. /* look for more vorbis header packets */
  519. while(vorbis_p && (vorbis_p<3) && (ret=ogg_stream_packetout(&vo,&op))){
  520. if(ret<0){
  521. fprintf(stderr,"Error parsing Vorbis stream headers; corrupt stream?\n");
  522. exit(1);
  523. }
  524. if(vorbis_synthesis_headerin(&vi,&vc,&op)){
  525. fprintf(stderr,"Error parsing Vorbis stream headers; corrupt stream?\n");
  526. exit(1);
  527. }
  528. vorbis_p++;
  529. if(vorbis_p==3)break;
  530. }
  531. /* The header pages/packets will arrive before anything else we
  532. care about, or the stream is not obeying spec */
  533. if(ogg_sync_pageout(&oy,&og)>0){
  534. queue_page(&og); /* demux into the appropriate stream */
  535. }else{
  536. int ret=buffer_data(infile,&oy); /* someone needs more data */
  537. if(ret==0){
  538. fprintf(stderr,"End of file while searching for codec headers.\n");
  539. exit(1);
  540. }
  541. }
  542. }
  543. /* and now we have it all. initialize decoders */
  544. if(theora_p){
  545. td=th_decode_alloc(&ti,ts);
  546. printf("Ogg logical stream %lx is Theora %dx%d %.02f fps",
  547. to.serialno,ti.pic_width,ti.pic_height,
  548. (double)ti.fps_numerator/ti.fps_denominator);
  549. px_fmt=ti.pixel_fmt;
  550. switch(ti.pixel_fmt){
  551. case TH_PF_420: printf(" 4:2:0 video\n"); break;
  552. case TH_PF_422: printf(" 4:2:2 video\n"); break;
  553. case TH_PF_444: printf(" 4:4:4 video\n"); break;
  554. case TH_PF_RSVD:
  555. default:
  556. printf(" video\n (UNKNOWN Chroma sampling!)\n");
  557. break;
  558. }
  559. if(ti.pic_width!=ti.frame_width || ti.pic_height!=ti.frame_height)
  560. printf(" Frame content is %dx%d with offset (%d,%d).\n",
  561. ti.frame_width, ti.frame_height, ti.pic_x, ti.pic_y);
  562. report_colorspace(&ti);
  563. dump_comments(&tc);
  564. th_decode_ctl(td,TH_DECCTL_GET_PPLEVEL_MAX,&pp_level_max,
  565. sizeof(pp_level_max));
  566. pp_level=pp_level_max;
  567. th_decode_ctl(td,TH_DECCTL_SET_PPLEVEL,&pp_level,sizeof(pp_level));
  568. pp_inc=0;
  569. /*{
  570. int arg = 0xffff;
  571. th_decode_ctl(td,TH_DECCTL_SET_TELEMETRY_MBMODE,&arg,sizeof(arg));
  572. th_decode_ctl(td,TH_DECCTL_SET_TELEMETRY_MV,&arg,sizeof(arg));
  573. th_decode_ctl(td,TH_DECCTL_SET_TELEMETRY_QI,&arg,sizeof(arg));
  574. arg=10;
  575. th_decode_ctl(td,TH_DECCTL_SET_TELEMETRY_BITS,&arg,sizeof(arg));
  576. }*/
  577. }else{
  578. /* tear down the partial theora setup */
  579. th_info_clear(&ti);
  580. th_comment_clear(&tc);
  581. }
  582. th_setup_free(ts);
  583. if(vorbis_p){
  584. vorbis_synthesis_init(&vd,&vi);
  585. vorbis_block_init(&vd,&vb);
  586. fprintf(stderr,"Ogg logical stream %lx is Vorbis %d channel %ld Hz audio.\n",
  587. vo.serialno,vi.channels,vi.rate);
  588. }else{
  589. /* tear down the partial vorbis setup */
  590. vorbis_info_clear(&vi);
  591. vorbis_comment_clear(&vc);
  592. }
  593. /* open audio */
  594. if(vorbis_p)open_audio();
  595. /* open video */
  596. if(theora_p)open_video();
  597. /* install signal handler as SDL clobbered the default */
  598. signal (SIGINT, sigint_handler);
  599. /* on to the main decode loop. We assume in this example that audio
  600. and video start roughly together, and don't begin playback until
  601. we have a start frame for both. This is not necessarily a valid
  602. assumption in Ogg A/V streams! It will always be true of the
  603. example_encoder (and most streams) though. */
  604. stateflag=0; /* playback has not begun */
  605. while(!got_sigint){
  606. /* we want a video and audio frame ready to go at all times. If
  607. we have to buffer incoming, buffer the compressed data (ie, let
  608. ogg do the buffering) */
  609. while(vorbis_p && !audiobuf_ready){
  610. int ret;
  611. float **pcm;
  612. /* if there's pending, decoded audio, grab it */
  613. if((ret=vorbis_synthesis_pcmout(&vd,&pcm))>0){
  614. int count=audiobuf_fill/2;
  615. int maxsamples=(audiofd_fragsize-audiobuf_fill)/2/vi.channels;
  616. for(i=0;i<ret && i<maxsamples;i++)
  617. for(j=0;j<vi.channels;j++){
  618. int val=rint(pcm[j][i]*32767.f);
  619. if(val>32767)val=32767;
  620. if(val<-32768)val=-32768;
  621. audiobuf[count++]=val;
  622. }
  623. vorbis_synthesis_read(&vd,i);
  624. audiobuf_fill+=i*vi.channels*2;
  625. if(audiobuf_fill==audiofd_fragsize)audiobuf_ready=1;
  626. if(vd.granulepos>=0)
  627. audiobuf_granulepos=vd.granulepos-ret+i;
  628. else
  629. audiobuf_granulepos+=i;
  630. }else{
  631. /* no pending audio; is there a pending packet to decode? */
  632. if(ogg_stream_packetout(&vo,&op)>0){
  633. if(vorbis_synthesis(&vb,&op)==0) /* test for success! */
  634. vorbis_synthesis_blockin(&vd,&vb);
  635. }else /* we need more data; break out to suck in another page */
  636. break;
  637. }
  638. }
  639. while(theora_p && !videobuf_ready){
  640. /* theora is one in, one out... */
  641. if(ogg_stream_packetout(&to,&op)>0){
  642. if(pp_inc){
  643. pp_level+=pp_inc;
  644. th_decode_ctl(td,TH_DECCTL_SET_PPLEVEL,&pp_level,
  645. sizeof(pp_level));
  646. pp_inc=0;
  647. }
  648. /*HACK: This should be set after a seek or a gap, but we might not have
  649. a granulepos for the first packet (we only have them for the last
  650. packet on a page), so we just set it as often as we get it.
  651. To do this right, we should back-track from the last packet on the
  652. page and compute the correct granulepos for the first packet after
  653. a seek or a gap.*/
  654. if(op.granulepos>=0){
  655. th_decode_ctl(td,TH_DECCTL_SET_GRANPOS,&op.granulepos,
  656. sizeof(op.granulepos));
  657. }
  658. if(th_decode_packetin(td,&op,&videobuf_granulepos)==0){
  659. videobuf_time=th_granule_time(td,videobuf_granulepos);
  660. frames++;
  661. /* is it already too old to be useful? This is only actually
  662. useful cosmetically after a SIGSTOP. Note that we have to
  663. decode the frame even if we don't show it (for now) due to
  664. keyframing. Soon enough libtheora will be able to deal
  665. with non-keyframe seeks. */
  666. if(videobuf_time>=get_time())
  667. videobuf_ready=1;
  668. else{
  669. /*If we are too slow, reduce the pp level.*/
  670. pp_inc=pp_level>0?-1:0;
  671. dropped++;
  672. }
  673. }
  674. }else
  675. break;
  676. }
  677. if(!videobuf_ready && !audiobuf_ready && feof(infile))break;
  678. if(!videobuf_ready || !audiobuf_ready){
  679. /* no data yet for somebody. Grab another page */
  680. buffer_data(infile,&oy);
  681. while(ogg_sync_pageout(&oy,&og)>0){
  682. queue_page(&og);
  683. }
  684. }
  685. /* If playback has begun, top audio buffer off immediately. */
  686. if(stateflag) audio_write_nonblocking();
  687. /* are we at or past time for this video frame? */
  688. if(stateflag && videobuf_ready && videobuf_time<=get_time()){
  689. video_write();
  690. videobuf_ready=0;
  691. }
  692. if(stateflag &&
  693. (audiobuf_ready || !vorbis_p) &&
  694. (videobuf_ready || !theora_p) &&
  695. !got_sigint){
  696. /* we have an audio frame ready (which means the audio buffer is
  697. full), it's not time to play video, so wait until one of the
  698. audio buffer is ready or it's near time to play video */
  699. /* set up select wait on the audiobuffer and a timeout for video */
  700. struct timeval timeout;
  701. fd_set writefs;
  702. fd_set empty;
  703. int n=0;
  704. FD_ZERO(&writefs);
  705. FD_ZERO(&empty);
  706. if(audiofd>=0){
  707. FD_SET(audiofd,&writefs);
  708. n=audiofd+1;
  709. }
  710. if(theora_p){
  711. double tdiff;
  712. long milliseconds;
  713. tdiff=videobuf_time-get_time();
  714. /*If we have lots of extra time, increase the post-processing level.*/
  715. if(tdiff>ti.fps_denominator*0.25/ti.fps_numerator){
  716. pp_inc=pp_level<pp_level_max?1:0;
  717. }
  718. else if(tdiff<ti.fps_denominator*0.05/ti.fps_numerator){
  719. pp_inc=pp_level>0?-1:0;
  720. }
  721. milliseconds=tdiff*1000-5;
  722. if(milliseconds>500)milliseconds=500;
  723. if(milliseconds>0){
  724. timeout.tv_sec=milliseconds/1000;
  725. timeout.tv_usec=(milliseconds%1000)*1000;
  726. n=select(n,&empty,&writefs,&empty,&timeout);
  727. if(n)audio_calibrate_timer(0);
  728. }
  729. }else{
  730. select(n,&empty,&writefs,&empty,NULL);
  731. }
  732. }
  733. /* if our buffers either don't exist or are ready to go,
  734. we can begin playback */
  735. if((!theora_p || videobuf_ready) &&
  736. (!vorbis_p || audiobuf_ready))stateflag=1;
  737. /* same if we've run out of input */
  738. if(feof(infile))stateflag=1;
  739. }
  740. /* tear it all down */
  741. audio_close();
  742. SDL_Quit();
  743. if(vorbis_p){
  744. ogg_stream_clear(&vo);
  745. vorbis_block_clear(&vb);
  746. vorbis_dsp_clear(&vd);
  747. vorbis_comment_clear(&vc);
  748. vorbis_info_clear(&vi);
  749. }
  750. if(theora_p){
  751. ogg_stream_clear(&to);
  752. th_decode_free(td);
  753. th_comment_clear(&tc);
  754. th_info_clear(&ti);
  755. }
  756. ogg_sync_clear(&oy);
  757. if(infile && infile!=stdin)fclose(infile);
  758. fprintf(stderr,
  759. "\r \r");
  760. fprintf(stderr, "%d frames", frames);
  761. if (dropped) fprintf(stderr, " (%d dropped)", dropped);
  762. fprintf(stderr, "\n");
  763. fprintf(stderr, "\nDone.\n");
  764. return(0);
  765. }