Debian Codegraph @

win32/experimental/transcoder/transcoder_example.c

raw
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-2004 *
9 * by the Xiph.Org Foundation https://www.xiph.org/ *
10 * *
11 ********************************************************************
12
13 function: example encoder application; makes an Ogg Theora/Vorbis
14 file from YUV4MPEG2 and WAV input
15
16 ********************************************************************/
17
18 #define _GNU_SOURCE
19 #define _REENTRANT
20 #define _LARGEFILE_SOURCE
21 #define _LARGEFILE64_SOURCE
22 #define _FILE_OFFSET_BITS 64
23
24 #include <stdio.h>
25 #include <unistd.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <getopt.h>
29 #include <time.h>
30 #include <math.h>
31 #include "theora/theora.h"
32 #include "vorbis/codec.h"
33 #include "vorbis/vorbisenc.h"
34
35 #ifdef _WIN32
36 /*supply missing headers and functions to Win32. going to hell, I know*/
37 #include <io.h>
38 #include <fcntl.h>
39
40 static double rint(double x)
41 {
42 if (x < 0.0)
43 return (double)(int)(x - 0.5);
44 else
45 return (double)(int)(x + 0.5);
46 }
47 #endif
48
49 /*Copied from vorbis/sharedbook.c*/
50 static int _ilog(unsigned int v){
51 int ret=0;
52 while(v){
53 ret++;
54 v>>=1;
55 }
56 return(ret);
57 }
58
59
60 const char *optstring = "o:a:A:v:V:";
61 struct option options [] = {
62 {"output",required_argument,NULL,'o'},
63 {"audio-rate-target",required_argument,NULL,'A'},
64 {"video-rate-target",required_argument,NULL,'V'},
65 {"audio-quality",required_argument,NULL,'a'},
66 {"video-quality",required_argument,NULL,'v'},
67 {NULL,0,NULL,0}
68 };
69
70 typedef struct TC_INSTANCE {
71 ogg_uint32_t LastKeyFrame ;
72 ogg_int64_t KeyFrameCount;
73 int ThisIsFirstFrame;
74 int ThisIsKeyFrame;
75 ogg_uint32_t CurrentFrame;
76 ogg_int64_t granulepos;
77 int keyframe_granule_shift;
78 char * in_bytes;
79 long in_bytecount;
80 ogg_uint32_t fps_denominator;
81 ogg_uint32_t fps_numerator;
82 oggpack_buffer opb_in;
83 oggpack_buffer opb_out;
84 } TC_INSTANCE;
85
86 /* You'll go to Hell for using globals. */
87
88 FILE *audio=NULL;
89 FILE *video=NULL;
90
91 int audio_ch=0;
92 int audio_hz=0;
93
94 float audio_q=.1;
95 int audio_r=-1;
96
97 int video_x=0;
98 int video_y=0;
99 int frame_x=0;
100 int frame_y=0;
101 int frame_x_offset=0;
102 int frame_y_offset=0;
103 int video_hzn=0;
104 int video_hzd=0;
105 int video_an=0;
106 int video_ad=0;
107
108 int video_r=-1;
109 int video_q=16;
110
111 char *vp3frame[2];
112 int framebytecount[2];
113 int frameiskey[2];
114
115 ogg_page audiopage;
116 ogg_page videopage;
117
118 static void usage(void){
119 fprintf(stderr,
120 "Usage: encoder_example [options] [audio_file] video_file\n\n"
121 "Options: \n\n"
122 " -o --output <filename.ogv> file name for encoded output;\n"
123 " If this option is not given, the\n"
124 " compressed data is sent to stdout.\n\n"
125 " -A --audio-rate-target <n> bitrate target for Vorbis audio;\n"
126 " use -a and not -A if at all possible,\n"
127 " as -a gives higher quality for a given\n"
128 " bitrate.\n\n"
129 " -V --video-rate-target <n> bitrate target for Theora video\n\n"
130 " -a --audio-quality <n> Vorbis quality selector from -1 to 10\n"
131 " (-1 yields smallest files but lowest\n"
132 " fidelity; 10 yields highest fidelity\n"
133 " but large files. '2' is a reasonable\n"
134 " default).\n\n"
135 " -v --video-quality <n> Theora quality selector from 0 to 10\n"
136 " (0 yields smallest files but lowest\n"
137 " video quality. 10 yields highest\n"
138 " fidelity but large files).\n\n"
139 "encoder_example accepts only uncompressed RIFF WAV format audio and\n"
140 "YUV4MPEG2 uncompressed video.\n\n");
141 exit(1);
142 }
143
144 static void id_file(char *f){
145 FILE *test;
146 unsigned char buffer[80];
147 int ret;
148
149 /* open it, look for magic */
150
151 if(!strcmp(f,"-")){
152 /* stdin */
153 test=stdin;
154 }else{
155 test=fopen(f,"rb");
156 if(!test){
157 fprintf(stderr,"Unable to open file %s.\n",f);
158 exit(1);
159 }
160 }
161
162 ret=fread(buffer,1,4,test);
163 if(ret<4){
164 fprintf(stderr,"EOF determining file type of file %s.\n",f);
165 exit(1);
166 }
167
168 if(!memcmp(buffer,"RIFF",4)){
169 /* possible WAV file */
170
171 if(audio){
172 /* umm, we already have one */
173 fprintf(stderr,"Multiple RIFF WAVE files specified on command line.\n");
174 exit(1);
175 }
176
177 /* Parse the rest of the header */
178
179 ret=fread(buffer,1,4,test);
180 ret=fread(buffer,1,4,test);
181 if(ret<4)goto riff_err;
182 if(!memcmp(buffer,"WAVE",4)){
183
184 while(!feof(test)){
185 ret=fread(buffer,1,4,test);
186 if(ret<4)goto riff_err;
187 if(!memcmp("fmt",buffer,3)){
188
189 /* OK, this is our audio specs chunk. Slurp it up. */
190
191 ret=fread(buffer,1,20,test);
192 if(ret<20)goto riff_err;
193
194 if(memcmp(buffer+4,"\001\000",2)){
195 fprintf(stderr,"The WAV file %s is in a compressed format; "
196 "can't read it.\n",f);
197 exit(1);
198 }
199
200 audio=test;
201 audio_ch=buffer[6]+(buffer[7]<<8);
202 audio_hz=buffer[8]+(buffer[9]<<8)+
203 (buffer[10]<<16)+(buffer[11]<<24);
204
205 if(buffer[18]+(buffer[19]<<8)!=16){
206 fprintf(stderr,"Can only read 16 bit WAV files for now.\n");
207 exit(1);
208 }
209
210 /* Now, align things to the beginning of the data */
211 /* Look for 'dataxxxx' */
212 while(!feof(test)){
213 ret=fread(buffer,1,4,test);
214 if(ret<4)goto riff_err;
215 if(!memcmp("data",buffer,4)){
216 /* We're there. Ignore the declared size for now. */
217 ret=fread(buffer,1,4,test);
218 if(ret<4)goto riff_err;
219
220 fprintf(stderr,"File %s is 16 bit %d channel %d Hz RIFF WAV audio.\n",
221 f,audio_ch,audio_hz);
222
223 return;
224 }
225 }
226 }
227 }
228 }
229
230 fprintf(stderr,"Couldn't find WAVE data in RIFF file %s.\n",f);
231 exit(1);
232
233 }
234 if(!memcmp(buffer,"AVI2",4)){
235 /* possible AVI2VP31 format file */
236 /* read until newline, or 80 cols, whichever happens first */
237 int i;
238 for(i=0;i<79;i++){
239 ret=fread(buffer+i,1,1,test);
240 if(ret<1)goto yuv_err;
241 if(buffer[i]=='\n')break;
242 }
243 if(i==79){
244 fprintf(stderr,"Error parsing %s header; not a VP31 raw frames file?\n",f);
245 }
246 buffer[i]='\0';
247
248 if(!memcmp(buffer,"VP31",4)){
249 char interlace;
250
251 if(video){
252 /* umm, we already have one */
253 fprintf(stderr,"Multiple video files specified on command line.\n");
254 exit(1);
255 }
256
257 if(buffer[4]!='R'){
258 fprintf(stderr,"Incorrect file ; VP31 raw frames required.\n");
259 }
260
261 ret=sscanf(buffer,"VP31R W%d H%d F%d:%d I%c A%d:%d",
262 &frame_x,&frame_y,&video_hzn,&video_hzd,&interlace,
263 &video_an,&video_ad);
264 if(ret<7){
265 fprintf(stderr,"Error parsing AVI2VP31R header in file %s.\n",f);
266 exit(1);
267 }
268
269 if(interlace!='p'){
270 fprintf(stderr,"Input video is interlaced; Theora handles only progressive scan\n");
271 exit(1);
272 }
273
274 video=test;
275
276 fprintf(stderr,"File %s is %dx%d %.02f fps VP31 video.\n",
277 f,frame_x,frame_y,(double)video_hzn/video_hzd);
278
279 return;
280 }
281 }
282 fprintf(stderr,"Input file %s is neither a WAV nor VP31 file.\n",f);
283 exit(1);
284
285 riff_err:
286 fprintf(stderr,"EOF parsing RIFF file %s.\n",f);
287 exit(1);
288 yuv_err:
289 fprintf(stderr,"EOF parsing VP31 file %s.\n",f);
290 exit(1);
291
292 }
293
294 int spinner=0;
295 char *spinascii="|/-\\";
296 void spinnit(void){
297 spinner++;
298 if(spinner==4)spinner=0;
299 fprintf(stderr,"\r%c",spinascii[spinner]);
300 }
301
302 int fetch_and_process_audio(FILE *audio,ogg_page *audiopage,
303 ogg_stream_state *vo,
304 vorbis_dsp_state *vd,
305 vorbis_block *vb,
306 int audioflag){
307 ogg_packet op;
308 int i,j;
309
310 while(audio && !audioflag){
311 /* process any audio already buffered */
312 spinnit();
313 if(ogg_stream_pageout(vo,audiopage)>0) return 1;
314 if(ogg_stream_eos(vo))return 0;
315
316 {
317 /* read and process more audio */
318 signed char readbuffer[4096];
319 int toread=4096/2/audio_ch;
320 int bytesread=fread(readbuffer,1,toread*2*audio_ch,audio);
321 int sampread=bytesread/2/audio_ch;
322 float **vorbis_buffer;
323 int count=0;
324
325 if(bytesread<=0){
326 /* end of file. this can be done implicitly, but it's
327 easier to see here in non-clever fashion. Tell the
328 library we're at end of stream so that it can handle the
329 last frame and mark end of stream in the output properly */
330 vorbis_analysis_wrote(vd,0);
331 }else{
332 vorbis_buffer=vorbis_analysis_buffer(vd,sampread);
333 /* uninterleave samples */
334 for(i=0;i<sampread;i++){
335 for(j=0;j<audio_ch;j++){
336 vorbis_buffer[j][i]=((readbuffer[count+1]<<8)|
337 (0x00ff&(int)readbuffer[count]))/32768.f;
338 count+=2;
339 }
340 }
341
342 vorbis_analysis_wrote(vd,sampread);
343
344 }
345
346 while(vorbis_analysis_blockout(vd,vb)==1){
347
348 /* analysis, assume we want to use bitrate management */
349 vorbis_analysis(vb,NULL);
350 vorbis_bitrate_addblock(vb);
351
352 /* weld packets into the bitstream */
353 while(vorbis_bitrate_flushpacket(vd,&op))
354 ogg_stream_packetin(vo,&op);
355
356 }
357 }
358 }
359
360 return audioflag;
361 }
362
363 int theora_transcode_packetout( TC_INSTANCE *ttc, int last_p, ogg_packet *op){
364
365 long bytes=ttc->in_bytecount;
366
367 if(!bytes)return(0);
368
369 op->packet=ttc->in_bytes;
370 op->bytes=bytes;
371 op->b_o_s=0;
372 op->e_o_s=last_p;
373
374 op->packetno=ttc->CurrentFrame;
375 op->granulepos=ttc->granulepos;
376
377 return 1;
378 }
379
380 void TranscodeKeyFrame(TC_INSTANCE *ttc){
381 /* Keep track of the total number of Key Frames Coded */
382 ttc->KeyFrameCount += 1;
383 ttc->LastKeyFrame = 1;
384 }
385
386 void TranscodeFrame(TC_INSTANCE *ttc){
387 ttc->LastKeyFrame++;
388 }
389
390 void TranscodeFirstFrame(TC_INSTANCE *ttc){
391 /* Keep track of the total number of Key Frames Coded. */
392 ttc->KeyFrameCount = 1;
393 ttc->LastKeyFrame = 1;
394 }
395
396 int theora_transcode_bufferin( TC_INSTANCE *ttc, int isKeyFrame, char * bytes, int bytecount){
397
398 /*transcode: record keyframe flag*/
399 ttc->ThisIsKeyFrame = isKeyFrame;
400
401 /* Special case for first frame */
402 if ( ttc->ThisIsFirstFrame ){
403 ttc->ThisIsFirstFrame = 0;
404 ttc->ThisIsKeyFrame = 0;
405 } else if ( ttc->ThisIsKeyFrame ) {
406 TranscodeKeyFrame(ttc);
407 ttc->ThisIsKeyFrame = 0;
408 } else {
409 /* Compress the frame. */
410 TranscodeFrame( ttc );
411 }
412 /*need to pack info here*/
413 {
414
415 int frame_type;
416 long total_bits;
417 long total_words;
418 int frac_bits;
419
420 oggpackB_readinit(&ttc->opb_in,bytes,bytecount);
421 oggpackB_reset(&ttc->opb_out);
422
423 /*Mark as video frame.*/
424 oggpackB_write(&ttc->opb_out,0,1);
425 /*Copy frame type.*/
426 frame_type=oggpackB_read1(&ttc->opb_in);
427 oggpackB_write(&ttc->opb_out,frame_type,1);
428 /*Skip an unused bit in the VP32 header.*/
429 oggpackB_adv1(&ttc->opb_in);
430 /*Copy Q multiplier.*/
431 oggpackB_write(&ttc->opb_out,oggpackB_read(&ttc->opb_in,6),6);
432 /*VP3 has no per-block Q multipliers*/
433 oggpackB_write(&ttc->opb_out,0,1);
434 /*If the frame is a base/key/golden frame, copy a few extra bits.*/
435 if(frame_type==0){
436 /*These 13 bits are not included in a Theora frame header.
437 They were 0's and VP3 version info in VP32.*/
438 oggpackB_adv(&ttc->opb_in,13);
439 /*Copy the key frame type and the spare configuration bits.*/
440 oggpackB_write(&ttc->opb_out,oggpackB_read(&ttc->opb_in,3),3);
441 }
442
443 /*Copy the rest of the bits over.*/
444 total_bits=bytecount*8-oggpack_bits(&ttc->opb_in);
445 frac_bits=(int)(total_bits&31);
446 if(frac_bits){
447 oggpackB_write(&ttc->opb_out,oggpackB_read(&ttc->opb_in,frac_bits),
448 frac_bits);
449 }
450 total_words=total_bits>>5;
451 while(total_words-->0){
452 oggpackB_write(&ttc->opb_out,oggpackB_read(&ttc->opb_in,32),32);
453 }
454
455 ttc->in_bytecount = oggpackB_bytes(&ttc->opb_out);
456 ttc->in_bytes = oggpackB_get_buffer(&ttc->opb_out);
457 }
458
459 /* Update stats variables. */
460 ttc->CurrentFrame++;
461
462 ttc->granulepos=
463 ((ttc->CurrentFrame-ttc->LastKeyFrame-1)<<ttc->keyframe_granule_shift)+
464 ttc->LastKeyFrame-1;
465
466 return 0;
467 }
468
469 //static void _tp_writebuffer(oggpack_buffer *opb, const char *buf, const long len)
470
471 int theora_transcoder_init(theora_info * ti, TC_INSTANCE * ttc){
472 memset(ttc, 0, sizeof(*ttc));
473 ttc->granulepos = -1;
474 ttc->keyframe_granule_shift=_ilog(ti->keyframe_frequency_force-1);
475 ttc->LastKeyFrame = 0;
476 ttc->KeyFrameCount = 0;
477 ttc->ThisIsFirstFrame = 1;
478 ttc->ThisIsKeyFrame = 0;
479 ttc->CurrentFrame = 1;
480 ttc->in_bytes = 0;
481 ttc->in_bytecount = 0;
482 ttc->fps_denominator = ti->fps_denominator;
483 ttc->fps_numerator = ti->fps_numerator;
484 oggpackB_writeinit(&ttc->opb_out);
485 return 0;
486 }
487
488 int fetch_and_process_video(FILE *video,ogg_page *videopage,
489 ogg_stream_state *to,
490 TC_INSTANCE *ttc,
491 int videoflag){
492 /* You'll go to Hell for using static variables */
493 static int state=-1;
494 ogg_packet op;
495 int i;
496 int keyframeflag, framelength;
497
498
499 if(state==-1){
500 /* initialize the double frame buffer */
501 state=0;
502 }
503
504 /* is there a video page flushed? If not, work until there is. */
505 while(!videoflag){
506 spinnit();
507
508 if(ogg_stream_pageout(to,videopage)>0) return 1;
509 if(ogg_stream_eos(to)) return 0;
510
511 {
512 /* read and process more video */
513 /* video strategy reads one frame ahead so we know when we're
514 at end of stream and can mark last video frame as such
515 (vorbis audio has to flush one frame past last video frame
516 due to overlap and thus doesn't need this extra work */
517
518 /* have two frame buffers full (if possible) before
519 proceeding. after first pass and until eos, one will
520 always be full when we get here */
521
522 for(i=state;i<2;i++){
523 char c,frame[6];
524 int ret=fread(frame,1,6,video);
525
526 /* match and skip the frame header */
527 if(ret<6)break;
528 if(memcmp(frame,"FRAME",5)){
529 fprintf(stderr,"Loss of framing in VP31 input data\n");
530 exit(1);
531 }
532 if(frame[5]!='\n'){
533 int j;
534 for(j=0;j<79;j++)
535 if(fread(&c,1,1,video)&&c=='\n')break;
536 if(j==79){
537 fprintf(stderr,"Error parsing VP31 frame header\n");
538 exit(1);
539 }
540 }
541
542 /*read the length*/
543 ret=fread(&framelength, sizeof(int), 1, video);
544
545 /*read the keyframeflag*/
546 ret=fread(&keyframeflag, sizeof(int), 1, video);
547
548 vp3frame[i] = malloc(framelength);
549 framebytecount[i] = framelength;
550 frameiskey[i] = keyframeflag;
551
552 /* read the frame */
553 ret=fread((char *) vp3frame[i], sizeof(char), framelength, video);
554 if(ret!=framelength) break;
555
556 state++;
557 }
558
559 if(state<1){
560 /* can't get here unless VP31 stream has no video */
561 fprintf(stderr,"Video input contains no frames.\n");
562 exit(1);
563 }
564
565 /* Theora is a one-frame-in,one-frame-out system; submit a frame
566 for compression and pull out the packet */
567
568 //theora_encode_YUVin(td,&yuv);
569 theora_transcode_bufferin( ttc, frameiskey[0], vp3frame[0], framebytecount[0]);
570
571 /* if there's only one frame, it's the last in the stream */
572 if(state<2)
573 theora_transcode_packetout(ttc,1,&op);
574 else
575 theora_transcode_packetout(ttc,0,&op);
576
577 ogg_stream_packetin(to,&op);
578
579 {
580 signed char *temp=vp3frame[0];
581 vp3frame[0]=vp3frame[1];
582 vp3frame[1] = temp;
583 free(temp);
584
585 framebytecount[0]= framebytecount[1];
586 frameiskey[0] = frameiskey[1];
587 state--;
588 }
589 }
590 }
591 return videoflag;
592 }
593
594 /* returns, in seconds, absolute time of current packet in given
595 logical stream */
596 double transcode_granule_time(TC_INSTANCE *ttc,ogg_int64_t granulepos){
597 if(granulepos>=0){
598 ogg_int64_t iframe=granulepos>>ttc->keyframe_granule_shift;
599 ogg_int64_t pframe=granulepos-(iframe<<ttc->keyframe_granule_shift);
600
601 return (iframe+pframe)*
602 ((double)ttc->fps_denominator/ttc->fps_numerator);
603
604 }
605 return(-1);
606 }
607
608 int main(int argc,char *argv[]){
609 int c,long_option_index,ret;
610
611 ogg_stream_state to; /* take physical pages, weld into a logical
612 stream of packets */
613 ogg_stream_state vo; /* take physical pages, weld into a logical
614 stream of packets */
615 ogg_page og; /* one Ogg bitstream page. Vorbis packets are inside */
616 ogg_packet op; /* one raw packet of data for decode */
617
618 theora_state td;
619 theora_info ti;
620 theora_comment tc;
621
622 vorbis_info vi; /* struct that stores all the static vorbis bitstream
623 settings */
624 vorbis_comment vc; /* struct that stores all the user comments */
625
626 vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
627 vorbis_block vb; /* local working space for packet->PCM decode */
628
629 int audioflag=0;
630 int videoflag=0;
631 int akbps=0;
632 int vkbps=0;
633
634 ogg_int64_t audio_bytesout=0;
635 ogg_int64_t video_bytesout=0;
636 double timebase;
637
638 FILE* outfile = stdout;
639
640 TC_INSTANCE ttc;
641
642 #ifdef _WIN32 /* We need to set stdin/stdout to binary mode. Damn windows. */
643 /* if we were reading/writing a file, it would also need to in
644 binary mode, eg, fopen("file.wav","wb"); */
645 /* Beware the evil ifdef. We avoid these where we can, but this one we
646 cannot. Don't add any more, you'll probably go to hell if you do. */
647 _setmode( _fileno( stdin ), _O_BINARY );
648 _setmode( _fileno( stdout ), _O_BINARY );
649 #endif
650
651 while((c=getopt_long(argc,argv,optstring,options,&long_option_index))!=EOF){
652 switch(c){
653 case 'o':
654 outfile=fopen(optarg,"wb");
655 if(outfile==NULL){
656 fprintf(stderr,"Unable to open output file '%s'\n", optarg);
657 exit(1);
658 }
659 break;;
660
661 case 'a':
662 audio_q=atof(optarg)*.099;
663 if(audio_q<-.1 || audio_q>1){
664 fprintf(stderr,"Illegal audio quality (choose -1 through 10)\n");
665 exit(1);
666 }
667 audio_r=-1;
668 break;
669
670 case 'v':
671 video_q=rint(atof(optarg)*6.3);
672 if(video_q<0 || video_q>63){
673 fprintf(stderr,"Illegal video quality (choose 0 through 10)\n");
674 exit(1);
675 }
676 video_r=0;
677 break;
678
679 case 'A':
680 audio_r=atof(optarg)*1000;
681 if(audio_q<0){
682 fprintf(stderr,"Illegal audio quality (choose > 0 please)\n");
683 exit(1);
684 }
685 audio_q=-99;
686 break;
687
688 case 'V':
689 video_r=rint(atof(optarg)*1000);
690 if(video_r<45000 || video_r>2000000){
691 fprintf(stderr,"Illegal video bitrate (choose 45kbps through 2000kbps)\n");
692 exit(1);
693 }
694 video_q=0;
695 break;
696 default:
697 usage();
698 }
699 }
700
701 while(optind<argc){
702 /* assume that anything following the options must be a filename */
703 id_file(argv[optind]);
704 optind++;
705 }
706
707 /* yayness. Set up Ogg output stream */
708 srand(time(NULL));
709 ogg_stream_init(&vo,rand());
710 ogg_stream_init(&to,rand()); /* oops, add one to the above */
711
712 /* Set up Theora encoder */
713 if(!video){
714 fprintf(stderr,"No video files submitted for compression?\n");
715 exit(1);
716 }
717 /* Theora has a divisible-by-sixteen restriction for the encoded video size */
718 /* scale the frame size up to the nearest /16 and calculate offsets */
719 video_x=((frame_x + 15) >>4)<<4;
720 video_y=((frame_y + 15) >>4)<<4;
721 frame_x_offset=(video_x-frame_x)/2;
722 frame_y_offset=(video_y-frame_y)/2;
723
724 theora_info_init(&ti);
725 ti.width=video_x;
726 ti.height=video_y;
727 ti.frame_width=frame_x;
728 ti.frame_height=frame_y;
729 ti.offset_x=frame_x_offset;
730 ti.offset_y=frame_y_offset;
731 ti.fps_numerator=video_hzn;
732 ti.fps_denominator=video_hzd;
733 ti.aspect_numerator=video_an;
734 ti.aspect_denominator=video_ad;
735 ti.colorspace=OC_CS_UNSPECIFIED;
736 ti.target_bitrate=video_r;
737 ti.quality=video_q;
738
739 ti.dropframes_p=0;
740 ti.quick_p=1;
741 ti.keyframe_auto_p=1;
742 ti.keyframe_frequency=32768;
743 ti.keyframe_frequency_force=32768;
744 ti.keyframe_data_target_bitrate=video_r*1.5;
745 ti.keyframe_auto_threshold=80;
746 ti.keyframe_mindistance=8;
747 ti.noise_sensitivity=1;
748
749 theora_encode_init(&td,&ti);
750 theora_transcoder_init(&ti, &ttc);
751 theora_info_clear(&ti);
752
753 /* initialize Vorbis too, assuming we have audio to compress. */
754 if(audio){
755 vorbis_info_init(&vi);
756 if(audio_q>-99)
757 ret = vorbis_encode_init_vbr(&vi,audio_ch,audio_hz,audio_q);
758 else
759 ret = vorbis_encode_init(&vi,audio_ch,audio_hz,-1,audio_r,-1);
760 if(ret){
761 fprintf(stderr,"The Vorbis encoder could not set up a mode according to\n"
762 "the requested quality or bitrate.\n\n");
763 exit(1);
764 }
765
766 vorbis_comment_init(&vc);
767 vorbis_analysis_init(&vd,&vi);
768 vorbis_block_init(&vd,&vb);
769 }
770
771 /* write the bitstream header packets with proper page interleave */
772
773 /* first packet will get its own page automatically */
774 theora_encode_header(&td,&op);
775 ogg_stream_packetin(&to,&op);
776 if(ogg_stream_pageout(&to,&og)!=1){
777 fprintf(stderr,"Internal Ogg library error.\n");
778 exit(1);
779 }
780 fwrite(og.header,1,og.header_len,outfile);
781 fwrite(og.body,1,og.body_len,outfile);
782
783 /* create the remaining theora headers */
784 theora_comment_init(&tc);
785 theora_encode_comment(&tc,&op);
786 ogg_stream_packetin(&to,&op);
787 theora_encode_tables(&td,&op);
788 ogg_stream_packetin(&to,&op);
789
790 if(audio){
791 /* vorbis streams start with three header packets */
792 ogg_packet id;
793 ogg_packet comment;
794 ogg_packet code;
795
796 if(vorbis_analysis_headerout(&vd,&vc,&id,&comment,&code)<0){
797 fprint(stderr,"Internal Vorbis library error.\n");
798 exit(1);
799 }
800 /* id header is automatically placed in its own page */
801 ogg_stream_packetin(&vo,&id);
802 if(ogg_stream_pageout(&vo,&og)!=1){
803 fprintf(stderr,"Internal Ogg library error.\n");
804 exit(1);
805 }
806 fwrite(og.header,1,og.header_len,outfile);
807 fwrite(og.body,1,og.body_len,outfile);
808
809 /* append remaining vorbis header packets */
810 ogg_stream_packetin(&vo,&comment);
811 ogg_stream_packetin(&vo,&code);
812 }
813
814 /* Flush the rest of our headers. This ensures
815 the actual data in each stream will start
816 on a new page, as per spec. */
817 while(1){
818 int result = ogg_stream_flush(&to,&og);
819 if(result<0){
820 /* can't get here */
821 fprintf(stderr,"Internal Ogg library error.\n");
822 exit(1);
823 }
824 if(result==0)break;
825 fwrite(og.header,1,og.header_len,outfile);
826 fwrite(og.body,1,og.body_len,outfile);
827 }
828 if(audio){
829 while(1){
830 int result=ogg_stream_flush(&vo,&og);
831 if(result<0){
832 /* can't get here */
833 fprintf(stderr,"Internal Ogg library error.\n");
834 exit(1);
835 }
836 if(result==0)break;
837 fwrite(og.header,1,og.header_len,outfile);
838 fwrite(og.body,1,og.body_len,outfile);
839 }
840 }
841
842 /* setup complete. Raw processing loop */
843 fprintf(stderr,"Compressing....\n");
844 while(1){
845
846
847 /* is there an audio page flushed? If not, fetch one if possible */
848 audioflag=fetch_and_process_audio(audio,&audiopage,&vo,&vd,&vb,audioflag);
849
850 /* is there a video page flushed? If not, fetch one if possible */
851 videoflag=fetch_and_process_video(video,&videopage,&to,&ttc,videoflag);
852
853 /* no pages of either? Must be end of stream. */
854 if(!audioflag && !videoflag)break;
855
856 /* which is earlier; the end of the audio page or the end of the
857 video page? Flush the earlier to stream */
858 {
859 int audio_or_video=-1;
860 double audiotime=
861 audioflag?vorbis_granule_time(&vd,ogg_page_granulepos(&audiopage)):-1;
862 double videotime=
863 videoflag?transcode_granule_time(&ttc,ogg_page_granulepos(&videopage)):-1;
864
865 if(!audioflag){
866 audio_or_video=1;
867 } else if(!videoflag) {
868 audio_or_video=0;
869 } else {
870 if(audiotime<videotime)
871 audio_or_video=0;
872 else
873 audio_or_video=1;
874 }
875
876 if(audio_or_video==1){
877 /* flush a video page */
878 video_bytesout+=fwrite(videopage.header,1,videopage.header_len,outfile);
879 video_bytesout+=fwrite(videopage.body,1,videopage.body_len,outfile);
880 videoflag=0;
881 timebase=videotime;
882
883 }else{
884 /* flush an audio page */
885 audio_bytesout+=fwrite(audiopage.header,1,audiopage.header_len,outfile);
886 audio_bytesout+=fwrite(audiopage.body,1,audiopage.body_len,outfile);
887 audioflag=0;
888 timebase=audiotime;
889 }
890 {
891 int hundredths=timebase*100-(long)timebase*100;
892 int seconds=(long)timebase%60;
893 int minutes=((long)timebase/60)%60;
894 int hours=(long)timebase/3600;
895
896 if(audio_or_video)
897 vkbps=rint(video_bytesout*8./timebase*.001);
898 else
899 akbps=rint(audio_bytesout*8./timebase*.001);
900
901 fprintf(stderr,
902 "\n %d:%02d:%02d.%02d audio: %dkbps video: %dkbps ",
903 hours,minutes,seconds,hundredths,akbps,vkbps);
904 }
905 }
906
907 }
908
909 /* clear out state */
910
911 if(audio){
912 ogg_stream_clear(&vo);
913 vorbis_block_clear(&vb);
914 vorbis_dsp_clear(&vd);
915 vorbis_comment_clear(&vc);
916 vorbis_info_clear(&vi);
917 }
918 if(video){
919 ogg_stream_clear(&to);
920 theora_clear(&td);
921 }
922
923 if(outfile && outfile!=stdout)fclose(outfile);
924
925 fprintf(stderr,"\r \ndone.\n\n");
926
927 return(0);
928
929 }