dump_video.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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 http://www.xiph.org/ *
  10. * *
  11. ********************************************************************
  12. function: example dumpvid application; dumps Theora streams
  13. last mod: $Id: dump_video.c,v 1.2 2004/03/24 19:12:42 derf Exp $
  14. ********************************************************************/
  15. /* By Mauricio Piacentini (mauricio at xiph.org) */
  16. /* simply dump decoded YUV data, for verification of theora bitstream */
  17. #if !defined(_REENTRANT)
  18. #define _REENTRANT
  19. #endif
  20. #if !defined(_GNU_SOURCE)
  21. #define _GNU_SOURCE
  22. #endif
  23. #if !defined(_LARGEFILE_SOURCE)
  24. #define _LARGEFILE_SOURCE
  25. #endif
  26. #if !defined(_LARGEFILE64_SOURCE)
  27. #define _LARGEFILE64_SOURCE
  28. #endif
  29. #if !defined(_FILE_OFFSET_BITS)
  30. #define _FILE_OFFSET_BITS 64
  31. #endif
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <string.h>
  35. #include <sys/timeb.h>
  36. #include <sys/types.h>
  37. #include <sys/stat.h>
  38. /*Yes, yes, we're going to hell.*/
  39. #if defined(_WIN32)
  40. #include <io.h>
  41. #endif
  42. #include <fcntl.h>
  43. #include <limits.h>
  44. #include <math.h>
  45. #include <signal.h>
  46. #include "getopt.h"
  47. #include "theora/theoradec.h"
  48. const char *optstring = "o:crf";
  49. struct option options [] = {
  50. {"output",required_argument,NULL,'o'},
  51. {"crop",no_argument,NULL,'c'}, /*Crop down to the picture size.*/
  52. {"raw",no_argument, NULL,'r'}, /*Disable YUV4MPEG2 headers:*/
  53. {"fps-only",no_argument, NULL, 'f'}, /* Only interested in fps of decode loop */
  54. {NULL,0,NULL,0}
  55. };
  56. /* Helper; just grab some more compressed bitstream and sync it for
  57. page extraction */
  58. int buffer_data(FILE *in,ogg_sync_state *oy){
  59. char *buffer=ogg_sync_buffer(oy,4096);
  60. int bytes=fread(buffer,1,4096,in);
  61. ogg_sync_wrote(oy,bytes);
  62. return(bytes);
  63. }
  64. /* never forget that globals are a one-way ticket to Hell */
  65. /* Ogg and codec state for demux/decode */
  66. ogg_sync_state oy;
  67. ogg_page og;
  68. ogg_stream_state vo;
  69. ogg_stream_state to;
  70. th_info ti;
  71. th_comment tc;
  72. th_setup_info *ts=NULL;
  73. th_dec_ctx *td=NULL;
  74. int theora_p=0;
  75. int theora_processing_headers;
  76. int stateflag=0;
  77. /* single frame video buffering */
  78. int videobuf_ready=0;
  79. ogg_int64_t videobuf_granulepos=-1;
  80. double videobuf_time=0;
  81. int raw=0;
  82. int crop=0;
  83. FILE* outfile = NULL;
  84. int got_sigint=0;
  85. static void sigint_handler (int signal) {
  86. got_sigint = 1;
  87. }
  88. static th_ycbcr_buffer ycbcr;
  89. static void stripe_decoded(th_ycbcr_buffer _dst,th_ycbcr_buffer _src,
  90. int _fragy0,int _fragy_end){
  91. int pli;
  92. for(pli=0;pli<3;pli++){
  93. int yshift;
  94. int y_end;
  95. int y;
  96. yshift=pli!=0&&!(ti.pixel_fmt&2);
  97. y_end=_fragy_end<<3-yshift;
  98. /*An implemention intending to display this data would need to check the
  99. crop rectangle before proceeding.*/
  100. for(y=_fragy0<<3-yshift;y<y_end;y++){
  101. memcpy(_dst[pli].data+y*_dst[pli].stride,
  102. _src[pli].data+y*_src[pli].stride,_src[pli].width);
  103. }
  104. }
  105. }
  106. static void open_video(void){
  107. th_stripe_callback cb;
  108. int pli;
  109. /*Here we allocate a buffer so we can use the striped decode feature.
  110. There's no real reason to do this in this application, because we want to
  111. write to the file top-down, but the frame gets decoded bottom up, so we
  112. have to buffer it all anyway.
  113. But this illustrates how the API works.*/
  114. for(pli=0;pli<3;pli++){
  115. int xshift;
  116. int yshift;
  117. xshift=pli!=0&&!(ti.pixel_fmt&1);
  118. yshift=pli!=0&&!(ti.pixel_fmt&2);
  119. ycbcr[pli].data=(unsigned char *)malloc(
  120. (ti.frame_width>>xshift)*(ti.frame_height>>yshift)*
  121. sizeof(*ycbcr[pli].data));
  122. ycbcr[pli].stride=ti.frame_width>>xshift;
  123. ycbcr[pli].width=ti.frame_width>>xshift;
  124. ycbcr[pli].height=ti.frame_height>>yshift;
  125. }
  126. /*Similarly, since ycbcr is a global, there's no real reason to pass it as
  127. the context.
  128. In a more object-oriented decoder, we could pass the "this" pointer
  129. instead (though in C++, platform-dependent calling convention differences
  130. prevent us from using a real member function pointer).*/
  131. cb.ctx=ycbcr;
  132. cb.stripe_decoded=(th_stripe_decoded_func)stripe_decoded;
  133. th_decode_ctl(td,TH_DECCTL_SET_STRIPE_CB,&cb,sizeof(cb));
  134. }
  135. /*Write out the planar YUV frame, uncropped.*/
  136. static void video_write(void){
  137. int pli;
  138. int i;
  139. /*Uncomment the following to do normal, non-striped decoding.
  140. th_ycbcr_buffer ycbcr;
  141. th_decode_ycbcr_out(td,ycbcr);*/
  142. if(outfile){
  143. int x0;
  144. int y0;
  145. int xend;
  146. int yend;
  147. int hdec;
  148. int vdec;
  149. if(crop){
  150. x0=ti.pic_x;
  151. y0=ti.pic_y;
  152. xend=x0+ti.pic_width;
  153. yend=y0+ti.pic_height;
  154. }
  155. else{
  156. x0=y0=0;
  157. xend=ti.frame_width;
  158. yend=ti.frame_height;
  159. }
  160. hdec=vdec=0;
  161. if(!raw)fprintf(outfile, "FRAME\n");
  162. for(pli=0;pli<3;pli++){
  163. for(i=y0>>vdec;i<(yend+vdec>>vdec);i++){
  164. fwrite(ycbcr[pli].data+ycbcr[pli].stride*i+(x0>>hdec), 1,
  165. (xend+hdec>>hdec)-(x0>>hdec), outfile);
  166. }
  167. hdec=!(ti.pixel_fmt&1);
  168. vdec=!(ti.pixel_fmt&2);
  169. }
  170. }
  171. }
  172. /* dump the theora comment header */
  173. static int dump_comments(th_comment *_tc){
  174. int i;
  175. int len;
  176. FILE *out;
  177. out=stderr;
  178. fprintf(out,"Encoded by %s\n",_tc->vendor);
  179. if(_tc->comments){
  180. fprintf(out,"theora comment header:\n");
  181. for(i=0;i<_tc->comments;i++){
  182. if(_tc->user_comments[i]){
  183. len=_tc->comment_lengths[i]<INT_MAX?_tc->comment_lengths[i]:INT_MAX;
  184. fprintf(out,"\t%.*s\n",len,_tc->user_comments[i]);
  185. }
  186. }
  187. }
  188. return 0;
  189. }
  190. /* helper: push a page into the appropriate steam */
  191. /* this can be done blindly; a stream won't accept a page
  192. that doesn't belong to it */
  193. static int queue_page(ogg_page *page){
  194. if(theora_p)ogg_stream_pagein(&to,page);
  195. return 0;
  196. }
  197. static void usage(void){
  198. fprintf(stderr,
  199. "Usage: dumpvid [options] [<infile.ogv>] [-o <outfile.y4m>]\n\n"
  200. "If no input file is given, stdin is used.\n"
  201. "Options:\n\n"
  202. " -o --output <outfile.y4m> File name for decoded output. If\n"
  203. " this option is not given, the\n"
  204. " decompressed data is sent to stdout.\n"
  205. " -c --crop Crop the output to the picture region.\n"
  206. " By default, the entire encoded frame\n"
  207. " is output, including the padding\n"
  208. " require to make the image dimensions\n"
  209. " a multiple of 16.\n"
  210. " -r --raw Output raw YUV with no framing instead\n"
  211. " of YUV4MPEG2 (the default).\n"
  212. " -f --fps-only Only report the decoding frame rate.\n");
  213. exit(1);
  214. }
  215. int main(int argc,char *argv[]){
  216. ogg_packet op;
  217. int long_option_index;
  218. int c;
  219. struct timeb start;
  220. struct timeb after;
  221. struct timeb last;
  222. int fps_only=0;
  223. int frames = 0;
  224. FILE *infile = stdin;
  225. outfile = stdout;
  226. #ifdef _WIN32 /* We need to set stdin/stdout to binary mode on windows. */
  227. /* Beware the evil ifdef. We avoid these where we can, but this one we
  228. cannot. Don't add any more, you'll probably go to hell if you do. */
  229. _setmode( _fileno( stdin ), _O_BINARY );
  230. _setmode( _fileno( stdout ), _O_BINARY );
  231. #endif
  232. /* Process option arguments. */
  233. while((c=getopt_long(argc,argv,optstring,options,&long_option_index))!=EOF){
  234. switch(c){
  235. case 'o':
  236. if(strcmp(optarg,"-")!=0){
  237. outfile=fopen(optarg,"wb");
  238. if(outfile==NULL){
  239. fprintf(stderr,"Unable to open output file '%s'\n", optarg);
  240. exit(1);
  241. }
  242. }else{
  243. outfile=stdout;
  244. }
  245. break;
  246. case 'c':
  247. crop=1;
  248. break;
  249. case 'r':
  250. raw=1;
  251. break;
  252. case 'f':
  253. fps_only = 1;
  254. outfile = NULL;
  255. break;
  256. default:
  257. usage();
  258. }
  259. }
  260. if(optind<argc){
  261. infile=fopen(argv[optind],"rb");
  262. if(infile==NULL){
  263. fprintf(stderr,"Unable to open '%s' for extraction.\n", argv[optind]);
  264. exit(1);
  265. }
  266. if(++optind<argc){
  267. usage();
  268. exit(1);
  269. }
  270. }
  271. /*Ok, Ogg parsing.
  272. The idea here is we have a bitstream that is made up of Ogg pages.
  273. The libogg sync layer will find them for us.
  274. There may be pages from several logical streams interleaved; we find the
  275. first theora stream and ignore any others.
  276. Then we pass the pages for our stream to the libogg stream layer which
  277. assembles our original set of packets out of them.
  278. It's the packets that libtheora actually knows how to handle.*/
  279. /* start up Ogg stream synchronization layer */
  280. ogg_sync_init(&oy);
  281. /* init supporting Theora structures needed in header parsing */
  282. th_comment_init(&tc);
  283. th_info_init(&ti);
  284. /*Ogg file open; parse the headers.
  285. Theora (like Vorbis) depends on some initial header packets for decoder
  286. setup and initialization.
  287. We retrieve these first before entering the main decode loop.*/
  288. /* Only interested in Theora streams */
  289. while(!stateflag){
  290. int ret=buffer_data(infile,&oy);
  291. if(ret==0)break;
  292. while(ogg_sync_pageout(&oy,&og)>0){
  293. int got_packet;
  294. ogg_stream_state test;
  295. /* is this a mandated initial header? If not, stop parsing */
  296. if(!ogg_page_bos(&og)){
  297. /* don't leak the page; get it into the appropriate stream */
  298. queue_page(&og);
  299. stateflag=1;
  300. break;
  301. }
  302. ogg_stream_init(&test,ogg_page_serialno(&og));
  303. ogg_stream_pagein(&test,&og);
  304. got_packet = ogg_stream_packetpeek(&test,&op);
  305. /* identify the codec: try theora */
  306. if((got_packet==1) && !theora_p && (theora_processing_headers=
  307. th_decode_headerin(&ti,&tc,&ts,&op))>=0){
  308. /* it is theora -- save this stream state */
  309. memcpy(&to,&test,sizeof(test));
  310. theora_p=1;
  311. /*Advance past the successfully processed header.*/
  312. if(theora_processing_headers)ogg_stream_packetout(&to,NULL);
  313. }else{
  314. /* whatever it is, we don't care about it */
  315. ogg_stream_clear(&test);
  316. }
  317. }
  318. /* fall through to non-bos page parsing */
  319. }
  320. /* we're expecting more header packets. */
  321. while(theora_p && theora_processing_headers){
  322. int ret;
  323. /* look for further theora headers */
  324. while(theora_processing_headers&&(ret=ogg_stream_packetpeek(&to,&op))){
  325. if(ret<0)continue;
  326. theora_processing_headers=th_decode_headerin(&ti,&tc,&ts,&op);
  327. if(theora_processing_headers<0){
  328. fprintf(stderr,"Error parsing Theora stream headers; "
  329. "corrupt stream?\n");
  330. exit(1);
  331. }
  332. else if(theora_processing_headers>0){
  333. /*Advance past the successfully processed header.*/
  334. ogg_stream_packetout(&to,NULL);
  335. }
  336. theora_p++;
  337. }
  338. /*Stop now so we don't fail if there aren't enough pages in a short
  339. stream.*/
  340. if(!(theora_p && theora_processing_headers))break;
  341. /* The header pages/packets will arrive before anything else we
  342. care about, or the stream is not obeying spec */
  343. if(ogg_sync_pageout(&oy,&og)>0){
  344. queue_page(&og); /* demux into the appropriate stream */
  345. }else{
  346. int ret=buffer_data(infile,&oy); /* someone needs more data */
  347. if(ret==0){
  348. fprintf(stderr,"End of file while searching for codec headers.\n");
  349. exit(1);
  350. }
  351. }
  352. }
  353. /* and now we have it all. initialize decoders */
  354. if(theora_p){
  355. dump_comments(&tc);
  356. td=th_decode_alloc(&ti,ts);
  357. fprintf(stderr,"Ogg logical stream %lx is Theora %dx%d %.02f fps video\n"
  358. "Encoded frame content is %dx%d with %dx%d offset\n",
  359. to.serialno,ti.frame_width,ti.frame_height,
  360. (double)ti.fps_numerator/ti.fps_denominator,
  361. ti.pic_width,ti.pic_height,ti.pic_x,ti.pic_y);
  362. /*{
  363. int arg = 0xffff;
  364. th_decode_ctl(td,TH_DECCTL_SET_TELEMETRY_MBMODE,&arg,sizeof(arg));
  365. th_decode_ctl(td,TH_DECCTL_SET_TELEMETRY_MV,&arg,sizeof(arg));
  366. th_decode_ctl(td,TH_DECCTL_SET_TELEMETRY_QI,&arg,sizeof(arg));
  367. arg=10;
  368. th_decode_ctl(td,TH_DECCTL_SET_TELEMETRY_BITS,&arg,sizeof(arg));
  369. }*/
  370. }else{
  371. /* tear down the partial theora setup */
  372. th_info_clear(&ti);
  373. th_comment_clear(&tc);
  374. }
  375. /*Either way, we're done with the codec setup data.*/
  376. th_setup_free(ts);
  377. /* open video */
  378. if(theora_p)open_video();
  379. if(!raw && outfile){
  380. static const char *CHROMA_TYPES[4]={"420jpeg",NULL,"422jpeg","444"};
  381. int width;
  382. int height;
  383. if(ti.pixel_fmt>=4||ti.pixel_fmt==TH_PF_RSVD){
  384. fprintf(stderr,"Unknown pixel format: %i\n",ti.pixel_fmt);
  385. exit(1);
  386. }
  387. if(crop){
  388. int hdec;
  389. int vdec;
  390. hdec=!(ti.pixel_fmt&1);
  391. vdec=!(ti.pixel_fmt&2);
  392. if((ti.pic_x&hdec)||(ti.pic_width&hdec)
  393. ||(ti.pic_y&vdec)||(ti.pic_height&vdec)){
  394. fprintf(stderr,
  395. "Error: Cropped images with odd offsets/sizes and chroma subsampling\n"
  396. "cannot be output to YUV4MPEG2. Remove the --crop flag or add the\n"
  397. "--raw flag.\n");
  398. exit(1);
  399. }
  400. width=ti.pic_width;
  401. height=ti.pic_height;
  402. }
  403. else{
  404. width=ti.frame_width;
  405. height=ti.frame_height;
  406. }
  407. fprintf(outfile,"YUV4MPEG2 C%s W%d H%d F%d:%d I%c A%d:%d\n",
  408. CHROMA_TYPES[ti.pixel_fmt],width,height,
  409. ti.fps_numerator,ti.fps_denominator,'p',
  410. ti.aspect_numerator,ti.aspect_denominator);
  411. }
  412. /* install signal handler */
  413. signal (SIGINT, sigint_handler);
  414. /*Finally the main decode loop.
  415. It's one Theora packet per frame, so this is pretty straightforward if
  416. we're not trying to maintain sync with other multiplexed streams.
  417. The videobuf_ready flag is used to maintain the input buffer in the libogg
  418. stream state.
  419. If there's no output frame available at the end of the decode step, we must
  420. need more input data.
  421. We could simplify this by just using the return code on
  422. ogg_page_packetout(), but the flag system extends easily to the case where
  423. you care about more than one multiplexed stream (like with audio
  424. playback).
  425. In that case, just maintain a flag for each decoder you care about, and
  426. pull data when any one of them stalls.
  427. videobuf_time holds the presentation time of the currently buffered video
  428. frame.
  429. We ignore this value.*/
  430. stateflag=0; /* playback has not begun */
  431. /* queue any remaining pages from data we buffered but that did not
  432. contain headers */
  433. while(ogg_sync_pageout(&oy,&og)>0){
  434. queue_page(&og);
  435. }
  436. if(fps_only){
  437. ftime(&start);
  438. ftime(&last);
  439. }
  440. while(!got_sigint){
  441. while(theora_p && !videobuf_ready){
  442. /* theora is one in, one out... */
  443. if(ogg_stream_packetout(&to,&op)>0){
  444. if(th_decode_packetin(td,&op,&videobuf_granulepos)>=0){
  445. videobuf_time=th_granule_time(td,videobuf_granulepos);
  446. videobuf_ready=1;
  447. frames++;
  448. if(fps_only)
  449. ftime(&after);
  450. }
  451. }else
  452. break;
  453. }
  454. if(fps_only && (videobuf_ready || fps_only==2)){
  455. long ms =
  456. after.time*1000.+after.millitm-
  457. (last.time*1000.+last.millitm);
  458. if(ms>500 || fps_only==1 ||
  459. (feof(infile) && !videobuf_ready)){
  460. float file_fps = (float)ti.fps_numerator/ti.fps_denominator;
  461. fps_only=2;
  462. ms = after.time*1000.+after.millitm-
  463. (start.time*1000.+start.millitm);
  464. fprintf(stderr,"\rframe:%d rate:%.2fx ",
  465. frames,
  466. frames*1000./(ms*file_fps));
  467. memcpy(&last,&after,sizeof(last));
  468. }
  469. }
  470. if(!videobuf_ready && feof(infile))break;
  471. if(!videobuf_ready){
  472. /* no data yet for somebody. Grab another page */
  473. buffer_data(infile,&oy);
  474. while(ogg_sync_pageout(&oy,&og)>0){
  475. queue_page(&og);
  476. }
  477. }
  478. /* dumpvideo frame, and get new one */
  479. else if(outfile)video_write();
  480. videobuf_ready=0;
  481. }
  482. /* end of decoder loop -- close everything */
  483. if(theora_p){
  484. ogg_stream_clear(&to);
  485. th_decode_free(td);
  486. th_comment_clear(&tc);
  487. th_info_clear(&ti);
  488. }
  489. ogg_sync_clear(&oy);
  490. if(infile && infile!=stdin)fclose(infile);
  491. if(outfile && outfile!=stdout)fclose(outfile);
  492. fprintf(stderr, "\n\n%d frames\n", frames);
  493. fprintf(stderr, "\nDone.\n");
  494. return(0);
  495. }