S32 encode_vorbis_file(const std::string& in_fname, const std::string& out_fname) { #define READ_BUFFER 1024 unsigned char readbuffer[READ_BUFFER*4+44]; /* out of the data segment, not the stack */ /*Flawfinder: ignore*/ ogg_stream_state os; /* take physical pages, weld into a logical stream of packets */ ogg_page og; /* one Ogg bitstream page. Vorbis packets are inside */ ogg_packet op; /* one raw packet of data for decode */ vorbis_info vi; /* struct that stores all the static vorbis bitstream settings */ vorbis_comment vc; /* struct that stores all the user comments */ vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */ vorbis_block vb; /* local working space for packet->PCM decode */ int eos=0; int result; U16 num_channels = 0; U32 sample_rate = 0; U32 bits_per_sample = 0; S32 format_error = 0; std::string error_msg; if ((format_error = check_for_invalid_wav_formats(in_fname, error_msg))) { llwarns << error_msg << ": " << in_fname << llendl; return(format_error); } #if 1 unsigned char wav_header[44]; /*Flawfinder: ignore*/ S32 data_left = 0; LLAPRFile infile ; infile.open(in_fname,LL_APR_RB, LLAPRFile::global); if (!infile.getFileHandle()) { llwarns << "Couldn't open temporary ogg file for writing: " << in_fname << llendl; return(LLVORBISENC_SOURCE_OPEN_ERR); } LLAPRFile outfile ; outfile.open(out_fname,LL_APR_WPB, LLAPRFile::global); if (!outfile.getFileHandle()) { llwarns << "Couldn't open upload sound file for reading: " << in_fname << llendl; return(LLVORBISENC_DEST_OPEN_ERR); } // parse the chunks U32 chunk_length = 0; U32 file_pos = 12; // start at the first chunk (usually fmt but not always) while (infile.eof() != APR_EOF) { infile.seek(APR_SET,file_pos); infile.read(wav_header, 44); chunk_length = ((U32) wav_header[7] << 24) + ((U32) wav_header[6] << 16) + ((U32) wav_header[5] << 8) + wav_header[4]; // llinfos << "chunk found: '" << wav_header[0] << wav_header[1] << wav_header[2] << wav_header[3] << "'" << llendl; if (!(strncmp((char *)&(wav_header[0]),"fmt ",4))) { num_channels = ((U16) wav_header[11] << 8) + wav_header[10]; sample_rate = ((U32) wav_header[15] << 24) + ((U32) wav_header[14] << 16) + ((U32) wav_header[13] << 8) + wav_header[12]; bits_per_sample = ((U16) wav_header[23] << 8) + wav_header[22]; } else if (!(strncmp((char *)&(wav_header[0]),"data",4))) { infile.seek(APR_SET,file_pos+8); // leave the file pointer at the beginning of the data chunk data data_left = chunk_length; break; } file_pos += (chunk_length + 8); chunk_length = 0; } /********** Encode setup ************/ /* choose an encoding mode */ /* (mode 0: 44kHz stereo uncoupled, roughly 128kbps VBR) */ vorbis_info_init(&vi); // always encode to mono // SL-52913 & SL-53779 determined this quality level to be our 'good // enough' general-purpose quality level with a nice low bitrate. // Equivalent to oggenc -q0.5 F32 quality = 0.05f; // quality = (bitrate==128000 ? 0.4f : 0.1); // if (vorbis_encode_init(&vi, /* num_channels */ 1 ,sample_rate, -1, bitrate, -1)) if (vorbis_encode_init_vbr(&vi, /* num_channels */ 1 ,sample_rate, quality)) // if (vorbis_encode_setup_managed(&vi,1,sample_rate,-1,bitrate,-1) || // vorbis_encode_ctl(&vi,OV_ECTL_RATEMANAGE_AVG,NULL) || // vorbis_encode_setup_init(&vi)) { llwarns << "unable to initialize vorbis codec at quality " << quality << llendl; // llwarns << "unable to initialize vorbis codec at bitrate " << bitrate << llendl; return(LLVORBISENC_DEST_OPEN_ERR); } /* add a comment */ vorbis_comment_init(&vc); // vorbis_comment_add(&vc,"Linden"); /* set up the analysis state and auxiliary encoding storage */ vorbis_analysis_init(&vd,&vi); vorbis_block_init(&vd,&vb); /* set up our packet->stream encoder */ /* pick a random serial number; that way we can more likely build chained streams just by concatenation */ ogg_stream_init(&os, ll_rand()); /* Vorbis streams begin with three headers; the initial header (with most of the codec setup parameters) which is mandated by the Ogg bitstream spec. The second header holds any comment fields. The third header holds the bitstream codebook. We merely need to make the headers, then pass them to libvorbis one at a time; libvorbis handles the additional Ogg bitstream constraints */ { ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout(&vd,&vc,&header,&header_comm,&header_code); ogg_stream_packetin(&os,&header); /* automatically placed in its own page */ ogg_stream_packetin(&os,&header_comm); ogg_stream_packetin(&os,&header_code); /* We don't have to write out here, but doing so makes streaming * much easier, so we do, flushing ALL pages. This ensures the actual * audio data will start on a new page */ while(!eos){ int result=ogg_stream_flush(&os,&og); if(result==0)break; outfile.write(og.header, og.header_len); outfile.write(og.body, og.body_len); } } while(!eos) { long bytes_per_sample = bits_per_sample/8; long bytes=(long)infile.read(readbuffer,llclamp((S32)(READ_BUFFER*num_channels*bytes_per_sample),0,data_left)); /* stereo hardwired here */ if (bytes==0) { /* end of file. this can be done implicitly in the mainline, but it's easier to see here in non-clever fashion. Tell the library we're at end of stream so that it can handle the last frame and mark end of stream in the output properly */ vorbis_analysis_wrote(&vd,0); // eos = 1; } else { long i; long samples; int temp; data_left -= bytes; /* data to encode */ /* expose the buffer to submit data */ float **buffer=vorbis_analysis_buffer(&vd,READ_BUFFER); i = 0; samples = bytes / (num_channels * bytes_per_sample); if (num_channels == 2) { if (bytes_per_sample == 2) { /* uninterleave samples */ for(i=0; i<samples ;i++) { temp = ((signed char *)readbuffer)[i*4+1]; /*Flawfinder: ignore*/ temp += ((signed char *)readbuffer)[i*4+3]; /*Flawfinder: ignore*/ temp <<= 8; temp += readbuffer[i*4]; temp += readbuffer[i*4+2]; buffer[0][i] = ((float)temp) / 65536.f; } } else // presume it's 1 byte per which is unsigned (F#@%ing wav "standard") { /* uninterleave samples */ for(i=0; i<samples ;i++) { temp = readbuffer[i*2+0]; temp += readbuffer[i*2+1]; temp -= 256; buffer[0][i] = ((float)temp) / 256.f; } } } else if (num_channels == 1) { if (bytes_per_sample == 2) { for(i=0; i < samples ;i++) { temp = ((signed char*)readbuffer)[i*2+1]; temp <<= 8; temp += readbuffer[i*2]; buffer[0][i] = ((float)temp) / 32768.f; } } else // presume it's 1 byte per which is unsigned (F#@%ing wav "standard") { for(i=0; i < samples ;i++) { temp = readbuffer[i]; temp -= 128; buffer[0][i] = ((float)temp) / 128.f; } } } /* tell the library how much we actually submitted */ vorbis_analysis_wrote(&vd,i); } /* vorbis does some data preanalysis, then divvies up blocks for more involved (potentially parallel) processing. Get a single block for encoding now */ while(vorbis_analysis_blockout(&vd,&vb)==1) { /* analysis */ /* Do the main analysis, creating a packet */ vorbis_analysis(&vb, NULL); vorbis_bitrate_addblock(&vb); while(vorbis_bitrate_flushpacket(&vd, &op)) { /* weld the packet into the bitstream */ ogg_stream_packetin(&os,&op); /* write out pages (if any) */ while(!eos) { result = ogg_stream_pageout(&os,&og); if(result==0) break; outfile.write(og.header, og.header_len); outfile.write(og.body, og.body_len); /* this could be set above, but for illustrative purposes, I do it here (to show that vorbis does know where the stream ends) */ if(ogg_page_eos(&og)) eos=1; } } } } /* clean up and exit. vorbis_info_clear() must be called last */ ogg_stream_clear(&os); vorbis_block_clear(&vb); vorbis_dsp_clear(&vd); vorbis_comment_clear(&vc); vorbis_info_clear(&vi); /* ogg_page and ogg_packet structs always point to storage in libvorbis. They're never freed or manipulated directly */ // fprintf(stderr,"Vorbis encoding: Done.\n"); llinfos << "Vorbis encoding: Done." << llendl; #endif return(LLVORBISENC_NOERR); }
static int encode(quicktime_t *file, int16_t **input_i, float **input_f, int track, long samples) { int result = 0; int64_t offset = quicktime_position(file); quicktime_audio_map_t *track_map = &(file->atracks[track]); quicktime_trak_t *trak = track_map->track; quicktime_vorbis_codec_t *codec = ((quicktime_codec_t*)track_map->codec)->priv; int samplerate = trak->mdia.minf.stbl.stsd.table[0].sample_rate; float **output; int size = 0; int chunk_started = 0; quicktime_atom_t chunk_atom; if(samplerate < 32000) { printf("encode: sample rate %d not supported.\n", samplerate); return 1; } if(!codec->encode_initialized) { ogg_packet header; ogg_packet header_comm; ogg_packet header_code; codec->encode_initialized = 1; if(file->use_avi) trak->mdia.minf.stbl.stsd.table[0].sample_size = 0; vorbis_info_init(&codec->enc_vi); if(codec->use_vbr) { result = vorbis_encode_setup_managed(&codec->enc_vi, track_map->channels, samplerate, codec->max_bitrate, codec->nominal_bitrate, codec->min_bitrate); result |= vorbis_encode_ctl(&codec->enc_vi, OV_ECTL_RATEMANAGE_AVG, NULL); result |= vorbis_encode_setup_init(&codec->enc_vi); } else { vorbis_encode_init(&codec->enc_vi, track_map->channels, samplerate, codec->max_bitrate, codec->nominal_bitrate, codec->min_bitrate); } vorbis_comment_init(&codec->enc_vc); vorbis_analysis_init(&codec->enc_vd, &codec->enc_vi); vorbis_block_init(&codec->enc_vd, &codec->enc_vb); srand(time(NULL)); ogg_stream_init(&codec->enc_os, rand()); vorbis_analysis_headerout(&codec->enc_vd, &codec->enc_vc, &header, &header_comm, &header_code); ogg_stream_packetin(&codec->enc_os, &header); ogg_stream_packetin(&codec->enc_os, &header_comm); ogg_stream_packetin(&codec->enc_os, &header_code); FLUSH_OGG1 }
HOTSPOT PUBLIC SW32 vorbis_encode( const char *filename, void *data, W32 size, W32 in_channels, W32 in_samplesize, W32 rate, W32 quality, W32 max_bitrate, W32 min_bitrate ) { FILE *fp; ogg_stream_state os; ogg_page og; ogg_packet op; vorbis_dsp_state vd; vorbis_block vb; vorbis_info vi; ogg_packet header_main; ogg_packet header_comments; ogg_packet header_codebooks; SW32 result; W32 serialno = 0; vorbis_comment comments; SW32 ret = 0; SW32 eos; W32 samplesdone = 0; W32 packetsdone = 0; W32 bytes_written = 0; fp = fopen( filename, "wb" ); if( fp == NULL ) { return 0; } memset( &comments, 0, sizeof( comments ) ); channels = in_channels; samplesize = in_samplesize; ptrCurrent = (PW8)data; ptrEnd = (PW8)data + size; vorbis_info_init( &vi ); if( vorbis_encode_setup_vbr( &vi, channels, rate, quality ) ) { fprintf( stderr, "Mode initialisation failed: invalid parameters for quality\n" ); vorbis_info_clear( &vi ); // Añadido como consejo de cppcheck. fclose(fp); return 1; } /* do we have optional hard quality restrictions? */ if( max_bitrate > 0 || min_bitrate > 0 ) { struct ovectl_ratemanage_arg ai; vorbis_encode_ctl( &vi, OV_ECTL_RATEMANAGE_GET, &ai ); ai.bitrate_hard_min = min_bitrate; ai.bitrate_hard_max = max_bitrate; ai.management_active = 1; vorbis_encode_ctl( &vi, OV_ECTL_RATEMANAGE_SET, &ai ); } /* Turn off management entirely (if it was turned on). */ vorbis_encode_ctl( &vi, OV_ECTL_RATEMANAGE_SET, NULL ); vorbis_encode_setup_init( &vi ); vorbis_analysis_init( &vd, &vi ); vorbis_block_init( &vd, &vb ); ogg_stream_init( &os, serialno ); /* Now, build the three header packets and send through to the stream output stage (but defer actual file output until the main encode loop) */ /* Build the packets */ ret = vorbis_analysis_headerout( &vd, &comments, &header_main, &header_comments, &header_codebooks ); /* And stream them out */ ogg_stream_packetin( &os, &header_main ); ogg_stream_packetin( &os, &header_comments ); ogg_stream_packetin( &os, &header_codebooks ); while( (result = ogg_stream_flush( &os, &og )) ) { ret = fwrite( og.header, 1, og.header_len, fp ); ret += fwrite( og.body, 1, og.body_len, fp ); if(ret != og.header_len + og.body_len) { fprintf( stderr, "[vorbis_encode]: Failed writing header to output stream\n") ; ret = 1; goto cleanup; /* Bail and try to clean up stuff */ } } eos = 0; /* Main encode loop - continue until end of file */ while( ! eos ) { float **buffer = vorbis_analysis_buffer( &vd, READSIZE ); SW32 samples_read = read_samples( buffer, READSIZE ); if( samples_read == 0 ) { /* Tell the library that we wrote 0 bytes - signalling the end */ vorbis_analysis_wrote( &vd, 0 ); } else { samplesdone += samples_read; /* Call progress update every 40 pages */ if( packetsdone >= 40 ) { packetsdone = 0; // progress bar here } /* Tell the library how many samples (per channel) we wrote into the supplied buffer */ vorbis_analysis_wrote( &vd, samples_read ); } /* While we can get enough data from the library to analyse, one block at a time... */ while( vorbis_analysis_blockout( &vd, &vb ) == 1 ) { /* Do the main analysis, creating a packet */ vorbis_analysis( &vb, NULL ); vorbis_bitrate_addblock( &vb ); while( vorbis_bitrate_flushpacket( &vd, &op ) ) { /* Add packet to bitstream */ ogg_stream_packetin( &os, &op ); packetsdone++; /* If we've gone over a page boundary, we can do actual output, so do so (for however many pages are available) */ while( ! eos ) { SW32 result = ogg_stream_pageout( &os, &og ); if( ! result ) { break; } ret = fwrite( og.header, 1, og.header_len, fp ); ret += fwrite( og.body, 1, og.body_len, fp ); if(ret != og.header_len + og.body_len) { fprintf( stderr, "[vorbis_encode]: Failed writing data to output stream\n" ); ret = 1; goto cleanup; /* Bail */ } else { bytes_written += ret; } if( ogg_page_eos( &og ) ) { eos = 1; } } } } } cleanup: fclose( fp ); ogg_stream_clear( &os ); vorbis_block_clear( &vb ); vorbis_dsp_clear( &vd ); vorbis_info_clear( &vi ); return 0; }
int main(int argc,char *argv[]){ int c,long_option_index,ret; ogg_stream_state to; /* take physical pages, weld into a logical stream of packets */ ogg_stream_state vo; /* take physical pages, weld into a logical stream of packets */ ogg_page og; /* one Ogg bitstream page. Vorbis packets are inside */ ogg_packet op; /* one raw packet of data for decode */ theora_state td; theora_info ti; theora_comment tc; vorbis_info vi; /* struct that stores all the static vorbis bitstream settings */ vorbis_comment vc; /* struct that stores all the user comments */ vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */ vorbis_block vb; /* local working space for packet->PCM decode */ int audioflag=0; int videoflag=0; int akbps=0; int vkbps=0; ogg_int64_t audio_bytesout=0; ogg_int64_t video_bytesout=0; double timebase; FILE* outfile = stdout; #ifdef _WIN32 # ifdef THEORA_PERF_DATA LARGE_INTEGER start_time; LARGE_INTEGER final_time; LONGLONG elapsed_ticks; LARGE_INTEGER ticks_per_second; LONGLONG elapsed_secs; LONGLONG elapsed_sec_mod; double elapsed_secs_dbl ; # endif /* We need to set stdin/stdout to binary mode. Damn windows. */ /* if we were reading/writing a file, it would also need to in binary mode, eg, fopen("file.wav","wb"); */ /* Beware the evil ifdef. We avoid these where we can, but this one we cannot. Don't add any more, you'll probably go to hell if you do. */ _setmode( _fileno( stdin ), _O_BINARY ); _setmode( _fileno( stdout ), _O_BINARY ); #endif while((c=getopt_long(argc,argv,optstring,options,&long_option_index))!=EOF){ switch(c){ case 'o': outfile=fopen(optarg,"wb"); if(outfile==NULL){ fprintf(stderr,"Unable to open output file '%s'\n", optarg); exit(1); } break;; case 'a': audio_q=atof(optarg)*.099; if(audio_q<-.1 || audio_q>1){ fprintf(stderr,"Illegal audio quality (choose -1 through 10)\n"); exit(1); } audio_r=-1; break; case 'v': video_q=rint(atof(optarg)*6.3); if(video_q<0 || video_q>63){ fprintf(stderr,"Illegal video quality (choose 0 through 10)\n"); exit(1); } video_r=0; break; case 'A': audio_r=atof(optarg)*1000; if(audio_q<0){ fprintf(stderr,"Illegal audio quality (choose > 0 please)\n"); exit(1); } audio_q=-99; break; case 'V': video_r=rint(atof(optarg)*1000); if(video_r<45000 || video_r>2000000){ fprintf(stderr,"Illegal video bitrate (choose 45kbps through 2000kbps)\n"); exit(1); } video_q=0; break; case 's': video_an=rint(atof(optarg)); break; case 'S': video_ad=rint(atof(optarg)); break; case 'f': video_hzn=rint(atof(optarg)); break; case 'F': video_hzd=rint(atof(optarg)); break; default: usage(); } } while(optind<argc){ /* assume that anything following the options must be a filename */ id_file(argv[optind]); optind++; } #ifdef THEORA_PERF_DATA # ifdef WIN32 QueryPerformanceCounter(&start_time); # endif #endif /* yayness. Set up Ogg output stream */ srand(time(NULL)); { /* need two inequal serial numbers */ int serial1, serial2; serial1 = rand(); serial2 = rand(); if (serial1 == serial2) serial2++; ogg_stream_init(&to,serial1); ogg_stream_init(&vo,serial2); } /* Set up Theora encoder */ if(!video){ fprintf(stderr,"No video files submitted for compression?\n"); exit(1); } /* Theora has a divisible-by-sixteen restriction for the encoded video size */ /* scale the frame size up to the nearest /16 and calculate offsets */ video_x=((frame_x + 15) >>4)<<4; video_y=((frame_y + 15) >>4)<<4; /* We force the offset to be even. This ensures that the chroma samples align properly with the luma samples. */ frame_x_offset=((video_x-frame_x)/2)&~1; frame_y_offset=((video_y-frame_y)/2)&~1; theora_info_init(&ti); ti.width=video_x; ti.height=video_y; ti.frame_width=frame_x; ti.frame_height=frame_y; ti.offset_x=frame_x_offset; ti.offset_y=frame_y_offset; ti.fps_numerator=video_hzn; ti.fps_denominator=video_hzd; ti.aspect_numerator=video_an; ti.aspect_denominator=video_ad; ti.colorspace=OC_CS_UNSPECIFIED; ti.pixelformat=OC_PF_420; ti.target_bitrate=video_r; ti.quality=video_q; ti.dropframes_p=0; ti.quick_p=1; ti.keyframe_auto_p=1; ti.keyframe_frequency=64; ti.keyframe_frequency_force=64; ti.keyframe_data_target_bitrate=video_r*1.5; ti.keyframe_auto_threshold=80; ti.keyframe_mindistance=8; ti.noise_sensitivity=1; theora_encode_init(&td,&ti); theora_info_clear(&ti); /* initialize Vorbis too, assuming we have audio to compress. */ if(audio){ vorbis_info_init(&vi); if(audio_q>-99) ret = vorbis_encode_init_vbr(&vi,audio_ch,audio_hz,audio_q); else ret = vorbis_encode_init(&vi,audio_ch,audio_hz,-1,audio_r,-1); if(ret){ fprintf(stderr,"The Vorbis encoder could not set up a mode according to\n" "the requested quality or bitrate.\n\n"); exit(1); } vorbis_comment_init(&vc); vorbis_analysis_init(&vd,&vi); vorbis_block_init(&vd,&vb); } /* write the bitstream header packets with proper page interleave */ /* first packet will get its own page automatically */ theora_encode_header(&td,&op); ogg_stream_packetin(&to,&op); if(ogg_stream_pageout(&to,&og)!=1){ fprintf(stderr,"Internal Ogg library error.\n"); exit(1); } fwrite(og.header,1,og.header_len,outfile); fwrite(og.body,1,og.body_len,outfile); /* create the remaining theora headers */ theora_comment_init(&tc); theora_encode_comment(&tc,&op); ogg_stream_packetin(&to,&op); /*theora_encode_comment() doesn't take a theora_state parameter, so it has to allocate its own buffer to pass back the packet data. If we don't free it here, we'll leak. libogg2 makes this much cleaner: the stream owns the buffer after you call packetin in libogg2, but this is not true in libogg1.*/ free(op.packet); theora_encode_tables(&td,&op); ogg_stream_packetin(&to,&op); if(audio){ ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout(&vd,&vc,&header,&header_comm,&header_code); ogg_stream_packetin(&vo,&header); /* automatically placed in its own page */ if(ogg_stream_pageout(&vo,&og)!=1){ fprintf(stderr,"Internal Ogg library error.\n"); exit(1); } fwrite(og.header,1,og.header_len,outfile); fwrite(og.body,1,og.body_len,outfile); /* remaining vorbis header packets */ ogg_stream_packetin(&vo,&header_comm); ogg_stream_packetin(&vo,&header_code); } /* Flush the rest of our headers. This ensures the actual data in each stream will start on a new page, as per spec. */ while(1){ int result = ogg_stream_flush(&to,&og); if(result<0){ /* can't get here */ fprintf(stderr,"Internal Ogg library error.\n"); exit(1); } if(result==0)break; fwrite(og.header,1,og.header_len,outfile); fwrite(og.body,1,og.body_len,outfile); } if(audio){ while(1){ int result=ogg_stream_flush(&vo,&og); if(result<0){ /* can't get here */ fprintf(stderr,"Internal Ogg library error.\n"); exit(1); } if(result==0)break; fwrite(og.header,1,og.header_len,outfile); fwrite(og.body,1,og.body_len,outfile); } } /* setup complete. Raw processing loop */ fprintf(stderr,"Compressing....\n"); while(1){ ogg_page audiopage; ogg_page videopage; /* is there an audio page flushed? If not, fetch one if possible */ audioflag=fetch_and_process_audio(audio,&audiopage,&vo,&vd,&vb,audioflag); /* is there a video page flushed? If not, fetch one if possible */ videoflag=fetch_and_process_video(video,&videopage,&to,&td,videoflag); /* no pages of either? Must be end of stream. */ if(!audioflag && !videoflag)break; /* which is earlier; the end of the audio page or the end of the video page? Flush the earlier to stream */ { int audio_or_video=-1; double audiotime= audioflag?vorbis_granule_time(&vd,ogg_page_granulepos(&audiopage)):-1; double videotime= videoflag?theora_granule_time(&td,ogg_page_granulepos(&videopage)):-1; if(!audioflag){ audio_or_video=1; } else if(!videoflag) { audio_or_video=0; } else { if(audiotime<videotime) audio_or_video=0; else audio_or_video=1; } if(audio_or_video==1){ /* flush a video page */ video_bytesout+=fwrite(videopage.header,1,videopage.header_len,outfile); video_bytesout+=fwrite(videopage.body,1,videopage.body_len,outfile); videoflag=0; timebase=videotime; }else{ /* flush an audio page */ audio_bytesout+=fwrite(audiopage.header,1,audiopage.header_len,outfile); audio_bytesout+=fwrite(audiopage.body,1,audiopage.body_len,outfile); audioflag=0; timebase=audiotime; } { int hundredths=timebase*100-(long)timebase*100; int seconds=(long)timebase%60; int minutes=((long)timebase/60)%60; int hours=(long)timebase/3600; if(audio_or_video) vkbps=rint(video_bytesout*8./timebase*.001); else akbps=rint(audio_bytesout*8./timebase*.001); fprintf(stderr, "\r %d:%02d:%02d.%02d audio: %dkbps video: %dkbps ", hours,minutes,seconds,hundredths,akbps,vkbps); } } } /* clear out state */ if(audio){ ogg_stream_clear(&vo); vorbis_block_clear(&vb); vorbis_dsp_clear(&vd); vorbis_comment_clear(&vc); vorbis_info_clear(&vi); } if(video){ ogg_stream_clear(&to); theora_clear(&td); } if(outfile && outfile!=stdout)fclose(outfile); fprintf(stderr,"\r \ndone.\n\n"); #ifdef THEORA_PERF_DATA # ifdef WIN32 QueryPerformanceCounter(&final_time); elapsed_ticks = final_time.QuadPart - start_time.QuadPart; ticks_per_second; QueryPerformanceFrequency(&ticks_per_second); elapsed_secs = elapsed_ticks / ticks_per_second.QuadPart; elapsed_sec_mod = elapsed_ticks % ticks_per_second.QuadPart; elapsed_secs_dbl = elapsed_secs; elapsed_secs_dbl += ((double)elapsed_sec_mod / (double)ticks_per_second.QuadPart); printf("Encode time = %lld ticks\n", elapsed_ticks); printf("~%lld and %lld / %lld seconds\n", elapsed_secs, elapsed_sec_mod, ticks_per_second.QuadPart); printf("~%Lf seconds\n", elapsed_secs_dbl); # endif #endif return(0); }
int FileVorbis::open_file(int rd, int wr) { int result = 0; //printf("FileVorbis::open_file 1\n"); if(rd) { //printf("FileVorbis::open_file 1\n"); if(!(fd = fopen(asset->path, "rb"))) { eprintf("FileVorbis::open_file %s: %s\n", asset->path, strerror(errno)); result = 1; } else { //printf("FileVorbis::open_file 2 %p %p\n", fd, vf); if(ov_open(fd, &vf, NULL, 0) < 0) { eprintf(_("FileVorbis::open_file %s: invalid bitstream.\n"), asset->path); result = 1; } else { //printf("FileVorbis::open_file 1\n"); vorbis_info *vi = ov_info(&vf, -1); asset->channels = vi->channels; if(!asset->sample_rate) asset->sample_rate = vi->rate; //printf("FileVorbis::open_file 1\n"); asset->audio_length = ov_pcm_total(&vf,-1); //printf("FileVorbis::open_file 1\n"); asset->audio_data = 1; // printf("FileVorbis::open_file 1 %d %d %d\n", // asset->channels, // asset->sample_rate, // asset->audio_length); } } } if(wr) { if(!(fd = fopen(asset->path, "wb"))) { eprintf("FileVorbis::open_file %s: %s\n", asset->path, strerror(errno)); result = 1; } else { vorbis_info_init(&vi); if(!asset->vorbis_vbr) result = vorbis_encode_init(&vi, asset->channels, asset->sample_rate, asset->vorbis_max_bitrate, asset->vorbis_bitrate, asset->vorbis_min_bitrate); else { result = vorbis_encode_setup_managed(&vi, asset->channels, asset->sample_rate, asset->vorbis_max_bitrate, asset->vorbis_bitrate, asset->vorbis_min_bitrate); result |= vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE_AVG, NULL); result |= vorbis_encode_setup_init(&vi); } if(!result) { vorbis_analysis_init(&vd, &vi); vorbis_block_init(&vd, &vb); vorbis_comment_init(&vc); srand(time(NULL)); ogg_stream_init(&os, rand()); ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout(&vd, &vc, &header, &header_comm, &header_code); ogg_stream_packetin(&os, &header); ogg_stream_packetin(&os, &header_comm); ogg_stream_packetin(&os, &header_code); while(1) { int result = ogg_stream_flush(&os, &og); if(result == 0) break; fwrite(og.header, 1, og.header_len, fd); fwrite(og.body, 1, og.body_len, fd); } } } } //printf("FileVorbis::open_file 2\n"); return result; }
int ExportOGG::Export(AudacityProject *project, int numChannels, wxString fName, bool selectionOnly, double t0, double t1, MixerSpec *mixerSpec, Tags *metadata, int WXUNUSED(subformat)) { double rate = project->GetRate(); TrackList *tracks = project->GetTracks(); double quality = (gPrefs->Read(wxT("/FileFormats/OggExportQuality"), 50)/(float)100.0); wxLogNull logNo; // temporarily disable wxWidgets error messages int updateResult = eProgressSuccess; int eos = 0; FileIO outFile(fName, FileIO::Output); if (!outFile.IsOpened()) { wxMessageBox(_("Unable to open target file for writing")); return false; } // All the Ogg and Vorbis encoding data ogg_stream_state stream; ogg_page page; ogg_packet packet; vorbis_info info; vorbis_comment comment; vorbis_dsp_state dsp; vorbis_block block; // Encoding setup vorbis_info_init(&info); vorbis_encode_init_vbr(&info, numChannels, int(rate + 0.5), quality); // Retrieve tags if (!FillComment(project, &comment, metadata)) { return false; } // Set up analysis state and auxiliary encoding storage vorbis_analysis_init(&dsp, &info); vorbis_block_init(&dsp, &block); // Set up packet->stream encoder. According to encoder example, // a random serial number makes it more likely that you can make // chained streams with concatenation. srand(time(NULL)); ogg_stream_init(&stream, rand()); // First we need to write the required headers: // 1. The Ogg bitstream header, which contains codec setup params // 2. The Vorbis comment header // 3. The bitstream codebook. // // After we create those our responsibility is complete, libvorbis will // take care of any other ogg bistream constraints (again, according // to the example encoder source) ogg_packet bitstream_header; ogg_packet comment_header; ogg_packet codebook_header; vorbis_analysis_headerout(&dsp, &comment, &bitstream_header, &comment_header, &codebook_header); // Place these headers into the stream ogg_stream_packetin(&stream, &bitstream_header); ogg_stream_packetin(&stream, &comment_header); ogg_stream_packetin(&stream, &codebook_header); // Flushing these headers now guarentees that audio data will // start on a NEW page, which apparently makes streaming easier while (ogg_stream_flush(&stream, &page)) { outFile.Write(page.header, page.header_len); outFile.Write(page.body, page.body_len); } int numWaveTracks; WaveTrack **waveTracks; tracks->GetWaveTracks(selectionOnly, &numWaveTracks, &waveTracks); Mixer *mixer = CreateMixer(numWaveTracks, waveTracks, tracks->GetTimeTrack(), t0, t1, numChannels, SAMPLES_PER_RUN, false, rate, floatSample, true, mixerSpec); delete [] waveTracks; ProgressDialog *progress = new ProgressDialog(wxFileName(fName).GetName(), selectionOnly ? _("Exporting the selected audio as Ogg Vorbis") : _("Exporting the entire project as Ogg Vorbis")); while (updateResult == eProgressSuccess && !eos) { float **vorbis_buffer = vorbis_analysis_buffer(&dsp, SAMPLES_PER_RUN); sampleCount samplesThisRun = mixer->Process(SAMPLES_PER_RUN); if (samplesThisRun == 0) { // Tell the library that we wrote 0 bytes - signalling the end. vorbis_analysis_wrote(&dsp, 0); } else { for (int i = 0; i < numChannels; i++) { float *temp = (float *)mixer->GetBuffer(i); memcpy(vorbis_buffer[i], temp, sizeof(float)*SAMPLES_PER_RUN); } // tell the encoder how many samples we have vorbis_analysis_wrote(&dsp, samplesThisRun); } // I don't understand what this call does, so here is the comment // from the example, verbatim: // // vorbis does some data preanalysis, then divvies up blocks // for more involved (potentially parallel) processing. Get // a single block for encoding now while (vorbis_analysis_blockout(&dsp, &block) == 1) { // analysis, assume we want to use bitrate management vorbis_analysis(&block, NULL); vorbis_bitrate_addblock(&block); while (vorbis_bitrate_flushpacket(&dsp, &packet)) { // add the packet to the bitstream ogg_stream_packetin(&stream, &packet); // From vorbis-tools-1.0/oggenc/encode.c: // If we've gone over a page boundary, we can do actual output, // so do so (for however many pages are available). while (!eos) { int result = ogg_stream_pageout(&stream, &page); if (!result) { break; } outFile.Write(page.header, page.header_len); outFile.Write(page.body, page.body_len); if (ogg_page_eos(&page)) { eos = 1; } } } } updateResult = progress->Update(mixer->MixGetCurrentTime()-t0, t1-t0); } delete progress;; delete mixer; ogg_stream_clear(&stream); vorbis_block_clear(&block); vorbis_dsp_clear(&dsp); vorbis_info_clear(&info); vorbis_comment_clear(&comment); outFile.Close(); return updateResult; }
/***************************************************************************** * OpenEncoder: probe the encoder and return score *****************************************************************************/ static int OpenEncoder( vlc_object_t *p_this ) { encoder_t *p_enc = (encoder_t *)p_this; encoder_sys_t *p_sys; int i_quality, i_min_bitrate, i_max_bitrate; ogg_packet header[3]; if( p_enc->fmt_out.i_codec != VLC_CODEC_VORBIS && !p_enc->b_force ) { return VLC_EGENERIC; } /* Allocate the memory needed to store the decoder's structure */ if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL ) return VLC_ENOMEM; p_enc->p_sys = p_sys; p_enc->pf_encode_audio = Encode; p_enc->fmt_in.i_codec = VLC_CODEC_FL32; p_enc->fmt_out.i_codec = VLC_CODEC_VORBIS; config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg ); i_quality = var_GetInteger( p_enc, ENC_CFG_PREFIX "quality" ); if( i_quality > 10 ) i_quality = 10; if( i_quality < 0 ) i_quality = 0; if( var_GetBool( p_enc, ENC_CFG_PREFIX "cbr" ) ) i_quality = 0; i_max_bitrate = var_GetInteger( p_enc, ENC_CFG_PREFIX "max-bitrate" ); i_min_bitrate = var_GetInteger( p_enc, ENC_CFG_PREFIX "min-bitrate" ); /* Initialize vorbis encoder */ vorbis_info_init( &p_sys->vi ); if( i_quality > 0 ) { /* VBR mode */ if( vorbis_encode_setup_vbr( &p_sys->vi, p_enc->fmt_in.audio.i_channels, p_enc->fmt_in.audio.i_rate, i_quality * 0.1 ) ) { vorbis_info_clear( &p_sys->vi ); free( p_enc->p_sys ); msg_Err( p_enc, "VBR mode initialisation failed" ); return VLC_EGENERIC; } /* Do we have optional hard quality restrictions? */ if( i_max_bitrate > 0 || i_min_bitrate > 0 ) { struct ovectl_ratemanage_arg ai; vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_GET, &ai ); ai.bitrate_hard_min = i_min_bitrate; ai.bitrate_hard_max = i_max_bitrate; ai.management_active = 1; vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_SET, &ai ); } else { /* Turn off management entirely */ vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_SET, NULL ); } } else { if( vorbis_encode_setup_managed( &p_sys->vi, p_enc->fmt_in.audio.i_channels, p_enc->fmt_in.audio.i_rate, i_min_bitrate > 0 ? i_min_bitrate * 1000: -1, p_enc->fmt_out.i_bitrate, i_max_bitrate > 0 ? i_max_bitrate * 1000: -1 ) ) { vorbis_info_clear( &p_sys->vi ); msg_Err( p_enc, "CBR mode initialisation failed" ); free( p_enc->p_sys ); return VLC_EGENERIC; } } vorbis_encode_setup_init( &p_sys->vi ); /* Add a comment */ vorbis_comment_init( &p_sys->vc); vorbis_comment_add_tag( &p_sys->vc, "ENCODER", "VLC media player"); /* Set up the analysis state and auxiliary encoding storage */ vorbis_analysis_init( &p_sys->vd, &p_sys->vi ); vorbis_block_init( &p_sys->vd, &p_sys->vb ); /* Create and store headers */ vorbis_analysis_headerout( &p_sys->vd, &p_sys->vc, &header[0], &header[1], &header[2]); for( int i = 0; i < 3; i++ ) { if( xiph_AppendHeaders( &p_enc->fmt_out.i_extra, &p_enc->fmt_out.p_extra, header[i].bytes, header[i].packet ) ) { p_enc->fmt_out.i_extra = 0; p_enc->fmt_out.p_extra = NULL; } } p_sys->i_channels = p_enc->fmt_in.audio.i_channels; p_sys->i_last_block_size = 0; p_sys->i_samples_delay = 0; ConfigureChannelOrder(p_sys->pi_chan_table, p_sys->vi.channels, p_enc->fmt_in.audio.i_physical_channels, true); return VLC_SUCCESS; }
//Method to start encoding int startEncoding(JNIEnv *env, jclass *cls_ptr, jlong *sampleRate_ptr, jlong *channels_ptr, jfloat *quality_ptr, jlong *bitrate_ptr, jobject *encoderDataFeed_ptr, int type) { //Dereference our variables jclass cls = (*cls_ptr); jlong sampleRate = (*sampleRate_ptr); jlong channels = (*channels_ptr); jfloat quality = (*quality_ptr); jlong bitrate = (*bitrate_ptr); jobject encoderDataFeed = (*encoderDataFeed_ptr); //Create our PCM data buffer signed char readbuffer[READ*4+44]; //Create a new java byte array to pass to the data feed method jbyteArray jByteArrayBuffer = (*env)->NewByteArray(env, READ*4); //Create a new java byte buffer to write to jbyteArray jByteArrayWriteBuffer = (*env)->NewByteArray(env, READ*8); //Find our java classes we'll be calling jclass encoderDataFeedClass = (*env)->FindClass(env, "org/xiph/vorbis/encoder/EncodeFeed"); //Find our java method id's we'll be calling jmethodID writeVorbisDataMethodId = (*env)->GetMethodID(env, encoderDataFeedClass, "writeVorbisData", "([BI)I"); jmethodID readPCMDataMethodId = (*env)->GetMethodID(env, encoderDataFeedClass, "readPCMData", "([BI)J"); jmethodID startMethodId = (*env)->GetMethodID(env, encoderDataFeedClass, "start", "()V"); jmethodID stopMethodId = (*env)->GetMethodID(env, encoderDataFeedClass, "stop", "()V"); ogg_stream_state os; /* take physical pages, weld into a logical stream of packets */ ogg_page og; /* one Ogg bitstream page. Vorbis packets are inside */ ogg_packet op; /* one raw packet of data for decode */ vorbis_info vi; /* struct that stores all the static vorbis bitstream settings */ vorbis_comment vc; /* struct that stores all the user comments */ vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */ vorbis_block vb; /* local working space for packet->PCM decode */ int eos=0,ret; int i, founddata; /********** Encode setup ************/ __android_log_print(ANDROID_LOG_INFO, "VorbisEncoder", "Setting up encoding"); vorbis_info_init(&vi); /* choose an encoding mode. A few possibilities commented out, one actually used: */ /********************************************************************* Encoding using a VBR quality mode. The usable range is -.1 (lowest quality, smallest file) to 1. (highest quality, largest file). Example quality mode .4: 44kHz stereo coupled, roughly 128kbps VBR ret = vorbis_encode_init_vbr(&vi,2,44100,.4); --------------------------------------------------------------------- Encoding using an average bitrate mode (ABR). example: 44kHz stereo coupled, average 128kbps VBR ret = vorbis_encode_init(&vi,2,44100,-1,128000,-1); --------------------------------------------------------------------- Encode using a quality mode, but select that quality mode by asking for an approximate bitrate. This is not ABR, it is true VBR, but selected using the bitrate interface, and then turning bitrate management off: ret = ( vorbis_encode_setup_managed(&vi,2,44100,-1,128000,-1) || vorbis_encode_ctl(&vi,OV_ECTL_RATEMANAGE2_SET,NULL) || vorbis_encode_setup_init(&vi)); *********************************************************************/ switch(type) { case WITH_BITRATE: __android_log_print(ANDROID_LOG_INFO, "VorbisEncoder", "Initializing with %lld channels %lldHz sample rate and %lld bitrate", channels, sampleRate, bitrate); ret=vorbis_encode_init(&vi, (long)channels, (long)sampleRate, (long)-1, (long)bitrate, (long)-1); break; case WITH_QUALITY: __android_log_print(ANDROID_LOG_INFO, "VorbisEncoder", "Initializing with %lld channels %lldHz sample rate and %f quality", channels, sampleRate, quality); ret=vorbis_encode_init_vbr(&vi, (long)channels, (long)sampleRate, (float)quality); break; default: __android_log_print(ANDROID_LOG_ERROR, "VorbisEncoder", "Failed to initialize"); stopEncodeFeed(env, &encoderDataFeed, &stopMethodId); return ERROR_INITIALIZING; } /* do not continue if setup failed; this can happen if we ask for a mode that libVorbis does not support (eg, too low a bitrate, etc, will return 'OV_EIMPL') */ if(ret) { __android_log_print(ANDROID_LOG_ERROR, "VorbisEncoder", "Failed to initialize"); stopEncodeFeed(env, &encoderDataFeed, &stopMethodId); return ERROR_INITIALIZING; } startEncodeFeed(env, &encoderDataFeed, &startMethodId); /* add a comment */ __android_log_print(ANDROID_LOG_DEBUG, "VorbisEncoder", "Adding comments"); vorbis_comment_init(&vc); vorbis_comment_add_tag(&vc,"ENCODER","JNIVorbisEncoder"); /* set up the analysis state and auxiliary encoding storage */ vorbis_analysis_init(&vd,&vi); vorbis_block_init(&vd,&vb); /* set up our packet->stream encoder */ /* pick a random serial number; that way we can more likely build chained streams just by concatenation */ srand(time(NULL)); ogg_stream_init(&os,rand()); /* Vorbis streams begin with three headers; the initial header (with most of the codec setup parameters) which is mandated by the Ogg bitstream spec. The second header holds any comment fields. The third header holds the bitstream codebook. We merely need to make the headers, then pass them to libvorbis one at a time; libvorbis handles the additional Ogg bitstream constraints */ { ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout(&vd,&vc,&header,&header_comm,&header_code); ogg_stream_packetin(&os,&header); /* automatically placed in its own page */ ogg_stream_packetin(&os,&header_comm); ogg_stream_packetin(&os,&header_code); /* This ensures the actual * audio data will start on a new page, as per spec */ __android_log_print(ANDROID_LOG_INFO, "VorbisEncoder", "Writting header"); while(!eos){ int result=ogg_stream_flush(&os,&og); if(result==0)break; writeVorbisDataToEncoderDataFeed(env, &encoderDataFeed, &writeVorbisDataMethodId, og.header, og.header_len, &jByteArrayWriteBuffer); writeVorbisDataToEncoderDataFeed(env, &encoderDataFeed, &writeVorbisDataMethodId, og.body, og.body_len, &jByteArrayWriteBuffer); } } __android_log_print(ANDROID_LOG_INFO, "VorbisEncoder", "Starting to read from pcm callback"); while(!eos){ long i; long bytes = readPCMDataFromEncoderDataFeed(env, &encoderDataFeed, &readPCMDataMethodId, readbuffer, READ*4, &jByteArrayBuffer); if(bytes==0){ /* end of file. this can be done implicitly in the mainline, but it's easier to see here in non-clever fashion. Tell the library we're at end of stream so that it can handle the last frame and mark end of stream in the output properly */ __android_log_print(ANDROID_LOG_INFO, "VorbisEncoder", "End of file"); vorbis_analysis_wrote(&vd,0); }else{ /* data to encode */ /* expose the buffer to submit data */ float **buffer=vorbis_analysis_buffer(&vd,bytes/(2*channels)); /* uninterleave samples */ int channel; for(i=0;i<bytes/(2*channels);i++) { for(channel = 0; channel < channels; channel++) { buffer[channel][i]=((readbuffer[i*(2*channels)+(channel*2+1)]<<8)| (0x00ff&(int)readbuffer[i*(2*channels)+(channel*2)]))/32768.f; } } /* tell the library how much we actually submitted */ vorbis_analysis_wrote(&vd,i); } /* vorbis does some data preanalysis, then divvies up blocks for more involved (potentially parallel) processing. Get a single block for encoding now */ while(vorbis_analysis_blockout(&vd,&vb)==1){ /* analysis, assume we want to use bitrate management */ vorbis_analysis(&vb,NULL); vorbis_bitrate_addblock(&vb); while(vorbis_bitrate_flushpacket(&vd,&op)){ /* weld the packet into the bitstream */ ogg_stream_packetin(&os,&op); /* write out pages (if any) */ while(!eos){ int result=ogg_stream_pageout(&os,&og); if(result==0)break; writeVorbisDataToEncoderDataFeed(env, &encoderDataFeed, &writeVorbisDataMethodId, og.header, og.header_len, &jByteArrayWriteBuffer); writeVorbisDataToEncoderDataFeed(env, &encoderDataFeed, &writeVorbisDataMethodId, og.body, og.body_len, &jByteArrayWriteBuffer); /* this could be set above, but for illustrative purposes, I do it here (to show that vorbis does know where the stream ends) */ if(ogg_page_eos(&og))eos=1; } } } } /* clean up and exit. vorbis_info_clear() must be called last */ __android_log_print(ANDROID_LOG_INFO, "VorbisEncoder", "Cleaning up encoder"); ogg_stream_clear(&os); vorbis_block_clear(&vb); vorbis_dsp_clear(&vd); vorbis_comment_clear(&vc); vorbis_info_clear(&vi); /* ogg_page and ogg_packet structs always point to storage in libvorbis. They're never freed or manipulated directly */ __android_log_print(ANDROID_LOG_INFO, "VorbisEncoder", "Completed encoding."); stopEncodeFeed(env, &encoderDataFeed, &stopMethodId); //Clean up encode buffers (*env)->DeleteLocalRef(env, jByteArrayBuffer); (*env)->DeleteLocalRef(env, jByteArrayWriteBuffer); return SUCCESS; }
static LONG APIENTRY IOProc_Entry2(PVOID pmmioStr, USHORT usMsg, LONG lParam1, LONG lParam2) { PMMIOINFO pmmioinfo = (PMMIOINFO)pmmioStr; switch (usMsg) { case MMIOM_OPEN: { HMMIO hmmioSS; MMIOINFO mmioinfoSS; PSZ pszFileName = (char *)lParam1; if (!pmmioinfo) return MMIO_ERROR; if ((pmmioinfo->ulFlags & MMIO_READWRITE)) { #ifdef DEBUG fprintf(file,"ReadWrite - requested.\n"); #endif return MMIO_ERROR; } if (!(pmmioinfo->ulTranslate & MMIO_TRANSLATEHEADER) && !(pmmioinfo->ulTranslate & MMIO_TRANSLATEDATA)) return MMIO_ERROR; if (!pmmioinfo->fccChildIOProc) { FOURCC fccFileStorageSystem; if (pmmioinfo->ulFlags & MMIO_CREATE) { if (mmioDetermineSSIOProc(pszFileName, pmmioinfo, &fccFileStorageSystem, NULL)) { fccFileStorageSystem = FOURCC_DOS; } } else { if (mmioIdentifyStorageSystem(pszFileName, pmmioinfo, &fccFileStorageSystem)) { return MMIO_ERROR; } } if (!fccFileStorageSystem) { return MMIO_ERROR; } else { pmmioinfo->fccChildIOProc = fccFileStorageSystem; } /* endif */ } memmove(&mmioinfoSS, pmmioinfo, sizeof(MMIOINFO)); mmioinfoSS.pIOProc = NULL; mmioinfoSS.fccIOProc = pmmioinfo->fccChildIOProc; mmioinfoSS.ulFlags |= MMIO_NOIDENTIFY; hmmioSS = mmioOpen (pszFileName, &mmioinfoSS, mmioinfoSS.ulFlags); if (pmmioinfo->ulFlags & MMIO_DELETE) { if (!hmmioSS) { pmmioinfo->ulErrorRet = MMIOERR_DELETE_FAILED; return MMIO_ERROR; } else return MMIO_SUCCESS; } if (!hmmioSS) return MMIO_ERROR; if (pmmioinfo->ulFlags & MMIO_READ) { DecInfo *decInfo = (DecInfo *)malloc(sizeof(DecInfo)); #ifdef DEBUG fprintf(file,"File Read: %s\n",pszFileName); #endif if (!decInfo) { mmioClose(hmmioSS, 0); return MMIO_ERROR; } decInfo->t = READNUM; decInfo->vorbisOptions = pmmioinfo->pExtraInfoStruct; pmmioinfo->pExtraInfoStruct = (PVOID)decInfo; { ov_callbacks cb; cb.read_func = mread; cb.seek_func = mseek; cb.close_func = mclose; cb.tell_func = mtell; if(0 != ov_open_callbacks((void *)hmmioSS, &decInfo->oggfile, 0, 0, cb)) { free(decInfo); mmioClose(hmmioSS, 0); return MMIO_ERROR; } } #ifdef DEBUG fprintf(file,"Open successfull\n"); #endif return MMIO_SUCCESS; } else if (pmmioinfo->ulFlags & MMIO_WRITE) { EncInfo *encInfo = (EncInfo *)malloc(sizeof(EncInfo)); #ifdef DEBUG fprintf(file,"File Write: %s\n",pszFileName); #endif if (!encInfo) { mmioClose(hmmioSS, 0); return MMIO_ERROR; } memset(encInfo, 0, sizeof(EncInfo)); encInfo->t = WRITENUM; encInfo->hmmioSS = hmmioSS; encInfo->vorbisOptions = (PVORBISOPTIONS)pmmioinfo->pExtraInfoStruct; pmmioinfo->pExtraInfoStruct = (PVOID)encInfo; return MMIO_SUCCESS; } #ifdef DEBUG fprintf(file,"File not read nor write: %s\n",pszFileName); #endif return MMIO_ERROR; } break; case MMIOM_READ: { if (!pmmioinfo || !pmmioinfo->pExtraInfoStruct || !lParam1) return MMIO_ERROR; if (!pmmioinfo->ulTranslate & MMIO_TRANSLATEDATA) { return MMIO_ERROR; // return mmioRead (ogginfo->hmmioSS, (PVOID) lParam1, (ULONG) lParam2); } else { OggVorbis_File *oggfile; long rc = 0; int current_section; long total = 0; oggfile = &((DecInfo *)pmmioinfo->pExtraInfoStruct)->oggfile; if (READNUM != ((DecInfo *)pmmioinfo->pExtraInfoStruct)->t) return MMIO_ERROR; while (lParam2 > 0) { rc = ov_read(oggfile, (char *)lParam1, (int)lParam2, 0, 2, 1, ¤t_section); if (rc < 0) { #ifdef DEBUG fprintf(file, "Read failed once\n"); #endif continue; } if (rc <= 0) break; lParam2 -= rc; lParam1 += rc; total += rc; } #ifdef DEBUG fprintf(file,"Read rc:%ld total:%ld\n",rc,total); #endif if (rc < 0) return MMIO_ERROR; return total; } } break; case MMIOM_SEEK: { LONG lPosDesired; OggVorbis_File *oggfile; vorbis_info *vi; if (!pmmioinfo || !pmmioinfo->pExtraInfoStruct) return MMIO_ERROR; if (!pmmioinfo->ulTranslate & MMIO_TRANSLATEDATA) return MMIO_ERROR; oggfile = &((DecInfo *)pmmioinfo->pExtraInfoStruct)->oggfile; if (READNUM != ((DecInfo *)pmmioinfo->pExtraInfoStruct)->t) return MMIO_ERROR; vi = ov_info(oggfile, -1); if (!vi) return MMIO_ERROR; if (SEEK_SET == lParam2) { lPosDesired = lParam1/(2*vi->channels); } else if (SEEK_CUR == lParam2) { if (0 == lParam1) { return ov_pcm_tell(oggfile)*2*vi->channels; } /* endif */ lPosDesired = ov_pcm_tell(oggfile) + lParam1/(2*vi->channels); } else if (SEEK_END == lParam2) { lPosDesired = ov_pcm_total(oggfile,-1) + lParam1/(2*vi->channels); } else { return MMIO_ERROR; } #ifdef DEBUG fprintf(file,"Seek to %ld by %d\n",lPosDesired, lParam2); #endif if (ov_pcm_seek(oggfile, lPosDesired) < 0) return MMIO_ERROR; return lPosDesired*2*vi->channels; } break; case MMIOM_CLOSE: { int rc; #ifdef DEBUG fprintf(file,"start CLOSE\n"); #endif if (!pmmioinfo) return MMIO_ERROR; if (pmmioinfo->pExtraInfoStruct) { DecInfo *decInfo = (DecInfo *)pmmioinfo->pExtraInfoStruct; #ifdef DEBUG fprintf(file,"ready CLOSE\n"); #endif if (READNUM == decInfo->t) { #ifdef DEBUG fprintf(file,"read CLOSE\n"); #endif ov_clear(&decInfo->oggfile); free(decInfo); decInfo = 0; rc=MMIO_SUCCESS; } else if (WRITENUM == decInfo->t) { EncInfo *encInfo = (EncInfo*)pmmioinfo->pExtraInfoStruct; #ifdef DEBUG fprintf(file,"write CLOSE\n"); #endif if (encInfo->headerSet) { vorbis_analysis_wrote(&encInfo->vd,0); rc = oggWrite(encInfo,1); ogg_stream_clear(&encInfo->os); vorbis_block_clear(&encInfo->vb); vorbis_dsp_clear(&encInfo->vd); vorbis_comment_clear(&encInfo->vc); vorbis_info_clear(&encInfo->vi); } mmioClose(encInfo->hmmioSS, 0); free(encInfo); encInfo = 0; rc = MMIO_SUCCESS; } else rc = MMIO_ERROR; pmmioinfo->pExtraInfoStruct = 0; #ifdef DEBUG fprintf(file,"CLOSE\n"); #endif return rc; } return MMIO_ERROR; } break; case MMIOM_IDENTIFYFILE: { unsigned char buf[4]; HMMIO hmmioTemp; ULONG ulTempFlags = MMIO_READ | MMIO_DENYWRITE | MMIO_NOIDENTIFY; LONG rc = MMIO_ERROR; if (!lParam1 && !lParam2) return MMIO_ERROR; hmmioTemp = (HMMIO)lParam2; if (!hmmioTemp) { hmmioTemp = mmioOpen((PSZ)lParam1, NULL, ulTempFlags); } if (hmmioTemp) { rc = mmioRead(hmmioTemp, buf, 4); if (rc == 4 && buf[0] == 'O' && buf[1] == 'g' && buf[2] == 'g' && buf[3] == 'S') { rc = MMIO_SUCCESS; } if (!lParam2) mmioClose(hmmioTemp, 0); } return rc; } break; case MMIOM_GETFORMATINFO: { PMMFORMATINFO pmmformatinfo; pmmformatinfo = (PMMFORMATINFO)lParam1; pmmformatinfo->ulStructLen = sizeof(MMFORMATINFO); pmmformatinfo->fccIOProc = FOURCC_Vorbis; pmmformatinfo->ulIOProcType = MMIO_IOPROC_FILEFORMAT; pmmformatinfo->ulMediaType = MMIO_MEDIATYPE_AUDIO; pmmformatinfo->ulFlags = MMIO_CANREADTRANSLATED | MMIO_CANWRITETRANSLATED | MMIO_CANSEEKTRANSLATED; strcpy(pmmformatinfo->szDefaultFormatExt, "OGG"); pmmformatinfo->ulCodePage = 0; pmmformatinfo->ulLanguage = 0; pmmformatinfo->lNameLength = 21; return MMIO_SUCCESS; } break; case MMIOM_GETFORMATNAME: if (lParam2 > 21) { strcpy((PSZ)lParam1, "Ogg Vorbis"); return MMIO_SUCCESS; } else return MMIO_ERROR; break; case MMIOM_QUERYHEADERLENGTH: return (sizeof (MMAUDIOHEADER)); break; case MMIOM_GETHEADER: { OggVorbis_File *oggfile; DecInfo *decInfo; PMMAUDIOHEADER mmaudioheader; vorbis_info *vi; if (!pmmioinfo || !pmmioinfo->pExtraInfoStruct) return 0; if (!(pmmioinfo->ulFlags & MMIO_READ)) return 0; decInfo = (DecInfo *)pmmioinfo->pExtraInfoStruct; oggfile = &decInfo->oggfile; if (READNUM != decInfo->t){ pmmioinfo->ulErrorRet = MMIOERR_INVALID_STRUCTURE; return 0; } #ifdef DEBUG fprintf(file,"HERE\n"); #endif if (!(pmmioinfo->ulTranslate & MMIO_TRANSLATEHEADER) && !(pmmioinfo->ulTranslate & MMIO_TRANSLATEDATA)) return 0; mmaudioheader = (MMAUDIOHEADER *)lParam1; if (sizeof(MMAUDIOHEADER) > lParam2) { pmmioinfo->ulErrorRet = MMIOERR_INVALID_BUFFER_LENGTH; return 0; } #ifdef DEBUG fprintf(file,"THERE\n"); #endif vi = ov_info(oggfile, -1); if (!vi) { pmmioinfo->ulErrorRet = MMIOERR_INVALID_STRUCTURE; return 0; } mmaudioheader->ulContentType = MMIO_MIDI_UNKNOWN; mmaudioheader->ulMediaType = MMIO_MEDIATYPE_AUDIO; mmaudioheader->mmXWAVHeader.WAVEHeader.usFormatTag=DATATYPE_WAVEFORM; mmaudioheader->mmXWAVHeader.WAVEHeader.usChannels = vi->channels; mmaudioheader->mmXWAVHeader.WAVEHeader.ulSamplesPerSec = vi->rate; mmaudioheader->mmXWAVHeader.WAVEHeader.usBitsPerSample = 16; mmaudioheader->mmXWAVHeader.WAVEHeader.ulAvgBytesPerSec= mmaudioheader->mmXWAVHeader.WAVEHeader.usChannels * mmaudioheader->mmXWAVHeader.WAVEHeader.ulSamplesPerSec * mmaudioheader->mmXWAVHeader.WAVEHeader.usBitsPerSample / 8; mmaudioheader->mmXWAVHeader.WAVEHeader.usBlockAlign= mmaudioheader->mmXWAVHeader.WAVEHeader.usChannels * mmaudioheader->mmXWAVHeader.WAVEHeader.usBitsPerSample / 8; mmaudioheader->mmXWAVHeader.XWAVHeaderInfo.ulAudioLengthInMS= (unsigned long)(ov_time_total(oggfile, -1)*1000.0); mmaudioheader->mmXWAVHeader.XWAVHeaderInfo.ulAudioLengthInBytes= (unsigned long)ov_pcm_total(oggfile, -1)* mmaudioheader->mmXWAVHeader.WAVEHeader.usBlockAlign; #ifdef DEBUG fprintf(file,"time: %ld size: %ld rate: %ld\n", mmaudioheader->mmXWAVHeader.XWAVHeaderInfo.ulAudioLengthInMS, mmaudioheader->mmXWAVHeader.XWAVHeaderInfo.ulAudioLengthInBytes, mmaudioheader->mmXWAVHeader.WAVEHeader.ulSamplesPerSec); #endif if (0 != decInfo->vorbisOptions && VORBIS_COOKIE == decInfo->vorbisOptions->cookie) { decInfo->vorbisOptions->nominal_bitrate = ov_bitrate(oggfile, -1); mmaudioheader->mmXWAVHeader.XWAVHeaderInfo.pAdditionalInformation = decInfo->vorbisOptions; } return (sizeof (MMAUDIOHEADER)); } break; case MMIOM_SETHEADER: { EncInfo *encInfo; PMMAUDIOHEADER mmaudioheader; int totalout = 0; int rc; if (!pmmioinfo || !pmmioinfo->pExtraInfoStruct) return 0; encInfo = (EncInfo*)pmmioinfo->pExtraInfoStruct; if (WRITENUM != encInfo->t) return 0; #ifdef DEBUG fprintf(file,"write header: %x, %x, %x\n",!(pmmioinfo->ulFlags & MMIO_WRITE), encInfo->headerSet, (!(pmmioinfo->ulTranslate & MMIO_TRANSLATEHEADER) && !(pmmioinfo->ulTranslate & MMIO_TRANSLATEDATA))); fprintf(file,"flag: %x, trans: %x\n",pmmioinfo->ulFlags,pmmioinfo->ulTranslate); #endif if (/*!(pmmioinfo->ulFlags & MMIO_WRITE) ||*/ encInfo->headerSet || (!(pmmioinfo->ulTranslate & MMIO_TRANSLATEHEADER) && !(pmmioinfo->ulTranslate & MMIO_TRANSLATEDATA))) return 0; if (!lParam1) { pmmioinfo->ulErrorRet = MMIOERR_INVALID_STRUCTURE; return 0; } mmaudioheader = (PMMAUDIOHEADER)lParam1; if (lParam2 != sizeof(MMAUDIOHEADER)) { pmmioinfo->ulErrorRet = MMIOERR_INVALID_BUFFER_LENGTH; return 0; } /********** Encode setup ************/ if (0 != mmaudioheader->mmXWAVHeader.WAVEHeader.usBitsPerSample%8) { /* Bit-rate must be multiple of 8 */ return 0; } encInfo->bitsPerSample=mmaudioheader->mmXWAVHeader.WAVEHeader.usBitsPerSample; #ifdef DEBUG fprintf(file,"ready to write header: "); #endif vorbis_info_init(&encInfo->vi); if (0 == encInfo->vorbisOptions || VORBIS_COOKIE != encInfo->vorbisOptions->cookie) { #ifdef DEBUG fprintf(file,"default quality 0.3\n"); #endif rc = vorbis_encode_init_vbr(&encInfo->vi, mmaudioheader->mmXWAVHeader.WAVEHeader.usChannels, mmaudioheader->mmXWAVHeader.WAVEHeader.ulSamplesPerSec, 0.3); } else { #ifdef DEBUG fprintf(file,"bitsPerSample: %d channels: %d samplesPerSec: %ld min: %ld nominal: %ld max: %ld\n", encInfo->bitsPerSample, mmaudioheader->mmXWAVHeader.WAVEHeader.usChannels, mmaudioheader->mmXWAVHeader.WAVEHeader.ulSamplesPerSec, encInfo->vorbisOptions->max_bitrate, encInfo->vorbisOptions->nominal_bitrate, encInfo->vorbisOptions->min_bitrate); #endif rc = vorbis_encode_init(&encInfo->vi, mmaudioheader->mmXWAVHeader.WAVEHeader.usChannels, mmaudioheader->mmXWAVHeader.WAVEHeader.ulSamplesPerSec, encInfo->vorbisOptions->max_bitrate, encInfo->vorbisOptions->nominal_bitrate, encInfo->vorbisOptions->min_bitrate); } if (rc) { #ifdef DEBUG fprintf(file,"encodeInit failed: %d\n",rc); #endif return 0; } /* endif */ /* add a comment */ vorbis_comment_init(&encInfo->vc); vorbis_comment_add_tag(&encInfo->vc,"ENCODER","mmioVorbis"); /* set up the analysis state and auxiliary encoding storage */ vorbis_analysis_init(&encInfo->vd,&encInfo->vi); vorbis_block_init(&encInfo->vd,&encInfo->vb); /* set up our packet->stream encoder */ /* pick a random serial number; that way we can more likely build chained streams just by concatenation */ srand(time(NULL)); ogg_stream_init(&encInfo->os,rand()); { ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout(&encInfo->vd,&encInfo->vc,&header,&header_comm,&header_code); ogg_stream_packetin(&encInfo->os,&header); /* automatically placed in its own page */ ogg_stream_packetin(&encInfo->os,&header_comm); ogg_stream_packetin(&encInfo->os,&header_code); while(1){ int result=ogg_stream_flush(&encInfo->os,&encInfo->og); if(result==0)break; result = mmioWrite(encInfo->hmmioSS, encInfo->og.header,encInfo->og.header_len); totalout += result; if (result!=encInfo->og.header_len) { ogg_stream_clear(&encInfo->os); vorbis_block_clear(&encInfo->vb); vorbis_dsp_clear(&encInfo->vd); vorbis_comment_clear(&encInfo->vc); vorbis_info_clear(&encInfo->vi); return 0; } result = mmioWrite(encInfo->hmmioSS, encInfo->og.body,encInfo->og.body_len); totalout += result; if (result!=encInfo->og.body_len) { ogg_stream_clear(&encInfo->os); vorbis_block_clear(&encInfo->vb); vorbis_dsp_clear(&encInfo->vd); vorbis_comment_clear(&encInfo->vc); vorbis_info_clear(&encInfo->vi); return 0; } } } encInfo->headerSet = 1; return totalout; } break; case MMIOM_WRITE: { EncInfo *encInfo; if (!pmmioinfo || !pmmioinfo->pExtraInfoStruct) return MMIO_ERROR; encInfo = (EncInfo*)pmmioinfo->pExtraInfoStruct; if (WRITENUM != encInfo->t) return MMIO_ERROR; if (!encInfo->headerSet) return MMIO_ERROR; if (!(pmmioinfo->ulTranslate & MMIO_TRANSLATEDATA)) { if (!lParam1) return MMIO_ERROR; return mmioWrite(encInfo->hmmioSS, (PVOID)lParam1, lParam2); } else { if (lParam2 == 0) { vorbis_analysis_wrote(&encInfo->vd,0); } else { long i; int j, k; int num; float denom = 1; signed char *readbuffer = (char *)lParam1; /* data to encode */ /* expose the buffer to submit data */ int sampleSize = encInfo->vi.channels*encInfo->bitsPerSample/8; int samples = lParam2/sampleSize; float **buffer=vorbis_analysis_buffer(&encInfo->vd, samples); #ifdef DEBUG fprintf(file,"write: %ld\n",lParam2); #endif /* :TODO: Work with buffers not a multiple of sampleSize*/ if (lParam2 % sampleSize != 0) { #ifdef DEBUG fprintf(file,"Bad Write Buffer Size\n"); #endif return MMIO_ERROR; } for(i=0;i<samples;i++){ for (j=0;j<encInfo->vi.channels;j++) { num=0; denom=0.5; if (encInfo->bitsPerSample<=8) { buffer[j][i]=(float)((unsigned char)(readbuffer[i*sampleSize])- (1<<(encInfo->bitsPerSample-1)))/ (float)(1<<(encInfo->bitsPerSample-1)); } else { for (k=encInfo->bitsPerSample/8;k>0;k--) { if (k==encInfo->bitsPerSample/8) { num=(readbuffer[i*sampleSize+k-1]); } else { num=(num<<8)|((0xff)&(int)(readbuffer[i*sampleSize+k-1])); } denom *= 256.0; } buffer[j][i]=((float)num)/denom; } } /* endfor */ } vorbis_analysis_wrote(&encInfo->vd,i); } /* endif */ if (oggWrite(encInfo,0)>=0) { return lParam2; } else { return MMIO_ERROR; } /* endif */ } } break; #ifdef DEBUG case MMIOM_TEMPCHANGE: { return MMIO_SUCCESS; } break; #endif } #ifdef DEBUG fprintf(file,"unexpected command: %x\n",usMsg); #endif return MMIOERR_UNSUPPORTED_MESSAGE; }
int encvorbisInit(hb_work_object_t *w, hb_job_t *job) { hb_work_private_t *pv = calloc(1, sizeof(hb_work_private_t)); hb_audio_t *audio = w->audio; w->private_data = pv; pv->job = job; int i; ogg_packet header[3]; hb_log("encvorbis: opening libvorbis"); /* init */ for (i = 0; i < 3; i++) { // Zero vorbis headers so that we don't crash in mk_laceXiph // when vorbis_encode_setup_managed fails. memset(w->config->vorbis.headers[i], 0, sizeof(ogg_packet)); } vorbis_info_init(&pv->vi); pv->out_discrete_channels = hb_mixdown_get_discrete_channel_count(audio->config.out.mixdown); if (audio->config.out.bitrate > 0) { if (vorbis_encode_setup_managed(&pv->vi, pv->out_discrete_channels, audio->config.out.samplerate, -1, audio->config.out.bitrate * 1000, -1)) { hb_error("encvorbis: vorbis_encode_setup_managed() failed"); *job->die = 1; return -1; } } else if (audio->config.out.quality != HB_INVALID_AUDIO_QUALITY) { // map VBR quality to Vorbis API (divide by 10) if (vorbis_encode_setup_vbr(&pv->vi, pv->out_discrete_channels, audio->config.out.samplerate, audio->config.out.quality / 10)) { hb_error("encvorbis: vorbis_encode_setup_vbr() failed"); *job->die = 1; return -1; } } if (vorbis_encode_ctl(&pv->vi, OV_ECTL_RATEMANAGE2_SET, NULL) || vorbis_encode_setup_init(&pv->vi)) { hb_error("encvorbis: vorbis_encode_ctl(ratemanage2_set) OR vorbis_encode_setup_init() failed"); *job->die = 1; return -1; } /* add a comment */ vorbis_comment_init(&pv->vc); vorbis_comment_add_tag(&pv->vc, "Encoder", "HandBrake"); vorbis_comment_add_tag(&pv->vc, "LANGUAGE", w->config->vorbis.language); /* set up the analysis state and auxiliary encoding storage */ vorbis_analysis_init(&pv->vd, &pv->vi); vorbis_block_init(&pv->vd, &pv->vb); /* get the 3 headers */ vorbis_analysis_headerout(&pv->vd, &pv->vc, &header[0], &header[1], &header[2]); for (i = 0; i < 3; i++) { memcpy(w->config->vorbis.headers[i], &header[i], sizeof(ogg_packet)); memcpy(w->config->vorbis.headers[i] + sizeof(ogg_packet), header[i].packet, header[i].bytes); } pv->input_samples = pv->out_discrete_channels * OGGVORBIS_FRAME_SIZE; audio->config.out.samples_per_frame = OGGVORBIS_FRAME_SIZE; pv->buf = malloc(pv->input_samples * sizeof(float)); pv->list = hb_list_init(); // channel remapping uint64_t layout = hb_ff_mixdown_xlat(audio->config.out.mixdown, NULL); pv->remap_table = hb_audio_remap_build_table(layout, &hb_vorbis_chan_map, audio->config.in.channel_map); if (pv->remap_table == NULL) { hb_error("encvorbisInit: hb_audio_remap_build_table() failed"); *job->die = 1; return -1; } return 0; }
int main(){ ogg_stream_state os; /* take physical pages, weld into a logical stream of packets */ ogg_page og; /* one Ogg bitstream page. Vorbis packets are inside */ ogg_packet op; /* one raw packet of data for decode */ vorbis_info vi; /* struct that stores all the static vorbis bitstream settings */ vorbis_comment vc; /* struct that stores all the user comments */ vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */ vorbis_block vb; /* local working space for packet->PCM decode */ int eos=0,ret; int i, founddata; int numReads=0; FILE *outFile = fopen("../test.ogg","wb"); /* we cheat on the WAV header; we just bypass 44 bytes (simplest WAV header is 44 bytes) and assume that the data is 44.1khz, stereo, 16 bit little endian pcm samples. This is just an example, after all. */ /********** Encode setup ************/ vorbis_info_init(&vi); /* choose an encoding mode. A few possibilities commented out, one actually used: */ /********************************************************************* Encoding using a VBR quality mode. The usable range is -.1 (lowest quality, smallest file) to 1. (highest quality, largest file). Example quality mode .4: 44kHz stereo coupled, roughly 128kbps VBR ret = vorbis_encode_init_vbr(&vi,2,44100,.4); --------------------------------------------------------------------- Encoding using an average bitrate mode (ABR). example: 44kHz stereo coupled, average 128kbps VBR ret = vorbis_encode_init(&vi,2,44100,-1,128000,-1); --------------------------------------------------------------------- Encode using a quality mode, but select that quality mode by asking for an approximate bitrate. This is not ABR, it is true VBR, but selected using the bitrate interface, and then turning bitrate management off: ret = ( vorbis_encode_setup_managed(&vi,2,44100,-1,128000,-1) || vorbis_encode_ctl(&vi,OV_ECTL_RATEMANAGE2_SET,NULL) || vorbis_encode_setup_init(&vi)); *********************************************************************/ ret=vorbis_encode_init_vbr(&vi,2,44100,1.0); /* do not continue if setup failed; this can happen if we ask for a mode that libVorbis does not support (eg, too low a bitrate, etc, will return 'OV_EIMPL') */ if(ret)exit(1); /* add a comment */ vorbis_comment_init(&vc); vorbis_comment_add_tag(&vc,"ENCODER","encoder_example.c"); /* set up the analysis state and auxiliary encoding storage */ vorbis_analysis_init(&vd,&vi); vorbis_block_init(&vd,&vb); /* set up our packet->stream encoder */ /* pick a random serial number; that way we can more likely build chained streams just by concatenation */ srand(time(NULL)); ogg_stream_init(&os,rand()); /* Vorbis streams begin with three headers; the initial header (with most of the codec setup parameters) which is mandated by the Ogg bitstream spec. The second header holds any comment fields. The third header holds the bitstream codebook. We merely need to make the headers, then pass them to libvorbis one at a time; libvorbis handles the additional Ogg bitstream constraints */ { ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout(&vd,&vc,&header,&header_comm,&header_code); ogg_stream_packetin(&os,&header); /* automatically placed in its own page */ ogg_stream_packetin(&os,&header_comm); ogg_stream_packetin(&os,&header_code); /* This ensures the actual * audio data will start on a new page, as per spec */ while(!eos){ int result=ogg_stream_flush(&os,&og); if(result==0)break; fwrite(og.header,1,og.header_len,outFile); fwrite(og.body,1,og.body_len,outFile); } } while(!eos){ long i; long bytes=READ*4; /* stereo hardwired here */ numReads++; if(numReads>10000) bytes=0; if(bytes==0){ /* end of file. this can be done implicitly in the mainline, but it's easier to see here in non-clever fashion. Tell the library we're at end of stream so that it can handle the last frame and mark end of stream in the output properly */ vorbis_analysis_wrote(&vd,0); }else{ /* data to encode */ /* expose the buffer to submit data */ float **buffer=vorbis_analysis_buffer(&vd,READ); /* uninterleave samples */ for(i=0;i<bytes/4;i++){ static float curamp = 0; curamp += 0.15f; buffer[0][i] = sinf(curamp); buffer[1][i] = sinf(curamp); } /* tell the library how much we actually submitted */ vorbis_analysis_wrote(&vd,i); } /* vorbis does some data preanalysis, then divvies up blocks for more involved (potentially parallel) processing. Get a single block for encoding now */ while(vorbis_analysis_blockout(&vd,&vb)==1){ /* analysis, assume we want to use bitrate management */ vorbis_analysis(&vb,NULL); vorbis_bitrate_addblock(&vb); while(vorbis_bitrate_flushpacket(&vd,&op)){ /* weld the packet into the bitstream */ ogg_stream_packetin(&os,&op); /* write out pages (if any) */ while(!eos){ int result=ogg_stream_pageout(&os,&og); if(result==0)break; fwrite(og.header,1,og.header_len,outFile); fwrite(og.body,1,og.body_len,outFile); /* this could be set above, but for illustrative purposes, I do it here (to show that vorbis does know where the stream ends) */ if(ogg_page_eos(&og))eos=1; } } } } /* clean up and exit. vorbis_info_clear() must be called last */ ogg_stream_clear(&os); vorbis_block_clear(&vb); vorbis_dsp_clear(&vd); vorbis_comment_clear(&vc); vorbis_info_clear(&vi); /* ogg_page and ogg_packet structs always point to storage in libvorbis. They're never freed or manipulated directly */ fprintf(stderr,"Done.\n"); return(0); }
DEFINE_CONSTRUCTOR() { Private *pv = NULL; JL_DEFINE_ARGS; JL_ASSERT_CONSTRUCTING(); JL_DEFINE_CONSTRUCTOR_OBJ; JL_ASSERT_ARGC_RANGE(0,3); pv = static_cast<Private*>(jl_malloc(sizeof(Private))); JL_SetPrivate(JL_OBJ, pv); long channels = jl::getValueDefault(cx, JL_SARG(1), 2L); long rate = jl::getValueDefault(cx, JL_SARG(2), 44100L); float quality = jl::getValueDefault(cx, JL_SARG(3), 0.f); // JL_ASSERT_RANGE(quality, -0.1f, 1.0f, "quality"); vorbis_info_init(&pv->vi); int st; //st = vorbis_encode_setup_vbr(&pv->vi, 2, 44100, 0.); // st = vorbis_encode_setup_init(&pv->vi); //vorbis_encode_ctl(&pv->vi, vorbis_encode_ctl(&pv->vi, OV_ECTL_RATEMANAGE_SET, NULL); // VBR st = vorbis_encode_init_vbr(&pv->vi, channels, rate, quality); ASSERT( st == 0 ); /* // CBR/ABR st = vorbis_encode_init(&pv->vi, channels, rate, 64 *1024, 96 *1024, 128 *1024); ASSERT( st == 0 ); */ // st = vorbis_encode_ctl(&pv->vi, OV_ECTL_RATEMANAGE2_SET, NULL); // ASSERT( st == 0 ); st = vorbis_analysis_init(&pv->vds, &pv->vi); ASSERT( st == 0 ); st = vorbis_block_init(&pv->vds, &pv->vb); ASSERT( st == 0 ); // ogg stream srand((unsigned)time(NULL)); st = ogg_stream_init(&pv->oss, rand()); ASSERT( st == 0 ); ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_comment vc; vorbis_comment_init(&vc); //vorbis_comment_add_tag(&vc, "ENCODER", "jslibs"); st = vorbis_analysis_headerout(&pv->vds, &vc, &header, &header_comm, &header_code); ASSERT( st == 0 ); st = ogg_stream_packetin(&pv->oss, &header); ASSERT( st == 0 ); st = ogg_stream_packetin(&pv->oss, &header_comm); ASSERT( st == 0 ); st = ogg_stream_packetin(&pv->oss, &header_code); ASSERT( st == 0 ); /* for (;;) { int flushStatus = ogg_stream_flush(&pv->oss, &pv->op); if( flushStatus == 0 ) break; } dstBuf.Write(pv->op.header, pv->op.header_len); dstBuf.Write(pv->op.body, pv->op.body_len); */ return true; bad: jl_free(pv); return false; }
/*! * \brief Create a new OGG/Vorbis filestream and set it up for writing. * \param fd File descriptor that points to on-disk storage. * \param comment Comment that should be embedded in the OGG/Vorbis file. * \return A new filestream. */ static struct cw_filestream *ogg_vorbis_rewrite(FILE *fp, const char *comment) { ogg_packet header; ogg_packet header_comm; ogg_packet header_code; struct cw_filestream *tmp; if ((tmp = malloc(sizeof(struct cw_filestream)))) { memset(tmp, 0, sizeof(struct cw_filestream)); tmp->writing = 1; tmp->fp = fp; vorbis_info_init(&tmp->vi); if (vorbis_encode_init_vbr(&tmp->vi, 1, 8000, 0.4)) { cw_log(LOG_ERROR, "Unable to initialize Vorbis encoder!\n"); free(tmp); return NULL; } vorbis_comment_init(&tmp->vc); vorbis_comment_add_tag(&tmp->vc, "ENCODER", "CallWeaver"); if (comment) vorbis_comment_add_tag(&tmp->vc, "COMMENT", (char *) comment); vorbis_analysis_init(&tmp->vd, &tmp->vi); vorbis_block_init(&tmp->vd, &tmp->vb); ogg_stream_init(&tmp->os, rand()); vorbis_analysis_headerout(&tmp->vd, &tmp->vc, &header, &header_comm, &header_code); ogg_stream_packetin(&tmp->os, &header); ogg_stream_packetin(&tmp->os, &header_comm); ogg_stream_packetin(&tmp->os, &header_code); while (!tmp->eos) { if (ogg_stream_flush(&tmp->os, &tmp->og) == 0) break; fwrite(tmp->og.header, 1, tmp->og.header_len, tmp->fp); fwrite(tmp->og.body, 1, tmp->og.body_len, tmp->fp); if (ogg_page_eos(&tmp->og)) tmp->eos = 1; } if (cw_mutex_lock(&ogg_vorbis_lock)) { cw_log(LOG_WARNING, "Unable to lock ogg_vorbis list\n"); fclose(fp); ogg_stream_clear(&tmp->os); vorbis_block_clear(&tmp->vb); vorbis_dsp_clear(&tmp->vd); vorbis_comment_clear(&tmp->vc); vorbis_info_clear(&tmp->vi); free(tmp); return NULL; } glistcnt++; cw_mutex_unlock(&ogg_vorbis_lock); cw_update_use_count(); } return tmp; }
/* The following function is basically a hacked version of the code in * examples/encoder_example.c */ void write_vorbis_data_or_die (const char *filename, int srate, float q, const float * data, int count, int ch) { FILE * file ; ogg_stream_state os; ogg_page og; ogg_packet op; vorbis_info vi; vorbis_comment vc; vorbis_dsp_state vd; vorbis_block vb; int eos = 0, ret; if ((file = fopen (filename, "wb")) == NULL) { printf("\n\nError : fopen failed : %s\n", strerror (errno)) ; exit (1) ; } /********** Encode setup ************/ vorbis_info_init (&vi); ret = vorbis_encode_init_vbr (&vi,ch,srate,q); if (ret) { printf ("vorbis_encode_init_vbr return %d\n", ret) ; exit (1) ; } vorbis_comment_init (&vc); vorbis_comment_add_tag (&vc,"ENCODER","test/util.c"); vorbis_analysis_init (&vd,&vi); vorbis_block_init (&vd,&vb); ogg_stream_init (&os,12345678); { ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout (&vd,&vc,&header,&header_comm,&header_code); ogg_stream_packetin (&os,&header); ogg_stream_packetin (&os,&header_comm); ogg_stream_packetin (&os,&header_code); /* Ensures the audio data will start on a new page. */ while (!eos){ int result = ogg_stream_flush (&os,&og); if (result == 0) break; fwrite (og.header,1,og.header_len,file); fwrite (og.body,1,og.body_len,file); } } { /* expose the buffer to submit data */ float **buffer = vorbis_analysis_buffer (&vd,count); int i; for(i=0;i<ch;i++) memcpy (buffer [i], data, count * sizeof (float)) ; /* tell the library how much we actually submitted */ vorbis_analysis_wrote (&vd,count); vorbis_analysis_wrote (&vd,0); } while (vorbis_analysis_blockout (&vd,&vb) == 1) { vorbis_analysis (&vb,NULL); vorbis_bitrate_addblock (&vb); while (vorbis_bitrate_flushpacket (&vd,&op)) { ogg_stream_packetin (&os,&op); while (!eos) { int result = ogg_stream_pageout (&os,&og); if (result == 0) break; fwrite (og.header,1,og.header_len,file); fwrite (og.body,1,og.body_len,file); if (ogg_page_eos (&og)) eos = 1; } } } ogg_stream_clear (&os); vorbis_block_clear (&vb); vorbis_dsp_clear (&vd); vorbis_comment_clear (&vc); vorbis_info_clear (&vi); fclose (file) ; }
gboolean ucil_theora_combine_av_file( const char *path, const char *codec, gboolean remove, ucil_processing_info_func_t procfunc, void *func_data, GError **error ) { FILE *f; FILE *af; FILE *vf; gchar *apath; gchar *vpath; long len; long filepos = 0; ogg_sync_state oy; ogg_stream_state tins; theora_comment tc; theora_info ti; theora_state ts; ogg_stream_state vs; vorbis_info vi; vorbis_comment vc; vorbis_dsp_state vd; vorbis_block vb; ogg_page og; ogg_packet op; ogg_packet header_comm; ogg_packet header_code; int pkt; double videopos, audiopos; f = fopen( path, "w" ); if( !f ) { gchar *name = g_filename_display_name( path ); g_set_error( error, G_FILE_ERROR, g_file_error_from_errno( errno ), _("Could not open '%s' for writing: %s"), name, g_strerror( errno ) ); g_free( name ); return FALSE; } apath = g_strconcat( path, ".atmp", NULL ); af = fopen( apath, "r" ); if( !af ) { gchar *name = g_filename_display_name( apath ); g_set_error( error, G_FILE_ERROR, g_file_error_from_errno( errno ), _("Could not open '%s' for reading: %s"), name, g_strerror( errno ) ); g_free( name ); g_free( apath ); fclose( f ); return FALSE; } vpath = g_strconcat( path, ".vtmp", NULL ); vf = fopen( vpath, "r" ); if( !vf ) { gchar *name = g_filename_display_name( vpath ); g_set_error( error, G_FILE_ERROR, g_file_error_from_errno( errno ), _("Could not open '%s' for reading: %s"), name, g_strerror( errno ) ); g_free( name ); g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); return FALSE; } fseek( af, 0L, SEEK_END ); len = ftell( af ); fseek( af, 0L, SEEK_SET ); ogg_sync_init( &oy ); theora_comment_init( &tc ); theora_info_init( &ti ); if( ogg_stream_init( &vs, 2 ) != 0 ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Failed to initialize audio stream") ); return FALSE; } vorbis_info_init( &vi ); if( vorbis_encode_init( &vi, 2, 44100, -1, 128000, -1 ) ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Failed to initialize audio encoder") ); return FALSE; } vorbis_comment_init( &vc ); vorbis_analysis_init( &vd, &vi ); vorbis_block_init( &vd, &vb ); // // write theora header page // { ogg_page og; while( ogg_sync_pageout( &oy, &og ) == 0 ) { int bytes; bytes = buffer_data( vf, &oy ); if( bytes == 0 ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Invalid video stream") ); return FALSE; } } if( !ogg_page_bos( &og ) ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Invalid video stream") ); return FALSE; } ogg_stream_init( &tins, ogg_page_serialno( &og ) ); fwrite( og.header, 1, og.header_len, f ); fwrite( og.body, 1, og.body_len, f ); if( ogg_stream_pagein( &tins, &og ) < 0 ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Invalid video stream") ); return FALSE; } pkt = 0; while( ( pkt < 3 ) && ( ogg_stream_packetout( &tins, &op ) > 0 ) ) { if( theora_decode_header( &ti, &tc, &op ) != 0 ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Invalid video stream") ); return FALSE; } pkt++; } } // // Write vorbis header page // vorbis_analysis_headerout( &vd, &vc, &op, &header_comm, &header_code ); ogg_stream_packetin( &vs, &op ); if( ogg_stream_pageout( &vs, &og ) != 1 ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Could not create audio stream") ); return FALSE; } fwrite( og.header, 1, og.header_len, f ); fwrite( og.body, 1, og.body_len, f ); ogg_stream_packetin( &vs, &header_comm ); ogg_stream_packetin( &vs, &header_code ); // write remaining theora headers for( pkt = 1; pkt < 3; ) { ogg_page og; if( ogg_sync_pageout( &oy, &og ) > 0 ) { fwrite( og.header, 1, og.header_len, f ); fwrite( og.body, 1, og.body_len, f ); if( ogg_stream_pagein( &tins, &og ) < 0 ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Invalid video stream") ); return FALSE; } while( ( pkt < 3 ) && ( ogg_stream_packetout( &tins, &op ) > 0 ) ) { if( theora_decode_header( &ti, &tc, &op ) != 0 ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Invalid video stream") ); return FALSE; } pkt++; } } else { int bytes; bytes = buffer_data( vf, &oy ); if( bytes == 0 ) { g_free( apath ); g_free( vpath ); fclose( f ); fclose( af ); fclose( vf ); g_set_error( error, UCIL_ERROR, UCIL_ERROR_INVALID_STREAM, _("Invalid video stream") ); return FALSE; } } } theora_decode_init( &ts, &ti ); // // Write remaining vorbis headers // while( ogg_stream_flush( &vs, &og ) > 0 ) { fwrite( og.header, 1, og.header_len, f ); fwrite( og.body, 1, og.body_len, f ); } audiopos = 0.0; videopos = 0.0; while( !feof( af ) ) { signed char abuf[512 * 4]; int n_samples; if( feof( vf ) || ( audiopos <= videopos ) ) { n_samples = fread( abuf, 4, 512, af ); audiopos = encode_vorbis( f, &vd, &vs, &vb, 44100, audiopos, abuf, n_samples ); filepos += n_samples * 4; } else { buffer_data( vf, &oy ); if( ogg_sync_pageout( &oy, &og ) > 0 ) { double tmppos; fwrite( og.header, 1, og.header_len, f ); fwrite( og.body, 1, og.body_len, f ); if( ogg_stream_pagein( &tins, &og ) < 0 ) { TRACE( "failed to decode theora\n" ); } ogg_stream_packetout( &tins, &op ); tmppos = theora_granule_time( &ts, ogg_page_granulepos( &og ) ); if( tmppos > 0 ) { videopos = tmppos; } } } if( procfunc ) { procfunc( func_data, (double)filepos/(double)len ); } } while( !feof( vf ) && buffer_data( vf, &oy ) ) { if( ogg_sync_pageout( &oy, &og ) > 0 ) { fwrite( og.header, 1, og.header_len, f ); fwrite( og.body, 1, og.body_len, f ); } } if( remove ) { unlink( vpath ); unlink( apath ); } g_free( vpath ); g_free( apath ); fclose( f ); fclose( af ); fclose( vf ); return TRUE; }
/*------------------------------------------------------------------------------ * Open an encoding session *----------------------------------------------------------------------------*/ bool VorbisLibEncoder :: open ( void ) throw ( Exception ) { int ret; if ( isOpen() ) { close(); } vorbis_info_init( &vorbisInfo); switch ( getOutBitrateMode() ) { case cbr: ret = vorbis_encode_setup_managed( &vorbisInfo, getInChannel(), getOutSampleRate(), -1, getOutBitrate() * 1000, -1) || vorbis_encode_ctl( &vorbisInfo, OV_ECTL_RATEMANAGE_AVG, NULL) || vorbis_encode_setup_init( &vorbisInfo); if ( ret ) { throw Exception( __FILE__, __LINE__, "vorbis encode init error", ret); } break; case abr: if ( (ret = vorbis_encode_init( &vorbisInfo, getInChannel(), getOutSampleRate(), -1, getOutBitrate() * 1000, -1 )) ) { throw Exception( __FILE__, __LINE__, "vorbis encode init error", ret); } break; case vbr: if ( (ret = vorbis_encode_init_vbr( &vorbisInfo, getInChannel(), getOutSampleRate(), getOutQuality() )) ) { throw Exception( __FILE__, __LINE__, "vorbis encode init error", ret); } break; } if ( (ret = vorbis_analysis_init( &vorbisDspState, &vorbisInfo)) ) { throw Exception( __FILE__, __LINE__, "vorbis analysis init error", ret); } if ( (ret = vorbis_block_init( &vorbisDspState, &vorbisBlock)) ) { throw Exception( __FILE__, __LINE__, "vorbis block init error", ret); } if ( (ret = ogg_stream_init( &oggStreamState, 0)) ) { throw Exception( __FILE__, __LINE__, "ogg stream init error", ret); } // open the underlying sink if ( !sink->open() ) { throw Exception( __FILE__, __LINE__, "vorbis lib opening underlying sink error"); } // create an empty vorbis_comment structure vorbis_comment_init( &vorbisComment); // create the vorbis stream headers and send them to the underlying sink ogg_packet header; ogg_packet commentHeader; ogg_packet codeHeader; if ( (ret = vorbis_analysis_headerout( &vorbisDspState, &vorbisComment, &header, &commentHeader, &codeHeader )) ) { throw Exception( __FILE__, __LINE__, "vorbis header init error", ret); } ogg_stream_packetin( &oggStreamState, &header); ogg_stream_packetin( &oggStreamState, &commentHeader); ogg_stream_packetin( &oggStreamState, &codeHeader); ogg_page oggPage; while ( ogg_stream_flush( &oggStreamState, &oggPage) ) { sink->write( oggPage.header, oggPage.header_len); sink->write( oggPage.body, oggPage.body_len); } vorbis_comment_clear( &vorbisComment ); // initialize the resampling coverter if needed if ( converter ) { converter->initialize( resampleRatio, getInChannel()); } encoderOpen = true; return true; }
const char * _edje_multisense_encode_to_ogg_vorbis(char *snd_path, double quality, SF_INFO sfinfo) { ogg_stream_state os; /* take physical pages, weld into a logical stream of packets */ ogg_page og; /* one Ogg bitstream page. Vorbis packets are inside */ ogg_packet op; /* one raw packet of data for decode */ vorbis_info vi; /* struct that stores all the static vorbis bitstream settings */ vorbis_comment vc; /* struct that stores all the user comments */ vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */ vorbis_block vb; /* local working space for packet->PCM decode */ int eos = 0, ret; char *tmp; SNDFILE *sfile; FILE *fout; sfile = sf_open(snd_path, SFM_READ, &sfinfo); if (!sfile) return NULL; if (!sf_format_check(&sfinfo)) { sf_close(sfile); return NULL; } tmp = malloc(strlen(snd_path) + 1 + 4); if (!tmp) { sf_close(sfile); return NULL; } strcpy(tmp, snd_path); snd_path = tmp; strcat(snd_path, ".ogg"); fout = fopen(snd_path, "wb"); if (!fout) { free(snd_path); sf_close(sfile); return NULL; } /********** Encode setup ************/ vorbis_info_init(&vi); ret = vorbis_encode_init(&vi, sfinfo.channels, sfinfo.samplerate, -1, (long)(quality * 1000), -1); if (ret == OV_EFAULT) printf("OV_EFAULT\n"); if (ret == OV_EINVAL) printf("OV_EINVAL\n"); if (ret == OV_EIMPL) printf("OV_EIMPL\n"); if (ret) { fclose(fout); free(snd_path); sf_close(sfile); return NULL; } /* add a comment */ vorbis_comment_init(&vc); vorbis_comment_add_tag(&vc, "", ""); /* set up the analysis state and auxiliary encoding storage */ vorbis_analysis_init(&vd, &vi); vorbis_block_init(&vd, &vb); srand(time(NULL)); ogg_stream_init(&os, rand()); ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout(&vd, &vc, &header, &header_comm, &header_code); ogg_stream_packetin(&os, &header); /* automatically placed in its own page */ ogg_stream_packetin(&os, &header_comm); ogg_stream_packetin(&os, &header_code); while (!eos) { int result = ogg_stream_flush(&os, &og); if (!result) break; fwrite(og.header, 1, og.header_len, fout); fwrite(og.body, 1, og.body_len, fout); } while (!eos) { int i, ch; float readbuffer[READBUF * 2]; sf_count_t count; count = sf_readf_float(sfile, readbuffer, READBUF); if (!count) vorbis_analysis_wrote(&vd, 0); else { float **buffer = vorbis_analysis_buffer(&vd, count); /* uninterleave samples */ for (i = 0; i < count; i++) { for (ch = 0; ch < sfinfo.channels; ch++) buffer[ch][i]= readbuffer[(i * sfinfo.channels) + ch]; } vorbis_analysis_wrote(&vd, i); } while (vorbis_analysis_blockout(&vd, &vb) == 1) { vorbis_analysis(&vb, NULL); vorbis_bitrate_addblock(&vb); while (vorbis_bitrate_flushpacket(&vd, &op)) { ogg_stream_packetin(&os, &op); while (!eos) { int result = ogg_stream_pageout(&os, &og); if (!result) break; fwrite(og.header, 1, og.header_len, fout); fwrite(og.body, 1, og.body_len, fout); if (ogg_page_eos(&og)) eos = 1; } } } } ogg_stream_clear(&os); vorbis_block_clear(&vb); vorbis_dsp_clear(&vd); vorbis_comment_clear(&vc); vorbis_info_clear(&vi); sf_close(sfile); fclose (fout); return snd_path; }
virtual bool Cook(FName Format, const TArray<uint8>& SrcBuffer, FSoundQualityInfo& QualityInfo, TArray<uint8>& CompressedDataStore) const override { check(Format == NAME_OGG); #if WITH_OGGVORBIS { short ReadBuffer[SAMPLES_TO_READ * SAMPLE_SIZE * 2]; ogg_stream_state os; // take physical pages, weld into a logical stream of packets ogg_page og; // one ogg bitstream page. Vorbis packets are inside ogg_packet op; // one raw packet of data for decode vorbis_info vi; // struct that stores all the static vorbis bitstream settings vorbis_comment vc; // struct that stores all the user comments vorbis_dsp_state vd; // central working state for the packet->PCM decoder vorbis_block vb; // local working space for packet->PCM decode uint32 i; bool eos; // Create a buffer to store compressed data CompressedDataStore.Empty(); FMemoryWriter CompressedData( CompressedDataStore ); uint32 BufferOffset = 0; float CompressionQuality = ( float )( QualityInfo.Quality * VORBIS_QUALITY_MODIFIER ) / 100.0f; CompressionQuality = FMath::Clamp( CompressionQuality, -0.1f, 1.0f ); vorbis_info_init( &vi ); if( vorbis_encode_init_vbr( &vi, QualityInfo.NumChannels, QualityInfo.SampleRate, CompressionQuality ) ) { return false; } // add a comment vorbis_comment_init( &vc ); vorbis_comment_add_tag( &vc, "ENCODER", "UnrealEngine4" ); // set up the analysis state and auxiliary encoding storage vorbis_analysis_init( &vd, &vi ); vorbis_block_init( &vd, &vb ); // set up our packet->stream encoder ogg_stream_init( &os, 0 ); ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout( &vd, &vc, &header, &header_comm, &header_code); ogg_stream_packetin( &os, &header ); ogg_stream_packetin( &os, &header_comm ); ogg_stream_packetin( &os, &header_code ); // This ensures the actual audio data will start on a new page, as per spec while( true ) { int result = ogg_stream_flush( &os, &og ); if( result == 0 ) { break; } CompressedData.Serialize( og.header, og.header_len ); CompressedData.Serialize( og.body, og.body_len ); } eos = false; while( !eos ) { // Read samples uint32 BytesToRead = FMath::Min( SAMPLES_TO_READ * QualityInfo.NumChannels * SAMPLE_SIZE, QualityInfo.SampleDataSize - BufferOffset ); FMemory::Memcpy( ReadBuffer, SrcBuffer.GetData() + BufferOffset, BytesToRead ); BufferOffset += BytesToRead; if( BytesToRead == 0) { // end of file vorbis_analysis_wrote( &vd, 0 ); } else { // expose the buffer to submit data float **buffer = vorbis_analysis_buffer( &vd, SAMPLES_TO_READ ); if( QualityInfo.NumChannels == 1 ) { for( i = 0; i < BytesToRead / SAMPLE_SIZE; i++ ) { buffer[0][i] = ( ReadBuffer[i] ) / 32768.0f; } } else { for( i = 0; i < BytesToRead / ( SAMPLE_SIZE * 2 ); i++ ) { buffer[0][i] = ( ReadBuffer[i * 2] ) / 32768.0f; buffer[1][i] = ( ReadBuffer[i * 2 + 1] ) / 32768.0f; } } // tell the library how many samples we actually submitted vorbis_analysis_wrote( &vd, i ); } // vorbis does some data preanalysis, then divvies up blocks for more involved (potentially parallel) processing. while( vorbis_analysis_blockout( &vd, &vb ) == 1 ) { // analysis, assume we want to use bitrate management vorbis_analysis( &vb, NULL ); vorbis_bitrate_addblock( &vb ); while( vorbis_bitrate_flushpacket( &vd, &op ) ) { // weld the packet into the bitstream ogg_stream_packetin( &os, &op ); // write out pages (if any) while( !eos ) { int result = ogg_stream_pageout( &os, &og ); if( result == 0 ) { break; } CompressedData.Serialize( og.header, og.header_len ); CompressedData.Serialize( og.body, og.body_len ); // this could be set above, but for illustrative purposes, I do it here (to show that vorbis does know where the stream ends) if( ogg_page_eos( &og ) ) { eos = true; } } } } } // clean up and exit. vorbis_info_clear() must be called last ogg_stream_clear( &os ); vorbis_block_clear( &vb ); vorbis_dsp_clear( &vd ); vorbis_comment_clear( &vc ); vorbis_info_clear( &vi ); // ogg_page and ogg_packet structs always point to storage in libvorbis. They're never freed or manipulated directly } return CompressedDataStore.Num() > 0; #else return false; #endif // WITH_OGGVOBVIS }
static int ogg_write_header (SF_PRIVATE *psf, int UNUSED (calc_length)) { OGG_PRIVATE *odata = (OGG_PRIVATE *) psf->container_data ; VORBIS_PRIVATE *vdata = (VORBIS_PRIVATE *) psf->codec_data ; int k, ret ; vorbis_info_init (&vdata->vi) ; /* The style of encoding should be selectable here, VBR quality mode. */ ret = vorbis_encode_init_vbr (&vdata->vi, psf->sf.channels, psf->sf.samplerate, vdata->quality) ; #if 0 ret = vorbis_encode_init (&vdata->vi, psf->sf.channels, psf->sf.samplerate, -1, 128000, -1) ; /* average bitrate mode */ ret = ( vorbis_encode_setup_managed (&vdata->vi, psf->sf.channels, psf->sf.samplerate, -1, 128000, -1) || vorbis_encode_ctl (&vdata->vi, OV_ECTL_RATEMANAGE_AVG, NULL) || vorbis_encode_setup_init (&vdata->vi)) ; #endif if (ret) return SFE_BAD_OPEN_FORMAT ; vdata->loc = 0 ; /* add a comment */ vorbis_comment_init (&vdata->vc) ; vorbis_comment_add_tag (&vdata->vc, "ENCODER", "libsndfile") ; for (k = 0 ; k < SF_MAX_STRINGS ; k++) { const char * name ; if (psf->strings [k].type == 0) break ; switch (psf->strings [k].type) { case SF_STR_TITLE : name = "TITLE" ; break ; case SF_STR_COPYRIGHT : name = "COPYRIGHT" ; break ; case SF_STR_SOFTWARE : name = "SOFTWARE" ; break ; case SF_STR_ARTIST : name = "ARTIST" ; break ; case SF_STR_COMMENT : name = "COMMENT" ; break ; case SF_STR_DATE : name = "DATE" ; break ; case SF_STR_ALBUM : name = "ALBUM" ; break ; case SF_STR_LICENSE : name = "LICENSE" ; break ; default : continue ; } ; vorbis_comment_add_tag (&vdata->vc, name, psf->strings [k].str) ; } ; /* set up the analysis state and auxiliary encoding storage */ vorbis_analysis_init (&vdata->vd, &vdata->vi) ; vorbis_block_init (&vdata->vd, &vdata->vb) ; /* ** Set up our packet->stream encoder. ** Pick a random serial number ; that way we can more likely build ** chained streams just by concatenation. */ ogg_stream_init (&odata->os, psf_rand_int32 ()) ; /* Vorbis streams begin with three headers ; the initial header (with most of the codec setup parameters) which is mandated by the Ogg bitstream spec. The second header holds any comment fields. The third header holds the bitstream codebook. We merely need to make the headers, then pass them to libvorbis one at a time ; libvorbis handles the additional Ogg bitstream constraints */ { ogg_packet header ; ogg_packet header_comm ; ogg_packet header_code ; int result ; vorbis_analysis_headerout (&vdata->vd, &vdata->vc, &header, &header_comm, &header_code) ; ogg_stream_packetin (&odata->os, &header) ; /* automatically placed in its own page */ ogg_stream_packetin (&odata->os, &header_comm) ; ogg_stream_packetin (&odata->os, &header_code) ; /* This ensures the actual * audio data will start on a new page, as per spec */ while ((result = ogg_stream_flush (&odata->os, &odata->og)) != 0) { psf_fwrite (odata->og.header, 1, odata->og.header_len, psf) ; psf_fwrite (odata->og.body, 1, odata->og.body_len, psf) ; } ; } return 0 ; } /* ogg_write_header */
/** \fn initialize */ bool AUDMEncoder_Vorbis::initialize(void) { int ret; ogg_packet header1,header2,header3; int err; vorbis_info_init(&VI) ; switch(_config.mode) { case ADM_VORBIS_VBR: err=vorbis_encode_init(&VI, wavheader.channels, wavheader.frequency, -1, // Max bitrate _config.bitrate*1000, //long nominal_bitrate, -1 //long min_bitrate)) ); break; case ADM_VORBIS_QUALITY : err=vorbis_encode_init_vbr(&VI, wavheader.channels, wavheader.frequency, _config.quality/10 ); break; default: ADM_assert(0); } if (err!=0) { delete (vorbisStruct*)_handle; _handle = NULL; printf("[vorbis] init error %d\n",err); return 0; } vorbis_analysis_init(&VD, &VI) ; vorbis_block_init(&VD, &VB); vorbis_comment_init(&VC); vorbis_comment_add_tag(&VC, "encoder", "AVIDEMUX2") ; vorbis_analysis_headerout(&VD, &VC, &header1, &header2, &header3); // Store all headers as extra data // see ogg vorbis decode for details // we need 3 packets _extraSize=header1.bytes+header2.bytes+header3.bytes+3*sizeof(uint32_t); _extraData=new uint8_t[_extraSize]; uint32_t *ex=(uint32_t *)_extraData; uint8_t *d; d=_extraData+sizeof(uint32_t)*3; ex[0]=header1.bytes; ex[1]=header2.bytes; ex[2]=header3.bytes; memcpy(d,header1.packet,ex[0]); d+=ex[0]; memcpy(d,header2.packet,ex[1]); d+=ex[1]; memcpy(d,header3.packet,ex[2]); vorbis_comment_clear(&VC); printf("\n[Vorbis]Vorbis encoder initialized\n"); switch(_config.mode) { case ADM_VORBIS_VBR: printf("[Vorbis]CBR Bitrate:%"PRIu32"\n",_config.bitrate); break; case ADM_VORBIS_QUALITY: //FIXME FIXME FIXME printf("[Vorbis]VBR Quality:%.1f\n",_config.quality); break; default: ADM_assert(0); } printf("[Vorbis]Channels :%"PRIu32"\n",wavheader.channels); printf("[Vorbis]Frequency :%"PRIu32"\n",wavheader.frequency); return 1; }
static GstFlowReturn gst_vorbis_enc_handle_frame (GstAudioEncoder * enc, GstBuffer * buffer) { GstVorbisEnc *vorbisenc; GstFlowReturn ret = GST_FLOW_OK; GstMapInfo map; gfloat *ptr; gulong size; gulong i, j; float **vorbis_buffer; GstBuffer *buf1, *buf2, *buf3; vorbisenc = GST_VORBISENC (enc); if (G_UNLIKELY (!vorbisenc->setup)) { if (buffer) { GST_DEBUG_OBJECT (vorbisenc, "forcing setup"); /* should not fail, as setup before same way */ if (!gst_vorbis_enc_setup (vorbisenc)) return GST_FLOW_ERROR; } else { /* end draining */ GST_LOG_OBJECT (vorbisenc, "already drained"); return GST_FLOW_OK; } } if (!vorbisenc->header_sent) { /* Vorbis streams begin with three headers; the initial header (with most of the codec setup parameters) which is mandated by the Ogg bitstream spec. The second header holds any comment fields. The third header holds the bitstream codebook. We merely need to make the headers, then pass them to libvorbis one at a time; libvorbis handles the additional Ogg bitstream constraints */ ogg_packet header; ogg_packet header_comm; ogg_packet header_code; GstCaps *caps; GList *headers; GST_DEBUG_OBJECT (vorbisenc, "creating and sending header packets"); gst_vorbis_enc_set_metadata (vorbisenc); vorbis_analysis_headerout (&vorbisenc->vd, &vorbisenc->vc, &header, &header_comm, &header_code); vorbis_comment_clear (&vorbisenc->vc); /* create header buffers */ buf1 = gst_vorbis_enc_buffer_from_header_packet (vorbisenc, &header); buf2 = gst_vorbis_enc_buffer_from_header_packet (vorbisenc, &header_comm); buf3 = gst_vorbis_enc_buffer_from_header_packet (vorbisenc, &header_code); /* mark and put on caps */ caps = gst_caps_new_simple ("audio/x-vorbis", "rate", G_TYPE_INT, vorbisenc->frequency, "channels", G_TYPE_INT, vorbisenc->channels, NULL); caps = _gst_caps_set_buffer_array (caps, "streamheader", buf1, buf2, buf3, NULL); /* negotiate with these caps */ GST_DEBUG_OBJECT (vorbisenc, "here are the caps: %" GST_PTR_FORMAT, caps); gst_audio_encoder_set_output_format (GST_AUDIO_ENCODER (vorbisenc), caps); gst_caps_unref (caps); /* store buffers for later pre_push sending */ headers = NULL; GST_DEBUG_OBJECT (vorbisenc, "storing header buffers"); headers = g_list_prepend (headers, buf3); headers = g_list_prepend (headers, buf2); headers = g_list_prepend (headers, buf1); gst_audio_encoder_set_headers (enc, headers); vorbisenc->header_sent = TRUE; } if (!buffer) return gst_vorbis_enc_clear (vorbisenc); gst_buffer_map (buffer, &map, GST_MAP_WRITE); /* data to encode */ size = map.size / (vorbisenc->channels * sizeof (float)); ptr = (gfloat *) map.data; /* expose the buffer to submit data */ vorbis_buffer = vorbis_analysis_buffer (&vorbisenc->vd, size); /* deinterleave samples, write the buffer data */ if (vorbisenc->channels < 2 || vorbisenc->channels > 8) { for (i = 0; i < size; i++) { for (j = 0; j < vorbisenc->channels; j++) { vorbis_buffer[j][i] = *ptr++; } } } else { gint i, j; /* Reorder */ for (i = 0; i < size; i++) { for (j = 0; j < vorbisenc->channels; j++) { vorbis_buffer[gst_vorbis_reorder_map[vorbisenc->channels - 1][j]][i] = ptr[j]; } ptr += vorbisenc->channels; } } /* tell the library how much we actually submitted */ vorbis_analysis_wrote (&vorbisenc->vd, size); gst_buffer_unmap (buffer, &map); GST_LOG_OBJECT (vorbisenc, "wrote %lu samples to vorbis", size); vorbisenc->samples_in += size; ret = gst_vorbis_enc_output_buffers (vorbisenc); return ret; }
static int ogg_output_open(const char *fname, const char *comment) { int fd; static vorbis_info ogg_info; vorbis_info *vi; /* struct that stores all the static vorbis bitstream settings */ vorbis_comment vc; /* struct that stores all the user comments */ if(strcmp(fname, "-") == 0) { fd = 1; /* data to stdout */ if(comment == NULL) comment = "(stdout)"; } else { /* Open the audio file */ fd = open(fname, FILE_OUTPUT_MODE); if(fd < 0) { ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: %s", fname, strerror(errno)); return -1; } if(comment == NULL) comment = fname; } /* choose an encoding mode */ /* (mode 0: 44kHz stereo uncoupled, roughly 128kbps VBR) */ memcpy(&ogg_info, &info_A, sizeof(ogg_info)); if(dpm.encoding & PE_MONO) ogg_info.channels = 1; else ogg_info.channels = 2; ogg_info.rate = dpm.rate; vi = &ogg_info; /* add a comment */ vorbis_comment_init(&vc); vorbis_comment_add(&vc, (char *)comment); /* set up the analysis state and auxiliary encoding storage */ vorbis_analysis_init(&vd, vi); vorbis_block_init(&vd, &vb); /* set up our packet->stream encoder */ /* pick a random serial number; that way we can more likely build chained streams just by concatenation */ srand(time(NULL)); ogg_stream_init(&os, rand()); /* Vorbis streams begin with three headers; the initial header (with most of the codec setup parameters) which is mandated by the Ogg bitstream spec. The second header holds any comment fields. The third header holds the bitstream codebook. We merely need to make the headers, then pass them to libvorbis one at a time; libvorbis handles the additional Ogg bitstream constraints */ { ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout(&vd, &vc, &header, &header_comm, &header_code); ogg_stream_packetin(&os, &header); /* automatically placed in its own page */ ogg_stream_packetin(&os, &header_comm); ogg_stream_packetin(&os, &header_code); /* no need to write out here. We'll get to that in the main loop */ } return fd; }