/* * wave_get: * --------- * Expects an interleaved 16bit pcm stream from read_samples, which it * de-interleaves into buffer. */ int wave_get(int16_t buffer[2][samp_per_frame], wave_t *wave, void *config_in) { FILE *file = wave->file; static int16_t temp_buf[2304]; int samples_read; int j; shine_config_t *config=config_in; switch(config->mpeg.mode) { case MODE_MONO : samples_read = read_samples(temp_buf,(int)samp_per_frame, file); for(j=0;j<samp_per_frame;j++) { buffer[0][j] = temp_buf[j]; buffer[1][j] = 0; } break; default: /* stereo */ samples_read = read_samples(temp_buf,(int)samp_per_frame<<1, file); for(j=0;j<samp_per_frame;j++) { buffer[0][j] = temp_buf[2*j]; buffer[1][j] = temp_buf[2*j+1]; } } return samples_read; }
int wave_get(short buffer[2][samp_per_frame]) /* expects an interleaved 16bit pcm stream from read_samples, which it */ /* de-interleaves into buffer */ { static short temp_buf[2304]; int samples_read; int j; switch(config.mpeg.mode) { case MODE_MONO : samples_read = read_samples(temp_buf,config.mpeg.samples_per_frame); for(j=0;j<samp_per_frame;j++) { buffer[0][j] = temp_buf[j]; buffer[1][j] = 0; } break; default: samples_read = read_samples(temp_buf,config.mpeg.samples_per_frame<<1); for(j=0;j<samp_per_frame;j++) { buffer[0][j] = temp_buf[2*j]; buffer[1][j] = temp_buf[2*j+1]; } } return samples_read; }
static void fill_buffer (sfx_t *sfx, sfxstream_t *stream, sfxbuffer_t *buffer, wavinfo_t *info, unsigned int headpos) { unsigned int samples; unsigned int loop_samples = 0; // find out how many samples can be read into the buffer samples = buffer->tail - buffer->head - SAMPLE_GAP; if (buffer->tail <= buffer->head) samples += buffer->length; if (headpos + samples > sfx->length) { if (sfx->loopstart == (unsigned int)-1) { samples = sfx->length - headpos; } else { loop_samples = headpos + samples - sfx->length; samples -= loop_samples; } } if (samples) read_samples (buffer, samples); if (loop_samples) { stream->seek (stream, info->loopstart); read_samples (buffer, loop_samples); } }
static int read_subframe(const struct sr_dev_inst *sdi, uint8_t *buf) { struct dev_context *devc = sdi->priv; uint8_t sig[3], ctrl; unsigned int num; gboolean interleave; interleave = readout_steps[devc->step].interleave; ctrl = C1284_NSTROBE; if ((interleave && devc->adc2) || (!interleave && devc->channel == 2)) ctrl |= C1284_NAUTOFD; ieee1284_write_control(sdi->conn, ctrl); num = readout_steps[devc->step].num; if (num < 1000) skip_samples(sdi->conn, ctrl, 1000 - num); read_samples(sdi->conn, ctrl, buf + (devc->adc2 ? 1 : 0), num, interleave ? 2 : 1); read_samples(sdi->conn, ctrl, sig, 3, 1); if (sig[0] != 0x01 || sig[1] != 0xfe || sig[2] != 0x80) { if (--devc->retries) { sr_dbg("Missing signature at end of buffer, %i tries remaining", devc->retries); return TRUE; } else { sr_err("Failed to read frame without transfer errors"); devc->step = 0; } } else { if (interleave && !devc->adc2) { devc->adc2 = TRUE; devc->retries = MAX_RETRIES; return TRUE; } else { if (interleave) num *= 2; if (!devc->step) { struct sr_datafeed_packet packet = { .type = SR_DF_TRIGGER }; push_samples(sdi, buf, 6); sr_session_send(sdi, &packet); buf += 6; num -= 6; } push_samples(sdi, buf, num); if (++devc->step > devc->last_step) devc->step = 0; } } devc->adc2 = FALSE; devc->retries = MAX_RETRIES; return devc->step > 0; }
int OverlayAudio::process_buffer(int64_t size, Samples **buffer, int64_t start_position, int sample_rate) { load_configuration(); int output_track = 0; if(config.output_track == OverlayAudioConfig::BOTTOM) output_track = get_total_buffers() - 1; // Direct copy the output track read_samples(buffer[output_track], output_track, sample_rate, start_position, size); // Add remaining tracks Samples *output_buffer = buffer[output_track]; double *output_samples = output_buffer->get_data(); for(int i = 0; i < get_total_buffers(); i++) { if(i != output_track) { Samples *input_buffer = buffer[i]; read_samples(buffer[i], i, sample_rate, start_position, size); double *input_samples = input_buffer->get_data(); switch(config.mode) { case OverlayAudioConfig::ADD: for(int j = 0; j < size; j++) { output_samples[j] += input_samples[j]; } break; case OverlayAudioConfig::MULTIPLY: for(int j = 0; j < size; j++) { output_samples[j] *= input_samples[j]; } break; } } } return 0; }
int main(int argc,char *argv[]){ int i=0; srand(time(NULL)); net mlpnet; int layer_neurons[]={2,10,5,1}; char sigmods[]={'l','l','l','l'}; init_net(&mlpnet,4,layer_neurons,sigmods); float *inputs=(float*)malloc(sizeof(float)*2); sample *samples; int num_lines=count_lines(argv[1]); samples=(sample*)malloc(sizeof(sample)*num_lines); read_samples(argv[1],samples,num_lines); train(&mlpnet,num_lines,samples,EPOCHS); free_samples(samples,num_lines); //================================================== num_lines=count_lines(argv[2]); sample *test_samples=(sample*)malloc(sizeof(sample)*num_lines); read_samples(argv[2],test_samples,num_lines); float *scores=(float*)malloc(sizeof(float)*num_lines); predict(&mlpnet,num_lines,test_samples,scores); free_samples(test_samples,num_lines); free_net(&mlpnet,4,layer_neurons); char scorefile[100]; sprintf(scorefile,"%s.score",argv[1]); FILE *score=fopen(scorefile,"w"); for(i=0;i<num_lines;i++) { fprintf(score,"%f\n",scores[i]); } fclose(score); return 0; }
int InterpolateAllEffect::process_loop(double *buffer, long &write_length) { //printf("InterpolateAllEffect::process_loop 1\n"); int result = 0; if(state == READING) { // Read a certain amount before the first sample int leadin = PluginClient::in_buffer_size; //printf("InterpolateAllEffect::process_loop 2\n"); double buffer[leadin]; if(PluginClient::start - leadin < 0) leadin = PluginClient::start; read_samples(buffer, PluginClient::start - leadin, leadin); sample1 = buffer[leadin - 1]; // Read a certain amount before the last sample leadin = PluginClient::in_buffer_size; if(PluginClient::end - leadin < 0) leadin = PluginClient::end; read_samples(buffer, PluginClient::end - leadin, leadin); sample2 = buffer[leadin - 1]; state = WRITING; current_position = PluginClient::start; // Get slope and intercept slope = (sample2 - sample1) / (PluginClient::end - PluginClient::start); intercept = sample1; //printf("InterpolateAllEffect::process_loop 3\n"); } //printf("InterpolateAllEffect::process_loop 4\n"); int fragment_len = PluginClient::in_buffer_size; if(current_position + fragment_len > PluginClient::end) fragment_len = PluginClient::end - current_position; double intercept2 = intercept + slope * (current_position - PluginClient::start); for(int i = 0; i < fragment_len; i++) { buffer[i] = intercept2 + slope * i; } current_position += fragment_len; write_length = fragment_len; result = progress->update(PluginClient::end - PluginClient::start + current_position - PluginClient::start); if(current_position >= PluginClient::end) result = 1; //printf("InterpolateAllEffect::process_loop 5\n"); return result; }
void Java_com_iliayugai_zapp_utils_CommonUtils_encodeFile(JNIEnv *env, jobject jobj, jstring in_source_path, jstring in_target_path) { const char *source_path, *target_path; source_path = (*env)->GetStringUTFChars(env, in_source_path, NULL); target_path = (*env)->GetStringUTFChars(env, in_target_path, NULL); FILE *input_file, *output_file; input_file = fopen(source_path, "rb"); output_file = fopen(target_path, "wb"); short input[BUFFER_SIZE]; char output[BUFFER_SIZE]; int nb_read = 0; int nb_write = 0; int nb_total = 0; LOGD("Encoding started"); while (nb_read = read_samples(input_file, input)) { nb_write = lame_encode_buffer(lame, input, input, nb_read, output, BUFFER_SIZE); fwrite(output, nb_write, 1, output_file); nb_total += nb_write; } LOGD("Encoded %d bytes", nb_total); nb_write = lame_encode_flush(lame, output, BUFFER_SIZE); fwrite(output, nb_write, 1, output_file); LOGD("Flushed %d bytes", nb_write); fclose(input_file); fclose(output_file); }
// Quick test of functions int main() { Blip_Buffer buf; Blip_Synth<blip_low_quality,20> synth; // Setup buffer buf.clock_rate( 44100 ); if ( buf.set_sample_rate( 44100 ) ) return 1; synth.output( &buf ); synth.volume( 0.5 ); // Add wave that goes from 0 to 50% to -50% synth.update( 4, 10 ); synth.update( 8, -10 ); buf.end_frame( 30 ); // Read samples as this type typedef float sample_t; // floating-point //typedef unsigned short sample_t; // unsigned 16-bit //typedef unsigned char sample_t; // unsigned 8-bit // Read and display samples const int max_samples = 30; sample_t samples [max_samples]; int count = read_samples( buf, samples, max_samples ); for ( int i = buf.output_latency() + 1; i < count; i++ ) printf( "%.2f,", (double) samples [i] ); printf( "\n" ); return 0; }
/** * Parses the file. * */ static stan_csv parse(std::istream& in) { stan_csv data; if (!read_metadata(in, data.metadata)) { std::cout << "Warning: non-fatal error reading metadata" << std::endl; } if (!read_header(in, data.header)) { std::cout << "Error: error reading header" << std::endl; throw std::invalid_argument ("Error with header of input file in parse"); } if (!read_adaptation(in, data.adaptation)) { std::cout << "Warning: non-fatal error reading adapation data" << std::endl; } data.timing.warmup = 0; data.timing.sampling = 0; if (!read_samples(in, data.samples, data.timing)) { std::cout << "Warning: non-fatal error reading samples" << std::endl; } return data; }
/** * The main routine. */ int main(void) { unsigned char cnt = 0; unsigned char c; clock_init(); pin_reserve(PIN_1_1); pin_reserve(PIN_1_2); serial_init(BAUDRATE); setup(); for(;;) { c = serial_recv_blocking(); if(c == SCRATCH_DATA_REQUEST) { if(cnt++ == COMM_BLINK_RATE) { // blink COMM to show data was requested pin_toggle(COMM); cnt = 0; } read_samples(); xmit_samples(); } } return 0; }
int main (int argc, const char *argv[]) { CmdArgParser parser(argc, argv); parser.setHeader("Archive Benchmark\n"); parser.setArgumentsInfo("<index>"); CmdArgFlag old(parser, "old", "Use old directory file"); CmdArgInt samples(parser, "samples", "<count>", "Number of samples to write"); CmdArgString channel_name(parser, "channel", "<name>", "Channel Name"); CmdArgFlag do_read(parser, "read", "Perform read test"); // defaults samples.set(100000); channel_name.set("fred"); if (parser.parse() == false) return -1; if (parser.getArguments().size() != 1) { parser.usage(); return -1; } stdString index_name = parser.getArgument(0); size_t count; epicsTime start, stop; try { if (do_read) { start = epicsTime::getCurrent (); if (old) count = old_read_samples(index_name, channel_name.get()); else count = read_samples(index_name, channel_name.get()); stop = epicsTime::getCurrent (); } else { count = samples.get(); start = epicsTime::getCurrent (); if (old) old_write_samples(index_name, channel_name.get(), count); else write_samples(index_name, channel_name.get(), count); stop = epicsTime::getCurrent (); } double secs = stop - start; printf("%zd values in %g seconds: %g vals/sec\n", count, secs, (double)count / secs); } catch (GenericException &e) { fprintf(stderr, "Error:\n%s\n", e.what()); } return 0; }
static void read_samples (sfxbuffer_t *buffer, int count) { if (buffer->head + count > buffer->length) { count -= buffer->length - buffer->head; read_samples (buffer, buffer->length - buffer->head); read_samples (buffer, count); } else { sfx_t *sfx = buffer->sfx; sfxstream_t *stream = sfx->data.stream; wavinfo_t *info = &stream->wavinfo; float *data = buffer->data + buffer->head * info->channels; int c; if ((c = stream->read (stream, data, count)) != count) Sys_Printf ("%s nr %d %d\n", sfx->name, count, c); buffer->head += count; if (buffer->head >= buffer->length) buffer->head -= buffer->length; } }
static int genode_run_in(HWVoiceIn *hw) { GenodeVoiceIn *in = (GenodeVoiceIn*)hw; int const live = audio_pcm_hw_get_live_in(&in->hw); if (!(in->hw.samples - live)) return 0; int const dead = in->hw.samples - live; int const samples = read_samples(in, dead); in->hw.wpos = (in->hw.wpos + samples) % in->hw.samples; return samples; }
void DataReaderListenerImpl::on_data_available ( ::DDS::DataReader_ptr reader) { std::cerr << "Data is available.\n"; GuardType guard (this->lock_); ACE_CDR::ULong ts = read_samples (reader); this->stats_.sample_for_throughput (ts, false); if (this->stats_.ready_to_dump ()) { this->stats_.file_dump_throughput (); this->is_finished_ = true; } }
int main(int argc, char *argv[]) { /* Audio Setup */ SDL_AudioSpec *desired, *obtained; read_samples(); if (argc <= 1) { fprintf(stderr, "Must supply filename.\n"); return 1; } org = organya_open(argv[1]); session = organya_new_session(org); desired = (SDL_AudioSpec*)malloc(sizeof(SDL_AudioSpec)); obtained = (SDL_AudioSpec*)malloc(sizeof(SDL_AudioSpec)); desired->freq=22050; desired->format=AUDIO_S16LSB; // desired->format=AUDIO_S8; desired->channels=0; desired->samples=22050*org->wait_value/500; desired->callback=create_tone; desired->userdata=NULL; SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); /* Open the audio device */ if (SDL_OpenAudio(desired, obtained) < 0){ fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError()); return 1; } /* desired spec is no longer needed */ free(desired); desired=NULL; SDL_PauseAudio(0); getchar(); SDL_PauseAudio(1); SDL_Quit(); return EXIT_SUCCESS; }
int main(void) { header hdr_1; header hdr_2; read_header(&hdr_1); read_header(&hdr_2); sample data[MAX_ROWS]; size_t numrows = read_samples(MAX_ROWS, data); print_header("H1", &hdr_1); print_header("H2", &hdr_2); printf("Number of rows: %zu\n", numrows); for (size_t i = 0; i < numrows; i++) print_sample(i, &data[i]); return 0; }
int main(int argc, char** argv) { int i; for ( i=0 ; i < INSTRCOUNT ; i++ ) { toplevel[i].opcode = i; toplevel[i].count = 0; toplevel[i].left_child = NULL; toplevel[i].right_sibling = NULL; jumps[i] = 0; operands[i] = 0; iname[i] = "***"; } jumps[OP_throw] = 1; jumps[OP_ifnlt] = 1; jumps[OP_ifnle] = 1; jumps[OP_ifngt] = 1; jumps[OP_ifnge] = 1; jumps[OP_jump] = 1; jumps[OP_iftrue] = 1; jumps[OP_iffalse] = 1; jumps[OP_ifeq] = 1; jumps[OP_ifne] = 1; jumps[OP_iflt] = 1; jumps[OP_ifle] = 1; jumps[OP_ifgt] = 1; jumps[OP_ifge] = 1; jumps[OP_ifstricteq] = 1; jumps[OP_ifstrictne] = 1; jumps[OP_lookupswitch] = 1; jumps[OP_returnvoid] = 1; jumps[OP_returnvalue] = 1; /* The operand count here is not important for correctness. 0 is * always a safe answer, and a too high number will result in an * out-of-bounds reference only occasionally :-P * * Getting the operand count right makes for better analysis, * though. */ DEF(OP_bkpt, 0); DEF(OP_throw, 0); DEF(OP_getsuper, 1); DEF(OP_setsuper, 1); DEF(OP_dxns, 1); DEF(OP_dxnslate, 0); DEF(OP_kill, 1); DEF(OP_ifnlt, 1); DEF(OP_ifnle, 1); DEF(OP_ifngt, 1); DEF(OP_ifnge, 1); DEF(OP_jump, 1); DEF(OP_iftrue, 1); DEF(OP_iffalse, 1); DEF(OP_ifeq, 1); DEF(OP_ifne, 1); DEF(OP_iflt, 1); DEF(OP_ifle, 1); DEF(OP_ifgt, 1); DEF(OP_ifge, 1); DEF(OP_ifstricteq, 1); DEF(OP_ifstrictne, 1); DEF(OP_lookupswitch, 2); DEF(OP_pushwith, 0); DEF(OP_popscope, 0); DEF(OP_nextname, 0); DEF(OP_hasnext, 0); DEF(OP_pushnull, 0); DEF(OP_pushundefined, 0); DEF(OP_nextvalue, 0); DEF(OP_pushtrue, 0); DEF(OP_pushfalse, 0); DEF(OP_pushnan, 0); DEF(OP_pop, 0); DEF(OP_dup, 0); DEF(OP_swap, 0); DEF(OP_pushstring, 1); DEF(OP_pushdouble, 1); DEF(OP_pushscope, 0); DEF(OP_pushnamespace, 1); DEF(OP_hasnext2, 2); DEF(OP_newfunction, 1); DEF(OP_call, 1); DEF(OP_construct, 1); DEF(OP_callmethod, 2); DEF(OP_callstatic, 2); DEF(OP_callsuper, 2); DEF(OP_callproperty, 2); DEF(OP_returnvoid, 0); DEF(OP_returnvalue, 0); DEF(OP_constructsuper, 1); DEF(OP_constructprop, 1); DEF(OP_callproplex, 1); DEF(OP_callsupervoid, 2); DEF(OP_callpropvoid, 2); DEF(OP_applytype, 1); DEF(OP_newobject, 1); DEF(OP_newarray, 1); DEF(OP_newactivation, 0); DEF(OP_newclass, 1); DEF(OP_getdescendants, 1); DEF(OP_newcatch, 1); DEF(OP_findpropstrict, 1); DEF(OP_findproperty, 1); DEF(OP_finddef, 1); DEF(OP_getlex, 1); DEF(OP_setproperty, 1); DEF(OP_getlocal, 1); DEF(OP_setlocal, 1); DEF(OP_getglobalscope, 0); DEF(OP_getscopeobject, 1); DEF(OP_getproperty, 1); DEF(OP_getouterscope, 1); DEF(OP_initproperty, 1); DEF(OP_deleteproperty, 1); DEF(OP_getslot, 1); DEF(OP_setslot, 1); DEF(OP_getglobalslot, 1); DEF(OP_setglobalslot, 1); DEF(OP_convert_s, 0); DEF(OP_esc_xelem, 0); DEF(OP_esc_xattr, 0); DEF(OP_convert_i, 0); DEF(OP_convert_u, 0); DEF(OP_convert_d, 0); DEF(OP_convert_b, 0); DEF(OP_convert_o, 0); DEF(OP_checkfilter, 0); DEF(OP_coerce, 1); DEF(OP_coerce_b, 0); DEF(OP_coerce_a, 0); DEF(OP_coerce_i, 0); DEF(OP_coerce_d, 0); DEF(OP_coerce_s, 0); DEF(OP_astype, 1); DEF(OP_astypelate, 0); DEF(OP_coerce_u, 0); DEF(OP_coerce_o, 0); DEF(OP_negate, 0); DEF(OP_increment, 0); DEF(OP_inclocal, 1); DEF(OP_decrement, 0); DEF(OP_declocal, 1); DEF(OP_typeof, 0); DEF(OP_not, 0); DEF(OP_bitnot, 0); DEF(OP_add, 0); DEF(OP_subtract, 0); DEF(OP_multiply, 0); DEF(OP_divide, 0); DEF(OP_modulo, 0); DEF(OP_lshift, 0); DEF(OP_rshift, 0); DEF(OP_urshift, 0); DEF(OP_bitand, 0); DEF(OP_bitor, 0); DEF(OP_bitxor, 0); DEF(OP_equals, 0); DEF(OP_strictequals, 0); DEF(OP_lessthan, 0); DEF(OP_lessequals, 0); DEF(OP_greaterthan, 0); DEF(OP_greaterequals, 0); DEF(OP_instanceof, 0); DEF(OP_istype, 1); DEF(OP_istypelate, 0); DEF(OP_in, 0); DEF(OP_increment_i, 0); DEF(OP_decrement_i, 0); DEF(OP_inclocal_i, 1); DEF(OP_declocal_i, 1); DEF(OP_negate_i, 0); DEF(OP_add_i, 0); DEF(OP_subtract_i, 0); DEF(OP_multiply_i, 0); DEF(OP_getlocal0, 0); DEF(OP_getlocal1, 0); DEF(OP_getlocal2, 0); DEF(OP_getlocal3, 0); DEF(OP_setlocal0, 0); DEF(OP_setlocal1, 0); DEF(OP_setlocal2, 0); DEF(OP_setlocal3, 0); DEF(OP_debugline, 1); DEF(OP_debugfile, 1); DEF(OP_bkptline, 1); DEF(OP_ext_pushbits, 1); DEF(OP_ext_push_doublebits, 2); progname = argv[0]; i=1; while (i < argc && argv[i][0] == '-') { if (strcmp(argv[i], "-c") == 0) { if (i+1 == argc || sscanf(argv[i+1], "%d", &cutoff_count) != 1) { i=argc; break; } i += 2; } else if (strcmp(argv[i], "-l") == 0) { if (i+1 == argc || sscanf(argv[i+1], "%d", &cutoff_length) != 1) { i=argc; break; } i += 2; } else if (strcmp(argv[i], "-f") == 0) { flat = 1; i++; } else if (strcmp(argv[i], "-h") == 0) { hierarchical = 0; i++; } else if (strcmp(argv[i], "-o") == 0) { operand_tracking = 1; i++; } else if (strcmp(argv[i], "-v") == 0) { verbose = 1; i++; } else { i = argc; break; } } if (i > argc-2 || (argc - i) % 2 != 0) { fprintf(stderr, "Usage: %s [options] ( code_file sample_file ) ... \n\n", progname); fprintf(stderr, "Options:\n"); fprintf(stderr, " -c n Set sample cutoff = n (default 100)\n"); fprintf(stderr, " -l n Set length cutoff = n (default unbounded)\n"); fprintf(stderr, " -f Enable flat report\n"); fprintf(stderr, " -h Disable hierarchical report\n"); fprintf(stderr, " -o Operand tracking\n"); fprintf(stderr, " -v Verbose"); return 1; } while (i < argc) { read_code(argv[i]); read_samples(argv[i+1]); i += 2; scale++; } extract_superwords(); return 0; }
int main_vcfcall(int argc, char *argv[]) { char *samples_fname = NULL; args_t args; memset(&args, 0, sizeof(args_t)); args.argc = argc; args.argv = argv; args.aux.prior_type = -1; args.aux.indel_frac = -1; args.aux.theta = 1e-3; args.aux.pref = 0.5; args.aux.min_perm_p = 0.01; args.aux.min_lrt = 1; args.flag = CF_ACGT_ONLY; args.output_fname = "-"; args.output_type = FT_VCF; args.aux.trio_Pm_SNPs = 1 - 1e-8; args.aux.trio_Pm_ins = args.aux.trio_Pm_del = 1 - 1e-9; int i, c, samples_is_file = 0; static struct option loptions[] = { {"help",0,0,'h'}, {"gvcf",1,0,'g'}, {"format-fields",1,0,'f'}, {"output",1,0,'o'}, {"output-type",1,0,'O'}, {"regions",1,0,'r'}, {"regions-file",1,0,'R'}, {"samples",1,0,'s'}, {"samples-file",1,0,'S'}, {"targets",1,0,'t'}, {"targets-file",1,0,'T'}, {"keep-alts",0,0,'A'}, {"insert-missed",0,0,'i'}, {"skip-Ns",0,0,'N'}, // now the new default {"keep-masked-refs",0,0,'M'}, {"skip-variants",1,0,'V'}, {"variants-only",0,0,'v'}, {"consensus-caller",0,0,'c'}, {"constrain",1,0,'C'}, {"multiallelic-caller",0,0,'m'}, {"pval-threshold",1,0,'p'}, {"prior",1,0,'P'}, {"chromosome-X",0,0,'X'}, {"chromosome-Y",0,0,'Y'}, {"novel-rate",1,0,'n'}, {0,0,0,0} }; char *tmp = NULL; while ((c = getopt_long(argc, argv, "h?o:O:r:R:s:S:t:T:ANMV:vcmp:C:XYn:P:f:ig:", loptions, NULL)) >= 0) { switch (c) { case 'g': args.flag |= CF_GVCF; args.gvcf.min_dp = strtol(optarg,&tmp,10); if ( *tmp ) error("Could not parse, expected integer argument: -g %s\n", optarg); break; case 'f': args.aux.output_tags |= parse_format_flag(optarg); break; case 'M': args.flag &= ~CF_ACGT_ONLY; break; // keep sites where REF is N case 'N': args.flag |= CF_ACGT_ONLY; break; // omit sites where first base in REF is N (the new default) case 'A': args.aux.flag |= CALL_KEEPALT; break; case 'c': args.flag |= CF_CCALL; break; // the original EM based calling method case 'i': args.flag |= CF_INS_MISSED; break; case 'v': args.aux.flag |= CALL_VARONLY; break; case 'o': args.output_fname = optarg; break; case 'O': switch (optarg[0]) { case 'b': args.output_type = FT_BCF_GZ; break; case 'u': args.output_type = FT_BCF; break; case 'z': args.output_type = FT_VCF_GZ; break; case 'v': args.output_type = FT_VCF; break; default: error("The output type \"%s\" not recognised\n", optarg); } break; case 'C': if ( !strcasecmp(optarg,"alleles") ) args.aux.flag |= CALL_CONSTR_ALLELES; else if ( !strcasecmp(optarg,"trio") ) args.aux.flag |= CALL_CONSTR_TRIO; else error("Unknown argument to -C: \"%s\"\n", optarg); break; case 'X': args.aux.flag |= CALL_CHR_X; break; case 'Y': args.aux.flag |= CALL_CHR_Y; break; case 'V': if ( !strcasecmp(optarg,"snps") ) args.flag |= CF_INDEL_ONLY; else if ( !strcasecmp(optarg,"indels") ) args.flag |= CF_NO_INDEL; else error("Unknown skip category \"%s\" (-S argument must be \"snps\" or \"indels\")\n", optarg); break; case 'm': args.flag |= CF_MCALL; break; // multiallelic calling method case 'p': args.aux.pref = atof(optarg); break; case 'P': args.aux.theta = strtod(optarg,&tmp); if ( *tmp ) error("Could not parse, expected float argument: -P %s\n", optarg); break; case 'n': parse_novel_rate(&args,optarg); break; case 'r': args.regions = optarg; break; case 'R': args.regions = optarg; args.regions_is_file = 1; break; case 't': args.targets = optarg; break; case 'T': args.targets = optarg; args.targets_is_file = 1; break; case 's': samples_fname = optarg; break; case 'S': samples_fname = optarg; samples_is_file = 1; break; default: usage(&args); } } if ( optind>=argc ) { if ( !isatty(fileno((FILE *)stdin)) ) args.bcf_fname = "-"; // reading from stdin else usage(&args); } else args.bcf_fname = argv[optind++]; // Sanity check options and initialize if ( samples_fname ) { args.samples = read_samples(&args.aux, samples_fname, samples_is_file, &args.nsamples); args.aux.ploidy = (uint8_t*) calloc(args.nsamples+1, 1); args.aux.all_diploid = 1; for (i=0; i<args.nsamples; i++) { args.aux.ploidy[i] = args.samples[i][strlen(args.samples[i]) + 1]; if ( args.aux.ploidy[i]!=2 ) args.aux.all_diploid = 0; } } if ( args.flag & CF_GVCF ) { // Force some flags to avoid unnecessary branching args.aux.flag &= ~CALL_KEEPALT; args.aux.flag |= CALL_VARONLY; } if ( (args.flag & CF_CCALL ? 1 : 0) + (args.flag & CF_MCALL ? 1 : 0) + (args.flag & CF_QCALL ? 1 : 0) > 1 ) error("Only one of -c or -m options can be given\n"); if ( !(args.flag & CF_CCALL) && !(args.flag & CF_MCALL) && !(args.flag & CF_QCALL) ) error("Expected -c or -m option\n"); if ( args.aux.n_perm && args.aux.ngrp1_samples<=0 ) error("Expected -1 with -U\n"); // not sure about this, please fix if ( args.aux.flag & CALL_CONSTR_ALLELES ) { if ( !args.targets ) error("Expected -t or -T with \"-C alleles\"\n"); if ( !(args.flag & CF_MCALL) ) error("The \"-C alleles\" mode requires -m\n"); } if ( args.aux.flag & CALL_CHR_X && args.aux.flag & CALL_CHR_Y ) error("Only one of -X or -Y should be given\n"); if ( args.flag & CF_INS_MISSED && !(args.aux.flag&CALL_CONSTR_ALLELES) ) error("The -i option requires -C alleles\n"); init_data(&args); while ( bcf_sr_next_line(args.aux.srs) ) { bcf1_t *bcf_rec = args.aux.srs->readers[0].buffer[0]; if ( args.samples_map ) bcf_subset(args.aux.hdr, bcf_rec, args.nsamples, args.samples_map); bcf_unpack(bcf_rec, BCF_UN_STR); // Skip unwanted sites if ( args.aux.flag & CALL_VARONLY ) { int is_ref = 0; if ( bcf_rec->n_allele==1 ) is_ref = 1; // not a variant else if ( bcf_rec->n_allele==2 ) { // second allele is mpileup's X, not a variant if ( bcf_rec->d.allele[1][0]=='X' ) is_ref = 1; else if ( bcf_rec->d.allele[1][0]=='<' && bcf_rec->d.allele[1][1]=='X' && bcf_rec->d.allele[1][2]=='>' ) is_ref = 1; } if ( is_ref ) { // gVCF output if ( args.flag & CF_GVCF ) gvcf_write(args.out_fh, &args.gvcf, args.aux.hdr, bcf_rec, 1); continue; } } if ( (args.flag & CF_INDEL_ONLY) && bcf_is_snp(bcf_rec) ) continue; // not an indel if ( (args.flag & CF_NO_INDEL) && !bcf_is_snp(bcf_rec) ) continue; // not a SNP if ( (args.flag & CF_ACGT_ONLY) && (bcf_rec->d.allele[0][0]=='N' || bcf_rec->d.allele[0][0]=='n') ) continue; // REF[0] is 'N' bcf_unpack(bcf_rec, BCF_UN_ALL); // Various output modes: QCall output (todo) if ( args.flag & CF_QCALL ) { qcall(&args.aux, bcf_rec); continue; } // Calling modes which output VCFs int ret; if ( args.flag & CF_MCALL ) ret = mcall(&args.aux, bcf_rec); else ret = ccall(&args.aux, bcf_rec); if ( ret==-1 ) error("Something is wrong\n"); // gVCF output if ( args.flag & CF_GVCF ) { gvcf_write(args.out_fh, &args.gvcf, args.aux.hdr, bcf_rec, ret?0:1); continue; } // Normal output if ( (args.aux.flag & CALL_VARONLY) && ret==0 ) continue; // not a variant bcf_write1(args.out_fh, args.aux.hdr, bcf_rec); } if ( args.flag & CF_GVCF ) gvcf_write(args.out_fh, &args.gvcf, args.aux.hdr, NULL, 0); if ( args.flag & CF_INS_MISSED ) bcf_sr_regions_flush(args.aux.srs->targets); destroy_data(&args); return 0; }
static void audio_callback(void*, Uint8 *stream, int len) { assert(len >= 0); read_samples((int16_t*)stream, len/sizeof(int16_t)); }
int NormalizeMain::process_loop(double **buffer, int64_t &write_length) { int result = 0; int64_t fragment_len; //printf("NormalizeMain::process_loop 1\n"); if(writing) { fragment_len = PluginClient::in_buffer_size; if(current_position + fragment_len > PluginClient::end) fragment_len = PluginClient::end - current_position; //printf("NormalizeMain::process_loop 2 %d %f\n", current_position, scale[0]); for(int i = 0; i < PluginClient::total_in_buffers; i++) { read_samples(buffer[i], i, current_position, fragment_len); for(int j = 0; j < fragment_len; j++) buffer[i][j] *= scale[i]; } //printf("NormalizeMain::process_loop 1 %d %f\n", current_position, scale[0]); current_position += fragment_len; write_length = fragment_len; result = progress->update(PluginClient::end - PluginClient::start + current_position - PluginClient::start); if(current_position >= PluginClient::end) result = 1; } else { // Get peak //printf("NormalizeMain::process_loop 4\n"); for(int i = PluginClient::start; i < PluginClient::end && !result; i += fragment_len) { fragment_len = PluginClient::in_buffer_size; if(i + fragment_len > PluginClient::end) fragment_len = PluginClient::end - i; //printf("NormalizeMain::process_loop 5\n"); for(int j = 0; j < PluginClient::total_in_buffers; j++) { //printf("NormalizeMain::process_loop 6 %p\n", buffer); read_samples(buffer[j], j, i, fragment_len); //printf("NormalizeMain::process_loop 7\n"); for(int k = 0; k < fragment_len; k++) { if(peak[j] < fabs(buffer[j][k])) peak[j] = fabs(buffer[j][k]); } } //printf("NormalizeMain::process_loop 8\n"); result = progress->update(i - PluginClient::start); //printf("NormalizeMain::process_loop 9\n"); } // Normalize all tracks double max = 0; for(int i = 0; i < PluginClient::total_in_buffers; i++) { if(peak[i] > max) max = peak[i]; } if(!separate_tracks) { for(int i = 0; i < PluginClient::total_in_buffers; i++) { peak[i] = max; } } for(int i = 0; i < PluginClient::total_in_buffers; i++) { scale[i] = DB::fromdb(db_over) / peak[i]; } //printf("NormalizeMain::process_loop 10\n"); char string[BCTEXTLEN]; sprintf(string, "%s %.0f%%...", plugin_title(), (DB::fromdb(db_over) / max) * 100); progress->update_title(string); // Start writing on next iteration writing = 1; } return result; }
int main( int argc, char *argv[] ) { int i; char fn_inspeech[80], fn_outspeech[80]; FILE *fin, *fout; int numread, nsamp; float temp[MAXSF]; unsigned long frame_num; unsigned long total_frames; unsigned long fer_count; struct ENCODER_MEM encoder_memory; struct DECODER_MEM decoder_memory; struct PACKET packet; struct CONTROL control; int input_format; int output_format; #if USE_CALLOC float *in_speech; float *out_speech; #else float in_speech[FSIZE+LPCSIZE-FSIZE+LPCOFFSET]; float out_speech[FSIZE]; #endif memset(&encoder_memory, 0, sizeof(encoder_memory)); memset(&decoder_memory, 0, sizeof(decoder_memory)); memset(&packet, 0, sizeof(packet)); memset(&control, 0, sizeof(control)); #if USE_CALLOC alloc_mem_for_speech(&in_speech, &out_speech); #endif for(i = 0; i < argc; i++) fprintf(stdout, "%s ", argv[i]); fprintf(stdout, "\n"); parse_command_line(argc, argv, fn_inspeech, fn_outspeech, &control); initialize_encoder_and_decoder(&encoder_memory, &decoder_memory, &control); print_welcome_message(); /*** Init TTY/TDD Routines and Varibles ***/ if( tty_debug_flag ) tty_debug(); if( tty_option == TTY_NO_GAIN ) { fprintf(stdout," TTY OPTION = NO GAIN\n"); init_tty_enc( &tty_enc_char, &tty_enc_header, &tty_enc_baud_rate); init_tty_dec(); } else { tty_option = 0; fprintf(stdout," TTY OPTION = OFF\n"); } if( trans_fname != NULL ) { fprintf(stdout,"FER SIMULATOR ON: seed = %d\n",fer_sim_seed); } for(i = 0; i < LPCORDER; i++) packet.lsp[i] = packet.lpc[i] = 0; encoder_memory.frame_num = 0; frame_num = 0; fer_count = 0; if (control.decode_only == YES) { /* Input is a CELP file */ switch (control.celp_file_format) { case FORMAT_PACKET: open_binary_input_file(&fin, fn_inspeech); total_frames = GetNumFrames(fin, sizeof(short)*WORDS_PER_PACKET); input_format = FORMAT_PACKET; break; case FORMAT_QCP: open_qcp_input_file(&fin, fn_inspeech); total_frames = get_qcp_packet_count(); input_format = FORMAT_QCP; break; default: fprintf(stderr, "unsupported decode_only input format %d\n", control.celp_file_format); exit(-2); } } else { /* Input is an audio file */ open_binary_input_file(&fin, fn_inspeech); input_format = FORMAT_RAW_AUDIO; total_frames = GetNumFrames(fin, sizeof(short)*FSIZE); } if ((control.form_res_out == YES) || (control.target_after_out == YES) || (control.cb_out == YES) || (control.pitch_out == YES)) { /* Output is encoder state for debugging */ open_binary_output_file(&fout, fn_outspeech); output_format = FORMAT_DEBUG_OUTPUT; } else if (control.encode_only == YES) { /* Output is a CELP file */ switch (control.celp_file_format) { case FORMAT_PACKET: open_binary_output_file(&fout, fn_outspeech); output_format = FORMAT_PACKET; break; case FORMAT_QCP: open_qcp_output_file(&fout, fn_outspeech, total_frames); output_format = FORMAT_QCP; break; default: fprintf(stderr, "unsupported encode_only output format %d\n", control.celp_file_format); exit(-2); } } else { /* Output is an audio file */ open_binary_output_file(&fout, fn_outspeech); output_format = FORMAT_RAW_AUDIO; } if(control.decode_only == NO) { #if 0 if (read_samples(fin, in_speech, LPCSIZE-FSIZE+LPCOFFSET) !=LPCSIZE-FSIZE+LPCOFFSET) { printf("Not even enough samples for 1 frame!\n"); usage(&control); } #else for( i=0 ; i < LPCSIZE-FSIZE+LPCOFFSET ; i++ ) { in_speech[i] = 0; } #endif } /*----------------------------------------------- * Main Loop *------------------------------------------------*/ while( control.num_frames == UNLIMITED || frame_num < control.num_frames ) { fprintf(stderr,"Processing %lu of %lu FER = %.2f%%\r", frame_num, total_frames, 100.0*fer_count/(frame_num+1)); if (control.decode_only==NO) { nsamp = read_samples(fin, &in_speech[LPCSIZE-FSIZE+LPCOFFSET], FSIZE); if( nsamp <= 0 ) { break; } else if(nsamp < FSIZE) { for (i=nsamp; i<FSIZE; i++) { in_speech[LPCSIZE-FSIZE+LPCOFFSET+i]=0; } } encoder(in_speech, &packet, &control, &encoder_memory, out_speech); update_snr(ENCODER, in_speech, out_speech, &(control.snr)); } if (control.decode_only==YES) { if (input_format == FORMAT_QCP) { numread = read_qcp_packet(fin, packet.data, WORDS_PER_PACKET); if (numread == 0) break; } else { /* FORMAT_PACKET */ numread = read_packet(fin, packet.data, WORDS_PER_PACKET); if( numread != WORDS_PER_PACKET) { if(numread != 0) { fprintf(stderr, "%s: Wrong number of words read: %d\n", argv[0], numread); } break; } } } if(control.encode_only==NO) { if (control.output_encoder_speech==NO) { decoder(out_speech, &packet, &control, &decoder_memory); if( packet.data[0] == ERASURE ) { fer_count++; } if(control.decode_only==NO) { update_snr(DECODER, in_speech, out_speech, &(control.snr)); } } i = write_samples(fout,out_speech,FSIZE); } else { if( trans_fname != NULL ) { fer_sim( &(packet.data[0]) ); } if( packet.data[0] == ERASURE ) { fer_count++; } if (output_format == FORMAT_QCP) { i = write_qcp_packet(fout, packet.data, WORDS_PER_PACKET); } else { i = write_packet(fout, packet.data, WORDS_PER_PACKET); } } /***** Update in_speech buffer ***************/ for (i=0; i<LPCSIZE-FSIZE+LPCOFFSET; i++) { in_speech[i]=in_speech[i+FSIZE]; } frame_num++; encoder_memory.frame_num = frame_num; } /* end main while() */ if (output_format == FORMAT_QCP) { finish_qcp_output_file(fout); } fclose(fin); fclose(fout); if ((control.encode_only==NO)&&(control.decode_only==NO)) { compute_snr(&(control.snr), &control); } if( control.decode_only == NO ) { /* calculate the avg. rate for active speech for the entire file */ temp[0] = (encoder_memory.full_cnt + encoder_memory.full_force + encoder_memory.full_cnt_t + encoder_memory.full_force_t)*14.4+ (encoder_memory.half_cnt + encoder_memory.half_force + encoder_memory.half_cnt_t + encoder_memory.half_force_t)*7.2+ (encoder_memory.quarter_cnt + encoder_memory.quarter_cnt_t)*3.6; temp[0] /= (encoder_memory.total_speech_frames+ (STATWINDOW-encoder_memory.block_cnt)); if(control.reduced_rate_flag != 0) { printf("\n The target_snr_threshold at the end of the run was %f", encoder_memory.target_snr_thr); printf("\n The average rate for the entire file was %f",temp[0]); i = STATWINDOW-encoder_memory.block_cnt+encoder_memory.total_speech_frames; temp[1] = i; printf("\n The # of speech frames in the file is = %d",i); i = encoder_memory.full_cnt+encoder_memory.full_cnt_t; printf("\n The percent of frames at 14.4 is %f",100.0*i/temp[1]); i = encoder_memory.full_force+encoder_memory.full_force_t; printf("\n The percent of frames forced to 14.4 is %f",100.*i/temp[1]); i = encoder_memory.half_cnt+encoder_memory.half_cnt_t; printf("\n The percent of frames at 7.2 is %f",100.*i/temp[1]); i = encoder_memory.half_force+encoder_memory.half_force_t; printf("\n The percent of frames forced to 7.2 is %f",100.*i/temp[1]); i = encoder_memory.quarter_cnt+encoder_memory.quarter_cnt_t; printf("\n The percent of frames coded at 3.6 is %f\n",100.*i/temp[1]); } } if(control.encode_only == NO) print_erasure_count(); free_encoder_and_decoder(&encoder_memory, &decoder_memory); #if USE_CALLOC free((char*) in_speech); free((char*) out_speech); #endif print_farewell_message(); exit(0); }/* end of main() */
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; }
static void make_table(FILE *p_file_table_c, FILE *p_file_table_h, char *p_table_name, char *p_file_name) { char *p_path_file_name; FILE *p_file_sample; int i, nb_samples; short *p_buf_samples; p_path_file_name = (char *) malloc(strlen(TEQ_STREAMS_PATH) + strlen(p_file_name) + 1); if(p_path_file_name == NULL) { fprintf(stderr, "can't allocate p_path_file_name\n"); return; } strcpy(p_path_file_name, TEQ_STREAMS_PATH); strcat(p_path_file_name, p_file_name); p_file_sample = fopen(p_path_file_name, "rb"); if(p_file_sample == NULL) { fprintf(stderr, "can't open \"%s\" input file\n", p_path_file_name); free(p_path_file_name); return; } free(p_path_file_name); fseek(p_file_sample, 0, SEEK_END); nb_samples = ftell(p_file_sample) / sizeof(short); rewind(p_file_sample); p_buf_samples = (short *) malloc(nb_samples * sizeof(short)); if(p_buf_samples == NULL) { fprintf(stderr, "can't allocate p_buf_samples\n"); fclose(p_file_sample); return; } read_samples(p_file_sample, p_buf_samples, nb_samples); fclose(p_file_sample); fprintf(p_file_table_h, "extern const int %s_size;\n", p_table_name, nb_samples); fprintf(p_file_table_h, "extern const short %s[%d];\n\n", p_table_name, nb_samples); fprintf(p_file_table_c, "const int %s_size = %d;\n", p_table_name, nb_samples); fprintf(p_file_table_c, "const short %s[%d] =\n{\n", p_table_name, nb_samples); for(i = 0; i < nb_samples; i++) { if((i % 16) == 0) { fprintf(p_file_table_c, "\t"); } else { fprintf(p_file_table_c, " "); } fprintf(p_file_table_c, "0x%04X", ((int) p_buf_samples[i]) & 0xFFFF); if(i < nb_samples - 1) { fprintf(p_file_table_c, ","); } if((i % 16) == 15) { fprintf(p_file_table_c, "\n"); } } if((nb_samples % 16) != 0) { fprintf(p_file_table_c, "\n"); } fprintf(p_file_table_c, "};\n\n"); free(p_buf_samples); }
/*! * \brief Read a frame full of audio data from the filestream. * \param fs The filestream. * \param whennext Number of sample times to schedule the next call. * \return A pointer to a frame containing audio data or NULL ifthere is no more audio data. */ static struct ast_frame *ogg_vorbis_read(struct ast_filestream *fs, int *whennext) { int clipflag = 0; int i; int j; double accumulator[SAMPLES_MAX]; int val; int samples_in; int samples_out = 0; struct vorbis_desc *s = (struct vorbis_desc *)fs->_private; short *buf; /* SLIN data buffer */ fs->fr.frametype = AST_FRAME_VOICE; fs->fr.subclass = AST_FORMAT_SLINEAR; fs->fr.mallocd = 0; AST_FRAME_SET_BUFFER(&fs->fr, fs->buf, AST_FRIENDLY_OFFSET, BUF_SIZE); buf = (short *)(fs->fr.data); /* SLIN data buffer */ while (samples_out != SAMPLES_MAX) { float **pcm; int len = SAMPLES_MAX - samples_out; /* See ifVorbis decoder has some audio data for us ... */ samples_in = read_samples(fs, &pcm); if (samples_in <= 0) break; /* Got some audio data from Vorbis... */ /* Convert the float audio data to 16-bit signed linear */ clipflag = 0; if (samples_in > len) samples_in = len; for (j = 0; j < samples_in; j++) accumulator[j] = 0.0; for (i = 0; i < s->vi.channels; i++) { float *mono = pcm[i]; for (j = 0; j < samples_in; j++) accumulator[j] += mono[j]; } for (j = 0; j < samples_in; j++) { val = accumulator[j] * 32767.0 / s->vi.channels; if (val > 32767) { val = 32767; clipflag = 1; } else if (val < -32768) { val = -32768; clipflag = 1; } buf[samples_out + j] = val; } if (clipflag) ast_log(LOG_WARNING, "Clipping in frame %ld\n", (long) (s->vd.sequence)); /* Tell the Vorbis decoder how many samples we actually used. */ vorbis_synthesis_read(&s->vd, samples_in); samples_out += samples_in; } if (samples_out > 0) { fs->fr.datalen = samples_out * 2; fs->fr.samples = samples_out; *whennext = samples_out; return &fs->fr; } else { return NULL; } }
int main(int argc, char **argv) { int nb_samples, total_samples=0, nb_encoded; int c; int option_index = 0; char *inFile, *outFile; FILE *fin, *fout; short input[MAX_FRAME_SIZE]; celt_int32 frame_size = 960; int quiet=0; int nbBytes; CELTMode *mode; void *st; unsigned char bits[MAX_FRAME_BYTES]; int with_cbr = 0; int with_cvbr = 0; int with_skeleton = 0; int total_bytes = 0; int peak_bytes = 0; struct option long_options[] = { {"bitrate", required_argument, NULL, 0}, {"cbr",no_argument,NULL, 0}, {"cvbr",no_argument,NULL, 0}, {"comp", required_argument, NULL, 0}, {"nopf", no_argument, NULL, 0}, {"independent", no_argument, NULL, 0}, {"framesize", required_argument, NULL, 0}, {"skeleton",no_argument,NULL, 0}, {"help", no_argument, NULL, 0}, {"quiet", no_argument, NULL, 0}, {"le", no_argument, NULL, 0}, {"be", no_argument, NULL, 0}, {"8bit", no_argument, NULL, 0}, {"16bit", no_argument, NULL, 0}, {"mono", no_argument, NULL, 0}, {"stereo", no_argument, NULL, 0}, {"rate", required_argument, NULL, 0}, {"version", no_argument, NULL, 0}, {"version-short", no_argument, NULL, 0}, {"comment", required_argument, NULL, 0}, {"author", required_argument, NULL, 0}, {"title", required_argument, NULL, 0}, {0, 0, 0, 0} }; int print_bitrate=0; celt_int32 rate=48000; celt_int32 size; int chan=1; int fmt=16; int lsb=1; ogg_stream_state os; ogg_stream_state so; /* ogg stream for skeleton bitstream */ ogg_page og; ogg_packet op; int bytes_written=0, ret, result; int id=-1; CELTHeader header; char vendor_string[64]; char *comments; int comments_length; int close_in=0, close_out=0; int eos=0; float bitrate=-1; char first_bytes[12]; int wave_input=0; celt_int32 lookahead = 0; int bytes_per_packet=-1; int complexity=-127; int prediction=2; /*Process command-line options*/ while(1) { c = getopt_long (argc, argv, "hvV", long_options, &option_index); if (c==-1) break; switch(c) { case 0: if (strcmp(long_options[option_index].name,"bitrate")==0) { bitrate = atof (optarg); } else if (strcmp(long_options[option_index].name,"cbr")==0) { with_cbr=1; } else if (strcmp(long_options[option_index].name,"cvbr")==0) { with_cvbr=1; } else if (strcmp(long_options[option_index].name,"skeleton")==0) { with_skeleton=1; } else if (strcmp(long_options[option_index].name,"help")==0) { usage(); exit(0); } else if (strcmp(long_options[option_index].name,"quiet")==0) { quiet = 1; } else if (strcmp(long_options[option_index].name,"version")==0) { version(); exit(0); } else if (strcmp(long_options[option_index].name,"version-short")==0) { version_short(); exit(0); } else if (strcmp(long_options[option_index].name,"le")==0) { lsb=1; } else if (strcmp(long_options[option_index].name,"be")==0) { lsb=0; } else if (strcmp(long_options[option_index].name,"8bit")==0) { fmt=8; } else if (strcmp(long_options[option_index].name,"16bit")==0) { fmt=16; } else if (strcmp(long_options[option_index].name,"stereo")==0) { chan=2; } else if (strcmp(long_options[option_index].name,"mono")==0) { chan=1; } else if (strcmp(long_options[option_index].name,"rate")==0) { rate=atoi (optarg); } else if (strcmp(long_options[option_index].name,"comp")==0) { complexity=atoi (optarg); } else if (strcmp(long_options[option_index].name,"framesize")==0) { frame_size=atoi (optarg); } else if (strcmp(long_options[option_index].name,"nopf")==0) { if (prediction>1) prediction=1; } else if (strcmp(long_options[option_index].name,"independent")==0) { prediction=0; } else if (strcmp(long_options[option_index].name,"comment")==0) { if (!strchr(optarg, '=')) { fprintf (stderr, "Invalid comment: %s\n", optarg); fprintf (stderr, "Comments must be of the form name=value\n"); exit(1); } comment_add(&comments, &comments_length, NULL, optarg); } else if (strcmp(long_options[option_index].name,"author")==0) { comment_add(&comments, &comments_length, "author=", optarg); } else if (strcmp(long_options[option_index].name,"title")==0) { comment_add(&comments, &comments_length, "title=", optarg); } break; case 'h': usage(); exit(0); break; case 'v': version(); exit(0); break; case 'V': print_bitrate=1; break; case '?': usage(); exit(1); break; } } if (argc-optind!=2) { usage(); exit(1); } inFile=argv[optind]; outFile=argv[optind+1]; /*Initialize Ogg stream struct*/ srand(time(NULL)); if (ogg_stream_init(&os, rand())==-1) { fprintf(stderr,"Error: stream init failed\n"); exit(1); } if (with_skeleton && ogg_stream_init(&so, rand())==-1) { fprintf(stderr,"Error: stream init failed\n"); exit(1); } if (strcmp(inFile, "-")==0) { #if defined WIN32 || defined _WIN32 _setmode(_fileno(stdin), _O_BINARY); #elif defined OS2 _fsetmode(stdin,"b"); #endif fin=stdin; } else { fin = fopen(inFile, "rb"); if (!fin) { perror(inFile); exit(1); } close_in=1; } { fread(first_bytes, 1, 12, fin); if (strncmp(first_bytes,"RIFF",4)==0 && strncmp(first_bytes,"RIFF",4)==0) { if (read_wav_header(fin, &rate, &chan, &fmt, &size)==-1) exit(1); wave_input=1; lsb=1; /* CHECK: exists big-endian .wav ?? */ } } if (bitrate<=0.005) if (chan==1) bitrate=64.0; else bitrate=128.0; bytes_per_packet = MAX_FRAME_BYTES; mode = celt_mode_create(rate, frame_size, NULL); if (!mode) return 1; snprintf(vendor_string, sizeof(vendor_string), "Encoded with CELT %s\n",CELT_VERSION); comment_init(&comments, &comments_length, vendor_string); /*celt_mode_info(mode, CELT_GET_FRAME_SIZE, &frame_size);*/ celt_header_init(&header, mode, frame_size, chan); header.nb_channels = chan; { char *st_string="mono"; if (chan==2) st_string="stereo"; if (!quiet) if (with_cbr) fprintf (stderr, "Encoding %.0f kHz %s audio in %.0fms packets at %0.3fkbit/sec (%d bytes per packet, CBR)\n", header.sample_rate/1000., st_string, frame_size/(float)header.sample_rate*1000., bitrate, bytes_per_packet); else fprintf (stderr, "Encoding %.0f kHz %s audio in %.0fms packets at %0.3fkbit/sec (%d bytes per packet maximum)\n", header.sample_rate/1000., st_string, frame_size/(float)header.sample_rate*1000., bitrate, bytes_per_packet); } /*Initialize CELT encoder*/ st = celt_encoder_create_custom(mode, chan, NULL); { int tmp = (bitrate*1000); if (celt_encoder_ctl(st, CELT_SET_BITRATE(tmp)) != CELT_OK) { fprintf (stderr, "bitrate request failed\n"); return 1; } } if (!with_cbr) { if (celt_encoder_ctl(st, CELT_SET_VBR(1)) != CELT_OK) { fprintf (stderr, "VBR request failed\n"); return 1; } if (!with_cvbr) { if (celt_encoder_ctl(st, CELT_SET_VBR_CONSTRAINT(0)) != CELT_OK) { fprintf (stderr, "VBR constraint failed\n"); return 1; } } } if (celt_encoder_ctl(st, CELT_SET_PREDICTION(prediction)) != CELT_OK) { fprintf (stderr, "Prediction request failed\n"); return 1; } if (complexity!=-127) { if (celt_encoder_ctl(st, CELT_SET_COMPLEXITY(complexity)) != CELT_OK) { fprintf (stderr, "Only complexity 0 through 10 is supported\n"); return 1; } } if (strcmp(outFile,"-")==0) { #if defined WIN32 || defined _WIN32 _setmode(_fileno(stdout), _O_BINARY); #endif fout=stdout; } else { fout = fopen(outFile, "wb"); if (!fout) { perror(outFile); exit(1); } close_out=1; } if (with_skeleton) { fprintf (stderr, "Warning: Enabling skeleton output may cause some decoders to fail.\n"); } /* first packet should be the skeleton header. */ if (with_skeleton) { add_fishead_packet(&so); if ((ret = flush_ogg_stream_to_file(&so, fout))) { fprintf (stderr,"Error: failed skeleton (fishead) header to output stream\n"); exit(1); } else bytes_written += ret; } /*Write header*/ { unsigned char header_data[100]; int packet_size = celt_header_to_packet(&header, header_data, 100); op.packet = header_data; op.bytes = packet_size; op.b_o_s = 1; op.e_o_s = 0; op.granulepos = 0; op.packetno = 0; ogg_stream_packetin(&os, &op); while((result = ogg_stream_flush(&os, &og))) { if(!result) break; ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } op.packet = (unsigned char *)comments; op.bytes = comments_length; op.b_o_s = 0; op.e_o_s = 0; op.granulepos = 0; op.packetno = 1; ogg_stream_packetin(&os, &op); } /* fisbone packet should be write after all bos pages */ if (with_skeleton) { add_fisbone_packet(&so, os.serialno, &header); if ((ret = flush_ogg_stream_to_file(&so, fout))) { fprintf (stderr,"Error: failed writing skeleton (fisbone )header to output stream\n"); exit(1); } else bytes_written += ret; } /* writing the rest of the celt header packets */ while((result = ogg_stream_flush(&os, &og))) { if(!result) break; ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } free(comments); /* write the skeleton eos packet */ if (with_skeleton) { add_eos_packet_to_stream(&so); if ((ret = flush_ogg_stream_to_file(&so, fout))) { fprintf (stderr,"Error: failed writing skeleton header to output stream\n"); exit(1); } else bytes_written += ret; } if (!wave_input) { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, first_bytes, NULL); } else { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); } if (nb_samples==0) eos=1; total_samples += nb_samples; nb_encoded = -lookahead; /*Main encoding loop (one frame per iteration)*/ while (!eos || total_samples>nb_encoded) { id++; /*Encode current frame*/ nbBytes = celt_encode(st, input, frame_size, bits, bytes_per_packet); if (nbBytes<0) { fprintf(stderr, "Got error %d while encoding. Aborting.\n", nbBytes); break; } nb_encoded += frame_size; total_bytes += nbBytes; peak_bytes=IMAX(nbBytes,peak_bytes); if (wave_input) { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); } else { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, NULL); } if (nb_samples==0) { eos=1; } if (eos && total_samples<=nb_encoded) op.e_o_s = 1; else op.e_o_s = 0; total_samples += nb_samples; op.packet = (unsigned char *)bits; op.bytes = nbBytes; op.b_o_s = 0; /*Is this redundent?*/ if (eos && total_samples<=nb_encoded) op.e_o_s = 1; else op.e_o_s = 0; op.granulepos = (id+1)*frame_size-lookahead; if (op.granulepos>total_samples) op.granulepos = total_samples; /*printf ("granulepos: %d %d %d %d %d %d\n", (int)op.granulepos, id, nframes, lookahead, 5, 6);*/ op.packetno = 2+id; ogg_stream_packetin(&os, &op); /*Write all new pages (most likely 0 or 1)*/ while (ogg_stream_pageout(&os,&og)) { ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } } /*Flush all pages left to be written*/ while (ogg_stream_flush(&os, &og)) { ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } if (!with_cbr && !quiet) fprintf (stderr, "Average rate %0.3fkbit/sec, %d peak bytes per packet\n", (total_bytes*8.0/((float)nb_encoded/header.sample_rate))/1000.0, peak_bytes); celt_encoder_destroy(st); celt_mode_destroy(mode); ogg_stream_clear(&os); if (close_in) fclose(fin); if (close_out) fclose(fout); return 0; }
int main(int argc, char **argv) { int nb_samples, total_samples=0, nb_encoded; int c; int option_index = 0; char *inFile, *outFile; FILE *fin, *fout; short input[MAX_FRAME_SIZE]; spx_int32_t frame_size; int quiet=0; spx_int32_t vbr_enabled=0; spx_int32_t vbr_max=0; int abr_enabled=0; spx_int32_t vad_enabled=0; spx_int32_t dtx_enabled=0; int nbBytes; const SpeexMode *mode=NULL; int modeID = -1; void *st; SpeexBits bits; char cbits[MAX_FRAME_BYTES]; int with_skeleton = 0; struct option long_options[] = { {"wideband", no_argument, NULL, 0}, {"ultra-wideband", no_argument, NULL, 0}, {"narrowband", no_argument, NULL, 0}, {"vbr", no_argument, NULL, 0}, {"vbr-max-bitrate", required_argument, NULL, 0}, {"abr", required_argument, NULL, 0}, {"vad", no_argument, NULL, 0}, {"dtx", no_argument, NULL, 0}, {"quality", required_argument, NULL, 0}, {"bitrate", required_argument, NULL, 0}, {"nframes", required_argument, NULL, 0}, {"comp", required_argument, NULL, 0}, #ifdef USE_SPEEXDSP {"denoise", no_argument, NULL, 0}, {"agc", no_argument, NULL, 0}, #endif {"no-highpass", no_argument, NULL, 0}, {"skeleton",no_argument,NULL, 0}, {"help", no_argument, NULL, 0}, {"quiet", no_argument, NULL, 0}, {"le", no_argument, NULL, 0}, {"be", no_argument, NULL, 0}, {"8bit", no_argument, NULL, 0}, {"16bit", no_argument, NULL, 0}, {"stereo", no_argument, NULL, 0}, {"rate", required_argument, NULL, 0}, {"version", no_argument, NULL, 0}, {"version-short", no_argument, NULL, 0}, {"comment", required_argument, NULL, 0}, {"author", required_argument, NULL, 0}, {"title", required_argument, NULL, 0}, {"print-rate", no_argument, NULL, 0}, {0, 0, 0, 0} }; int print_bitrate=0; spx_int32_t rate=0; spx_int32_t size; int chan=1; int fmt=16; spx_int32_t quality=-1; float vbr_quality=-1; int lsb=1; ogg_stream_state os; ogg_stream_state so; /* ogg stream for skeleton bitstream */ ogg_page og; ogg_packet op; int bytes_written=0, ret, result; int id=-1; SpeexHeader header; int nframes=1; spx_int32_t complexity=3; const char* speex_version; char vendor_string[64]; char *comments; int comments_length; int close_in=0, close_out=0; int eos=0; spx_int32_t bitrate=0; double cumul_bits=0, enc_frames=0; char first_bytes[12]; int wave_input=0; spx_int32_t tmp; #ifdef USE_SPEEXDSP SpeexPreprocessState *preprocess = NULL; int denoise_enabled=0, agc_enabled=0; #endif int highpass_enabled=1; int output_rate=0; spx_int32_t lookahead = 0; speex_lib_ctl(SPEEX_LIB_GET_VERSION_STRING, (void*)&speex_version); snprintf(vendor_string, sizeof(vendor_string), "Encoded with Speex %s", speex_version); comment_init(&comments, &comments_length, vendor_string); /*Process command-line options*/ while(1) { c = getopt_long (argc, argv, "nwuhvV", long_options, &option_index); if (c==-1) break; switch(c) { case 0: if (strcmp(long_options[option_index].name,"narrowband")==0) { modeID = SPEEX_MODEID_NB; } else if (strcmp(long_options[option_index].name,"wideband")==0) { modeID = SPEEX_MODEID_WB; } else if (strcmp(long_options[option_index].name,"ultra-wideband")==0) { modeID = SPEEX_MODEID_UWB; } else if (strcmp(long_options[option_index].name,"vbr")==0) { vbr_enabled=1; } else if (strcmp(long_options[option_index].name,"vbr-max-bitrate")==0) { vbr_max=atoi(optarg); if (vbr_max<1) { fprintf (stderr, "Invalid VBR max bit-rate value: %d\n", vbr_max); exit(1); } } else if (strcmp(long_options[option_index].name,"abr")==0) { abr_enabled=atoi(optarg); if (!abr_enabled) { fprintf (stderr, "Invalid ABR value: %d\n", abr_enabled); exit(1); } } else if (strcmp(long_options[option_index].name,"vad")==0) { vad_enabled=1; } else if (strcmp(long_options[option_index].name,"dtx")==0) { dtx_enabled=1; } else if (strcmp(long_options[option_index].name,"quality")==0) { quality = atoi (optarg); vbr_quality=atof(optarg); } else if (strcmp(long_options[option_index].name,"bitrate")==0) { bitrate = atoi (optarg); } else if (strcmp(long_options[option_index].name,"nframes")==0) { nframes = atoi (optarg); if (nframes<1) nframes=1; if (nframes>10) nframes=10; } else if (strcmp(long_options[option_index].name,"comp")==0) { complexity = atoi (optarg); #ifdef USE_SPEEXDSP } else if (strcmp(long_options[option_index].name,"denoise")==0) { denoise_enabled=1; } else if (strcmp(long_options[option_index].name,"agc")==0) { agc_enabled=1; #endif } else if (strcmp(long_options[option_index].name,"no-highpass")==0) { highpass_enabled=0; } else if (strcmp(long_options[option_index].name,"skeleton")==0) { with_skeleton=1; } else if (strcmp(long_options[option_index].name,"help")==0) { usage(); exit(0); } else if (strcmp(long_options[option_index].name,"quiet")==0) { quiet = 1; } else if (strcmp(long_options[option_index].name,"version")==0) { version(); exit(0); } else if (strcmp(long_options[option_index].name,"version-short")==0) { version_short(); exit(0); } else if (strcmp(long_options[option_index].name,"print-rate")==0) { output_rate=1; } else if (strcmp(long_options[option_index].name,"le")==0) { lsb=1; } else if (strcmp(long_options[option_index].name,"be")==0) { lsb=0; } else if (strcmp(long_options[option_index].name,"8bit")==0) { fmt=8; } else if (strcmp(long_options[option_index].name,"16bit")==0) { fmt=16; } else if (strcmp(long_options[option_index].name,"stereo")==0) { chan=2; } else if (strcmp(long_options[option_index].name,"rate")==0) { rate=atoi (optarg); } else if (strcmp(long_options[option_index].name,"comment")==0) { if (!strchr(optarg, '=')) { fprintf (stderr, "Invalid comment: %s\n", optarg); fprintf (stderr, "Comments must be of the form name=value\n"); exit(1); } comment_add(&comments, &comments_length, NULL, optarg); } else if (strcmp(long_options[option_index].name,"author")==0) { comment_add(&comments, &comments_length, "author=", optarg); } else if (strcmp(long_options[option_index].name,"title")==0) { comment_add(&comments, &comments_length, "title=", optarg); } break; case 'n': modeID = SPEEX_MODEID_NB; break; case 'h': usage(); exit(0); break; case 'v': version(); exit(0); break; case 'V': print_bitrate=1; break; case 'w': modeID = SPEEX_MODEID_WB; break; case 'u': modeID = SPEEX_MODEID_UWB; break; case '?': usage(); exit(1); break; } } if (argc-optind!=2) { usage(); exit(1); } inFile=argv[optind]; outFile=argv[optind+1]; /*Initialize Ogg stream struct*/ srand(time(NULL)); if (ogg_stream_init(&os, rand())==-1) { fprintf(stderr,"Error: stream init failed\n"); exit(1); } if (with_skeleton && ogg_stream_init(&so, rand())==-1) { fprintf(stderr,"Error: stream init failed\n"); exit(1); } if (strcmp(inFile, "-")==0) { #if defined WIN32 || defined _WIN32 _setmode(_fileno(stdin), _O_BINARY); #elif defined OS2 _fsetmode(stdin,"b"); #endif fin=stdin; } else { fin = fopen(inFile, "rb"); if (!fin) { perror(inFile); exit(1); } close_in=1; } { if (fread(first_bytes, 1, 12, fin) != 12) { perror("short file"); exit(1); } if (strncmp(first_bytes,"RIFF",4)==0 || strncmp(first_bytes,"riff",4)==0) { if (read_wav_header(fin, &rate, &chan, &fmt, &size)==-1) exit(1); wave_input=1; lsb=1; /* CHECK: exists big-endian .wav ?? */ } } if (modeID==-1 && !rate) { /* By default, use narrowband/8 kHz */ modeID = SPEEX_MODEID_NB; rate=8000; } else if (modeID!=-1 && rate) { mode = speex_lib_get_mode (modeID); if (rate>48000) { fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate); exit(1); } else if (rate>25000) { if (modeID != SPEEX_MODEID_UWB) { fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try ultra-wideband instead\n", mode->modeName , rate); } } else if (rate>12500) { if (modeID != SPEEX_MODEID_WB) { fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try wideband instead\n", mode->modeName , rate); } } else if (rate>=6000) { if (modeID != SPEEX_MODEID_NB) { fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try narrowband instead\n", mode->modeName , rate); } } else { fprintf (stderr, "Error: sampling rate too low: %d Hz\n", rate); exit(1); } } else if (modeID==-1) { if (rate>48000) { fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate); exit(1); } else if (rate>25000) { modeID = SPEEX_MODEID_UWB; } else if (rate>12500) { modeID = SPEEX_MODEID_WB; } else if (rate>=6000) { modeID = SPEEX_MODEID_NB; } else { fprintf (stderr, "Error: Sampling rate too low: %d Hz\n", rate); exit(1); } } else if (!rate) { if (modeID == SPEEX_MODEID_NB) rate=8000; else if (modeID == SPEEX_MODEID_WB) rate=16000; else if (modeID == SPEEX_MODEID_UWB) rate=32000; } if (!quiet) if (rate!=8000 && rate!=16000 && rate!=32000) fprintf (stderr, "Warning: Speex is only optimized for 8, 16 and 32 kHz. It will still work at %d Hz but your mileage may vary\n", rate); if (!mode) mode = speex_lib_get_mode (modeID); speex_init_header(&header, rate, 1, mode); header.frames_per_packet=nframes; header.vbr=vbr_enabled; header.nb_channels = chan; { char *st_string="mono"; if (chan==2) st_string="stereo"; if (!quiet) fprintf (stderr, "Encoding %d Hz audio using %s mode (%s)\n", header.rate, mode->modeName, st_string); } /*fprintf (stderr, "Encoding %d Hz audio at %d bps using %s mode\n", header.rate, mode->bitrate, mode->modeName);*/ /*Initialize Speex encoder*/ st = speex_encoder_init(mode); if (strcmp(outFile,"-")==0) { #if defined WIN32 || defined _WIN32 _setmode(_fileno(stdout), _O_BINARY); #endif fout=stdout; } else { fout = fopen(outFile, "wb"); if (!fout) { perror(outFile); exit(1); } close_out=1; } speex_encoder_ctl(st, SPEEX_GET_FRAME_SIZE, &frame_size); speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &complexity); speex_encoder_ctl(st, SPEEX_SET_SAMPLING_RATE, &rate); if (quality >= 0) { if (vbr_enabled) { if (vbr_max>0) speex_encoder_ctl(st, SPEEX_SET_VBR_MAX_BITRATE, &vbr_max); speex_encoder_ctl(st, SPEEX_SET_VBR_QUALITY, &vbr_quality); } else speex_encoder_ctl(st, SPEEX_SET_QUALITY, &quality); } if (bitrate) { if (quality >= 0 && vbr_enabled) fprintf (stderr, "Warning: --bitrate option is overriding --quality\n"); speex_encoder_ctl(st, SPEEX_SET_BITRATE, &bitrate); } if (vbr_enabled) { tmp=1; speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp); } else if (vad_enabled) { tmp=1; speex_encoder_ctl(st, SPEEX_SET_VAD, &tmp); } if (dtx_enabled) speex_encoder_ctl(st, SPEEX_SET_DTX, &tmp); if (dtx_enabled && !(vbr_enabled || abr_enabled || vad_enabled)) { fprintf (stderr, "Warning: --dtx is useless without --vad, --vbr or --abr\n"); } else if ((vbr_enabled || abr_enabled) && (vad_enabled)) { fprintf (stderr, "Warning: --vad is already implied by --vbr or --abr\n"); } if (with_skeleton) { fprintf (stderr, "Warning: Enabling skeleton output may cause some decoders to fail.\n"); } if (abr_enabled) { speex_encoder_ctl(st, SPEEX_SET_ABR, &abr_enabled); } speex_encoder_ctl(st, SPEEX_SET_HIGHPASS, &highpass_enabled); speex_encoder_ctl(st, SPEEX_GET_LOOKAHEAD, &lookahead); #ifdef USE_SPEEXDSP if (denoise_enabled || agc_enabled) { preprocess = speex_preprocess_state_init(frame_size, rate); speex_preprocess_ctl(preprocess, SPEEX_PREPROCESS_SET_DENOISE, &denoise_enabled); speex_preprocess_ctl(preprocess, SPEEX_PREPROCESS_SET_AGC, &agc_enabled); lookahead += frame_size; } #endif /* first packet should be the skeleton header. */ if (with_skeleton) { add_fishead_packet(&so); if ((ret = flush_ogg_stream_to_file(&so, fout))) { fprintf (stderr,"Error: failed skeleton (fishead) header to output stream\n"); exit(1); } else bytes_written += ret; } /*Write header*/ { int packet_size; op.packet = (unsigned char *)speex_header_to_packet(&header, &packet_size); op.bytes = packet_size; op.b_o_s = 1; op.e_o_s = 0; op.granulepos = 0; op.packetno = 0; ogg_stream_packetin(&os, &op); free(op.packet); while((result = ogg_stream_flush(&os, &og))) { if(!result) break; ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } op.packet = (unsigned char *)comments; op.bytes = comments_length; op.b_o_s = 0; op.e_o_s = 0; op.granulepos = 0; op.packetno = 1; ogg_stream_packetin(&os, &op); } /* fisbone packet should be write after all bos pages */ if (with_skeleton) { add_fisbone_packet(&so, os.serialno, &header); if ((ret = flush_ogg_stream_to_file(&so, fout))) { fprintf (stderr,"Error: failed writing skeleton (fisbone )header to output stream\n"); exit(1); } else bytes_written += ret; } /* writing the rest of the speex header packets */ while((result = ogg_stream_flush(&os, &og))) { if(!result) break; ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } free(comments); /* write the skeleton eos packet */ if (with_skeleton) { add_eos_packet_to_stream(&so); if ((ret = flush_ogg_stream_to_file(&so, fout))) { fprintf (stderr,"Error: failed writing skeleton header to output stream\n"); exit(1); } else bytes_written += ret; } speex_bits_init(&bits); if (!wave_input) { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, first_bytes, NULL); } else { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); } if (nb_samples==0) eos=1; total_samples += nb_samples; nb_encoded = -lookahead; /*Main encoding loop (one frame per iteration)*/ while (!eos || total_samples>nb_encoded) { id++; /*Encode current frame*/ if (chan==2) speex_encode_stereo_int(input, frame_size, &bits); #ifdef USE_SPEEXDSP if (preprocess) speex_preprocess(preprocess, input, NULL); #endif speex_encode_int(st, input, &bits); nb_encoded += frame_size; if (print_bitrate) { int tmp; char ch=13; speex_encoder_ctl(st, SPEEX_GET_BITRATE, &tmp); fputc (ch, stderr); cumul_bits += tmp; enc_frames += 1; if (!quiet) { if (vad_enabled || vbr_enabled || abr_enabled) fprintf (stderr, "Bitrate is use: %d bps (average %d bps) ", tmp, (int)(cumul_bits/enc_frames)); else fprintf (stderr, "Bitrate is use: %d bps ", tmp); if (output_rate) printf ("%d\n", tmp); } } if (wave_input) { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); } else { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, NULL); } if (nb_samples==0) { eos=1; } if (eos && total_samples<=nb_encoded) op.e_o_s = 1; else op.e_o_s = 0; total_samples += nb_samples; if ((id+1)%nframes!=0) continue; speex_bits_insert_terminator(&bits); nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES); speex_bits_reset(&bits); op.packet = (unsigned char *)cbits; op.bytes = nbBytes; op.b_o_s = 0; /*Is this redundent?*/ if (eos && total_samples<=nb_encoded) op.e_o_s = 1; else op.e_o_s = 0; op.granulepos = (id+1)*frame_size-lookahead; if (op.granulepos>total_samples) op.granulepos = total_samples; /*printf ("granulepos: %d %d %d %d %d %d\n", (int)op.granulepos, id, nframes, lookahead, 5, 6);*/ op.packetno = 2+id/nframes; ogg_stream_packetin(&os, &op); /*Write all new pages (most likely 0 or 1)*/ while (ogg_stream_pageout(&os,&og)) { ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } } if ((id+1)%nframes!=0) { while ((id+1)%nframes!=0) { id++; speex_bits_pack(&bits, 15, 5); } nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES); op.packet = (unsigned char *)cbits; op.bytes = nbBytes; op.b_o_s = 0; op.e_o_s = 1; op.granulepos = (id+1)*frame_size-lookahead; if (op.granulepos>total_samples) op.granulepos = total_samples; op.packetno = 2+id/nframes; ogg_stream_packetin(&os, &op); } /*Flush all pages left to be written*/ while (ogg_stream_flush(&os, &og)) { ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } speex_encoder_destroy(st); speex_bits_destroy(&bits); ogg_stream_clear(&os); if (close_in) fclose(fin); if (close_out) fclose(fout); return 0; }
int CompressorEffect::process_buffer(int64_t size, Samples **buffer, int64_t start_position, int sample_rate) { load_configuration(); // Calculate linear transfer from db levels.remove_all(); for(int i = 0; i < config.levels.total; i++) { levels.append(); levels.values[i].x = DB::fromdb(config.levels.values[i].x); levels.values[i].y = DB::fromdb(config.levels.values[i].y); } min_x = DB::fromdb(config.min_db); min_y = DB::fromdb(config.min_db); max_x = 1.0; max_y = 1.0; int reaction_samples = (int)(config.reaction_len * sample_rate + 0.5); int decay_samples = (int)(config.decay_len * sample_rate + 0.5); int trigger = CLIP(config.trigger, 0, PluginAClient::total_in_buffers - 1); CLAMP(reaction_samples, -1000000, 1000000); CLAMP(decay_samples, reaction_samples, 1000000); CLAMP(decay_samples, 1, 1000000); if(labs(reaction_samples) < 1) reaction_samples = 1; if(labs(decay_samples) < 1) decay_samples = 1; int total_buffers = get_total_buffers(); if(reaction_samples >= 0) { if(target_current_sample < 0) target_current_sample = reaction_samples; for(int i = 0; i < total_buffers; i++) { read_samples(buffer[i], i, sample_rate, start_position, size); } double current_slope = (next_target - previous_target) / reaction_samples; double *trigger_buffer = buffer[trigger]->get_data(); for(int i = 0; i < size; i++) { // Get slope required to reach current sample from smoothed sample over reaction // length. double sample; switch(config.input) { case CompressorConfig::MAX: { double max = 0; for(int j = 0; j < total_buffers; j++) { sample = fabs(buffer[j]->get_data()[i]); if(sample > max) max = sample; } sample = max; break; } case CompressorConfig::TRIGGER: sample = fabs(trigger_buffer[i]); break; case CompressorConfig::SUM: { double max = 0; for(int j = 0; j < total_buffers; j++) { sample = fabs(buffer[j]->get_data()[i]); max += sample; } sample = max; break; } } double new_slope = (sample - current_value) / reaction_samples; // Slope greater than current slope if(new_slope >= current_slope && (current_slope >= 0 || new_slope >= 0)) { next_target = sample; previous_target = current_value; target_current_sample = 0; target_samples = reaction_samples; current_slope = new_slope; } else if(sample > next_target && current_slope < 0) { next_target = sample; previous_target = current_value; target_current_sample = 0; target_samples = decay_samples; current_slope = (sample - current_value) / decay_samples; } // Current smoothed sample came up without finding higher slope if(target_current_sample >= target_samples) { next_target = sample; previous_target = current_value; target_current_sample = 0; target_samples = decay_samples; current_slope = (sample - current_value) / decay_samples; } // Update current value and store gain current_value = (next_target * target_current_sample + previous_target * (target_samples - target_current_sample)) / target_samples; target_current_sample++; if(config.smoothing_only) { for(int j = 0; j < total_buffers; j++) buffer[j]->get_data()[i] = current_value; } else { double gain = calculate_gain(current_value); for(int j = 0; j < total_buffers; j++) { buffer[j]->get_data()[i] *= gain; } } } } else { if(target_current_sample < 0) target_current_sample = target_samples; int64_t preview_samples = -reaction_samples; // Start of new buffer is outside the current buffer. Start buffer over. if(start_position < input_start || start_position >= input_start + input_size) { input_size = 0; input_start = start_position; } else // Shift current buffer so the buffer starts on start_position if(start_position > input_start && start_position < input_start + input_size) { if(input_buffer) { int len = input_start + input_size - start_position; for(int i = 0; i < total_buffers; i++) { memcpy(input_buffer[i]->get_data(), input_buffer[i]->get_data() + (start_position - input_start), len * sizeof(double)); } input_size = len; input_start = start_position; } } // Expand buffer to handle preview size if(size + preview_samples > input_allocated) { Samples **new_input_buffer = new Samples*[total_buffers]; for(int i = 0; i < total_buffers; i++) { new_input_buffer[i] = new Samples(size + preview_samples); if(input_buffer) { memcpy(new_input_buffer[i]->get_data(), input_buffer[i]->get_data(), input_size * sizeof(double)); delete input_buffer[i]; } } if(input_buffer) delete [] input_buffer; input_allocated = size + preview_samples; input_buffer = new_input_buffer; } // Append data to input buffer to construct readahead area. #define MAX_FRAGMENT_SIZE 131072 while(input_size < size + preview_samples) { int fragment_size = MAX_FRAGMENT_SIZE; if(fragment_size + input_size > size + preview_samples) fragment_size = size + preview_samples - input_size; for(int i = 0; i < total_buffers; i++) { input_buffer[i]->set_offset(input_size); //printf("CompressorEffect::process_buffer %d %p %d\n", __LINE__, input_buffer[i], input_size); read_samples(input_buffer[i], i, sample_rate, input_start + input_size, fragment_size); input_buffer[i]->set_offset(0); } input_size += fragment_size; } double current_slope = (next_target - previous_target) / target_samples; double *trigger_buffer = input_buffer[trigger]->get_data(); for(int i = 0; i < size; i++) { // Get slope from current sample to every sample in preview_samples. // Take highest one or first one after target_samples are up. // For optimization, calculate the first slope we really need. // Assume every slope up to the end of preview_samples has been calculated and // found <= to current slope. int first_slope = preview_samples - 1; // Need new slope immediately if(target_current_sample >= target_samples) first_slope = 1; for(int j = first_slope; j < preview_samples; j++) { double sample; switch(config.input) { case CompressorConfig::MAX: { double max = 0; for(int k = 0; k < total_buffers; k++) { sample = fabs(input_buffer[k]->get_data()[i + j]); if(sample > max) max = sample; } sample = max; break; } case CompressorConfig::TRIGGER: sample = fabs(trigger_buffer[i + j]); break; case CompressorConfig::SUM: { double max = 0; for(int k = 0; k < total_buffers; k++) { sample = fabs(input_buffer[k]->get_data()[i + j]); max += sample; } sample = max; break; } } double new_slope = (sample - current_value) / j; // Got equal or higher slope if(new_slope >= current_slope && (current_slope >= 0 || new_slope >= 0)) { target_current_sample = 0; target_samples = j; current_slope = new_slope; next_target = sample; previous_target = current_value; } else if(sample > next_target && current_slope < 0) { target_current_sample = 0; target_samples = decay_samples; current_slope = (sample - current_value) / decay_samples; next_target = sample; previous_target = current_value; } // Hit end of current slope range without finding higher slope if(target_current_sample >= target_samples) { target_current_sample = 0; target_samples = decay_samples; current_slope = (sample - current_value) / decay_samples; next_target = sample; previous_target = current_value; } } // Update current value and multiply gain current_value = (next_target * target_current_sample + previous_target * (target_samples - target_current_sample)) / target_samples; //buffer[0][i] = current_value; target_current_sample++; if(config.smoothing_only) { for(int j = 0; j < total_buffers; j++) { buffer[j]->get_data()[i] = current_value; } } else { double gain = calculate_gain(current_value); for(int j = 0; j < total_buffers; j++) { buffer[j]->get_data()[i] = input_buffer[j]->get_data()[i] * gain; } } } } return 0; }
int TimeStretch::process_loop(Samples *buffer, int64_t &write_length) { int result = 0; int64_t predicted_total = (int64_t)((double)get_total_len() * scale + 0.5); int samples_rendered = 0; // The FFT case if(use_fft) { samples_rendered = get_buffer_size(); pitch->process_buffer(total_written, samples_rendered, buffer, PLAY_FORWARD); } else // The windowing case { // Length to read based on desired output size int64_t size = (int64_t)((double)get_buffer_size() / scale); if(input_allocated < size) { if(input) delete input; input = new Samples(size); input_allocated = size; } read_samples(input, 0, current_position, size); current_position += size; samples_rendered = stretch->process(input, size); if(samples_rendered) { samples_rendered = MIN(samples_rendered, get_buffer_size()); stretch->read_output(buffer, samples_rendered); } } total_written += samples_rendered; // Trim output to predicted length of stretched selection. if(total_written > predicted_total) { samples_rendered -= total_written - predicted_total; result = 1; } write_length = samples_rendered; if(PluginClient::interactive) result = progress->update(total_written); return result; }
int main(int argc, char **argv) { int nb_samples, total_samples=0, nb_encoded; int c; int option_index = 0; char *inFile, *outFile; FILE *fin, *fout; short input[MAX_FRAME_SIZE]; celt_int32_t frame_size; int quiet=0; int nbBytes; CELTMode *mode; void *st; unsigned char bits[MAX_FRAME_BYTES]; int with_skeleton = 0; struct option long_options[] = { {"bitrate", required_argument, NULL, 0}, {"comp", required_argument, NULL, 0}, {"skeleton",no_argument,NULL, 0}, {"help", no_argument, NULL, 0}, {"quiet", no_argument, NULL, 0}, {"le", no_argument, NULL, 0}, {"be", no_argument, NULL, 0}, {"8bit", no_argument, NULL, 0}, {"16bit", no_argument, NULL, 0}, {"mono", no_argument, NULL, 0}, {"stereo", no_argument, NULL, 0}, {"rate", required_argument, NULL, 0}, {"version", no_argument, NULL, 0}, {"version-short", no_argument, NULL, 0}, {"comment", required_argument, NULL, 0}, {"author", required_argument, NULL, 0}, {"title", required_argument, NULL, 0}, {0, 0, 0, 0} }; int print_bitrate=0; celt_int32_t rate=44100; celt_int32_t size; int chan=1; int fmt=16; int lsb=1; ogg_stream_state os; ogg_stream_state so; /* ogg stream for skeleton bitstream */ ogg_page og; ogg_packet op; int bytes_written=0, ret, result; int id=-1; CELT051Header header; char vendor_string[64]; char *comments; int comments_length; int close_in=0, close_out=0; int eos=0; celt_int32_t bitrate=-1; char first_bytes[12]; int wave_input=0; celt_int32_t lookahead = 0; int bytes_per_packet=48; int complexity=-127; snprintf(vendor_string, sizeof(vendor_string), "Encoded with CELT\n"); comment_init(&comments, &comments_length, vendor_string); /*Process command-line options*/ while(1) { c = getopt_long (argc, argv, "hvV", long_options, &option_index); if (c==-1) break; switch(c) { case 0: if (strcmp(long_options[option_index].name,"bitrate")==0) { bitrate = atoi (optarg); } else if (strcmp(long_options[option_index].name,"skeleton")==0) { with_skeleton=1; } else if (strcmp(long_options[option_index].name,"help")==0) { usage(); exit(0); } else if (strcmp(long_options[option_index].name,"quiet")==0) { quiet = 1; } else if (strcmp(long_options[option_index].name,"version")==0) { version(); exit(0); } else if (strcmp(long_options[option_index].name,"version-short")==0) { version_short(); exit(0); } else if (strcmp(long_options[option_index].name,"le")==0) { lsb=1; } else if (strcmp(long_options[option_index].name,"be")==0) { lsb=0; } else if (strcmp(long_options[option_index].name,"8bit")==0) { fmt=8; } else if (strcmp(long_options[option_index].name,"16bit")==0) { fmt=16; } else if (strcmp(long_options[option_index].name,"stereo")==0) { chan=2; } else if (strcmp(long_options[option_index].name,"mono")==0) { chan=1; } else if (strcmp(long_options[option_index].name,"rate")==0) { rate=atoi (optarg); } else if (strcmp(long_options[option_index].name,"comp")==0) { complexity=atoi (optarg); } else if (strcmp(long_options[option_index].name,"comment")==0) { if (!strchr(optarg, '=')) { fprintf (stderr, "Invalid comment: %s\n", optarg); fprintf (stderr, "Comments must be of the form name=value\n"); exit(1); } comment_add(&comments, &comments_length, NULL, optarg); } else if (strcmp(long_options[option_index].name,"author")==0) { comment_add(&comments, &comments_length, "author=", optarg); } else if (strcmp(long_options[option_index].name,"title")==0) { comment_add(&comments, &comments_length, "title=", optarg); } break; case 'h': usage(); exit(0); break; case 'v': version(); exit(0); break; case 'V': print_bitrate=1; break; case '?': usage(); exit(1); break; } } fprintf(stderr,"\nWARNING: This encoder is a CELT *PRERELEASE*. It produces streams that are\n" " not decodable by ANY OTHER VERSION. These streams will NOT be\n" " supported or decodable by any future CELT release.\n\n"); if (argc-optind!=2) { usage(); exit(1); } inFile=argv[optind]; outFile=argv[optind+1]; /*Initialize Ogg stream struct*/ srand(time(NULL)); if (ogg_stream_init(&os, rand())==-1) { fprintf(stderr,"Error: stream init failed\n"); exit(1); } if (with_skeleton && ogg_stream_init(&so, rand())==-1) { fprintf(stderr,"Error: stream init failed\n"); exit(1); } if (strcmp(inFile, "-")==0) { #if defined WIN32 || defined _WIN32 _setmode(_fileno(stdin), _O_BINARY); #elif defined OS2 _fsetmode(stdin,"b"); #endif fin=stdin; } else { fin = fopen(inFile, "rb"); if (!fin) { perror(inFile); exit(1); } close_in=1; } { fread(first_bytes, 1, 12, fin); if (strncmp(first_bytes,"RIFF",4)==0 && strncmp(first_bytes,"RIFF",4)==0) { if (read_wav_header(fin, &rate, &chan, &fmt, &size)==-1) exit(1); wave_input=1; lsb=1; /* CHECK: exists big-endian .wav ?? */ } } if (chan == 1) { if (bitrate < 0) bitrate = 64; if (bitrate < 32) bitrate = 32; if (bitrate > 110) bitrate = 110; } else if (chan == 2) { if (bitrate < 0) bitrate = 128; if (bitrate < 64) bitrate = 64; if (bitrate > 150) bitrate = 150; } else { fprintf (stderr, "Only mono and stereo are supported\n"); return 1; } mode = celt051_mode_create(rate, chan, 256, NULL); if (!mode) return 1; celt051_mode_info(mode, CELT_GET_FRAME_SIZE, &frame_size); bytes_per_packet = (bitrate*1000*frame_size/rate+4)/8; celt051_header_init(&header, mode); header.nb_channels = chan; { char *st_string="mono"; if (chan==2) st_string="stereo"; if (!quiet) fprintf (stderr, "Encoding %d Hz audio using %s (%d bytes per packet)\n", header.sample_rate, st_string, bytes_per_packet); } /*fprintf (stderr, "Encoding %d Hz audio at %d bps using %s mode\n", header.rate, mode->bitrate, mode->modeName);*/ /*Initialize CELT encoder*/ st = celt051_encoder_create(mode); if (complexity!=-127) { if (celt051_encoder_ctl(st, CELT_SET_COMPLEXITY(complexity)) != CELT_OK) { fprintf (stderr, "Only complexity 0 through 10 is supported\n"); return 1; } } if (strcmp(outFile,"-")==0) { #if defined WIN32 || defined _WIN32 _setmode(_fileno(stdout), _O_BINARY); #endif fout=stdout; } else { fout = fopen(outFile, "wb"); if (!fout) { perror(outFile); exit(1); } close_out=1; } if (with_skeleton) { fprintf (stderr, "Warning: Enabling skeleton output may cause some decoders to fail.\n"); } /* first packet should be the skeleton header. */ if (with_skeleton) { add_fishead_packet(&so); if ((ret = flush_ogg_stream_to_file(&so, fout))) { fprintf (stderr,"Error: failed skeleton (fishead) header to output stream\n"); exit(1); } else bytes_written += ret; } /*Write header*/ { unsigned char header_data[100]; int packet_size = celt051_header_to_packet(&header, header_data, 100); op.packet = header_data; op.bytes = packet_size; op.b_o_s = 1; op.e_o_s = 0; op.granulepos = 0; op.packetno = 0; ogg_stream_packetin(&os, &op); while((result = ogg_stream_flush(&os, &og))) { if(!result) break; ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } op.packet = (unsigned char *)comments; op.bytes = comments_length; op.b_o_s = 0; op.e_o_s = 0; op.granulepos = 0; op.packetno = 1; ogg_stream_packetin(&os, &op); } /* fisbone packet should be write after all bos pages */ if (with_skeleton) { add_fisbone_packet(&so, os.serialno, &header); if ((ret = flush_ogg_stream_to_file(&so, fout))) { fprintf (stderr,"Error: failed writing skeleton (fisbone )header to output stream\n"); exit(1); } else bytes_written += ret; } /* writing the rest of the celt header packets */ while((result = ogg_stream_flush(&os, &og))) { if(!result) break; ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } free(comments); /* write the skeleton eos packet */ if (with_skeleton) { add_eos_packet_to_stream(&so); if ((ret = flush_ogg_stream_to_file(&so, fout))) { fprintf (stderr,"Error: failed writing skeleton header to output stream\n"); exit(1); } else bytes_written += ret; } if (!wave_input) { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, first_bytes, NULL); } else { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); } if (nb_samples==0) eos=1; total_samples += nb_samples; nb_encoded = -lookahead; /*Main encoding loop (one frame per iteration)*/ while (!eos || total_samples>nb_encoded) { id++; /*Encode current frame*/ nbBytes = celt051_encode(st, input, NULL, bits, bytes_per_packet); if (nbBytes<0) { fprintf(stderr, "Got error %d while encoding. Aborting.\n", nbBytes); break; } nb_encoded += frame_size; if (wave_input) { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); } else { nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, NULL); } if (nb_samples==0) { eos=1; } if (eos && total_samples<=nb_encoded) op.e_o_s = 1; else op.e_o_s = 0; total_samples += nb_samples; op.packet = (unsigned char *)bits; op.bytes = nbBytes; op.b_o_s = 0; /*Is this redundent?*/ if (eos && total_samples<=nb_encoded) op.e_o_s = 1; else op.e_o_s = 0; op.granulepos = (id+1)*frame_size-lookahead; if (op.granulepos>total_samples) op.granulepos = total_samples; /*printf ("granulepos: %d %d %d %d %d %d\n", (int)op.granulepos, id, nframes, lookahead, 5, 6);*/ op.packetno = 2+id; ogg_stream_packetin(&os, &op); /*Write all new pages (most likely 0 or 1)*/ while (ogg_stream_pageout(&os,&og)) { ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } } /*Flush all pages left to be written*/ while (ogg_stream_flush(&os, &og)) { ret = oe_write_page(&og, fout); if(ret != og.header_len + og.body_len) { fprintf (stderr,"Error: failed writing header to output stream\n"); exit(1); } else bytes_written += ret; } celt051_encoder_destroy(st); celt051_mode_destroy(mode); ogg_stream_clear(&os); if (close_in) fclose(fin); if (close_out) fclose(fout); return 0; }