static void pipe_Exit(void) { #if defined unix || (defined __APPLE__ && defined __MACH__) int pstat; pid_t pid2; #endif VC_Exit(); MikMod_free(audiobuffer); if(pipeout) { _mm_delete_file_writer(pipeout); pipeout=NULL; } if(pipefile) { #if !defined unix && (!defined __APPLE__ || !defined __MACH__) #ifdef __WATCOMC__ _pclose(pipefile); #else pclose(pipefile); #endif #ifdef __EMX__ _fsetmode(stdout,"t"); #endif #else fclose(pipefile); do { pid2=waitpid(pid,&pstat,0); } while (pid2==-1 && errno==EINTR); #endif pipefile=NULL; } }
static BOOL stdout_Init(void) { if(!(audiobuffer=(SBYTE*)_mm_malloc(BUFFERSIZE))) return 1; #ifdef __EMX__ _fsetmode(stdout,"b"); #endif return VC_Init(); }
static void stdout_Exit(void) { VC_Exit(); #ifdef __EMX__ _fsetmode(stdout,"t"); #endif MikMod_free(audiobuffer); audiobuffer=NULL; }
static BOOL pipe_Init(void) { if(!target) { _mm_errno=MMERR_OPENING_FILE; return 1; } #if !defined unix && (!defined __APPLE__ || !defined __MACH__) #ifdef __EMX__ _fsetmode(stdout, "b"); #endif #ifdef __WATCOMC__ pipefile = _popen(target, "wb"); #else pipefile = popen(target, "wb"); #endif if (!pipefile) { _mm_errno=MMERR_OPENING_FILE; return 1; } #else /* poor man's popen() */ if (pipe(pipefd)) { _mm_errno = MMERR_OPENING_FILE; return 1; } switch (pid=fork()) { case -1: close(pipefd[0]); close(pipefd[1]); pipefd[0]=pipefd[1]=-1; _mm_errno=MMERR_OPENING_FILE; return 1; case 0: if (pipefd[0]) { dup2(pipefd[0],0); close(pipefd[0]); } close(pipefd[1]); if (!MD_DropPrivileges()) execl("/bin/sh","sh","-c",target,NULL); exit(127); } close(pipefd[0]); if (!(pipefile=fdopen(pipefd[1],"wb"))) { _mm_errno=MMERR_OPENING_FILE; return 1; } #endif if(!(pipeout=_mm_new_file_writer(pipefile))) return 1; if(!(audiobuffer=(SBYTE*)MikMod_malloc(BUFFERSIZE))) return 1; md_mode|=DMODE_SOFT_MUSIC|DMODE_SOFT_SNDFX; return VC_Init(); }
NCURSES_SP_NAME(nonl) (NCURSES_SP_DCL0) { T((T_CALLED("nonl(%p)"), (void *) SP_PARM)); if (0 == SP_PARM) returnCode(ERR); SP_PARM->_nl = FALSE; #ifdef __EMX__ _nc_flush(); _fsetmode(NC_OUTPUT(SP_PARM), "b"); #endif returnCode(OK); }
int nonl(void) { T((T_CALLED("nonl()"))); SP->_nl = FALSE; #ifdef __EMX__ fflush(SP->_ofp); _fsetmode(SP->_ofp, "b"); #endif returnCode(OK); }
nonl(void) { T((T_CALLED("nonl()"))); SP->_nl = FALSE; #ifdef __EMX__ _nc_flush(); _fsetmode(NC_OUTPUT, "b"); #endif returnCode(OK); }
int lame_set_stream_binary_mode ( FILE* const fp ) { #if defined __EMX__ _fsetmode ( fp, "b" ); #elif defined __BORLANDC__ setmode (_fileno(fp), O_BINARY ); #elif defined __CYGWIN__ setmode ( fileno(fp), _O_BINARY ); #elif defined _WIN32 _setmode (_fileno(fp), _O_BINARY ); #endif return 0; }
int lame_set_stream_binary_mode(FILE * const fp) { #if defined __EMX__ _fsetmode(fp, "b"); #elif defined __BORLANDC__ setmode(_fileno(fp), O_BINARY); #elif defined __CYGWIN__ setmode(fileno(fp), _O_BINARY); #elif defined _WIN32 _setmode(_fileno(fp), _O_BINARY); #else (void) fp; /* doing nothing here, silencing the compiler only. */ #endif 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]; 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; }
FILE * OpenSndFile(lame_global_flags *gfp,const char* inPath, int default_samp, int default_channels) { struct stat sb; void parse_file_header(lame_global_flags *gfp,FILE *sf); /* set the defaults from info incase we cannot determine them from file */ num_samples=MAX_U_32_NUM; samp_freq=default_samp; num_channels = default_channels; if (!strcmp(inPath, "-")) { /* Read from standard input. */ #ifdef __EMX__ _fsetmode(stdin,"b"); #elif (defined __BORLANDC__) setmode(_fileno(stdin), O_BINARY); #elif (defined __CYGWIN__) setmode(fileno(stdin), _O_BINARY); #elif (defined _WIN32) _setmode(_fileno(stdin), _O_BINARY); #endif musicin = stdin; } else { if ((musicin = fopen(inPath, "rb")) == NULL) { fprintf(stderr, "Could not find \"%s\".\n", inPath); exit(1); } } input_bitrate=0; if (gfp->input_format==sf_mp3) { #ifdef AMIGA_MPEGA if (-1==lame_decode_initfile(inPath,&num_channels,&samp_freq,&input_bitrate,&num_samples)) { fprintf(stderr,"Error reading headers in mp3 input file %s.\n", inPath); exit(1); } #endif #ifdef HAVEMPGLIB if (-1==lame_decode_initfile(musicin,&num_channels,&samp_freq,&input_bitrate,&num_samples)) { fprintf(stderr,"Error reading headers in mp3 input file %s.\n", inPath); exit(1); } #endif }else{ if (gfp->input_format != sf_raw) { parse_file_header(gfp,musicin); } if (gfp->input_format==sf_raw) { /* assume raw PCM */ fprintf(stderr, "Assuming raw pcm input file"); if (gfp->swapbytes==TRUE) fprintf(stderr, " : Forcing byte-swapping\n"); else fprintf(stderr, "\n"); } } if (num_samples==MAX_U_32_NUM && musicin != stdin) { /* try to figure out num_samples */ if (0==stat(inPath,&sb)) { /* try file size, assume 2 bytes per sample */ if (gfp->input_format == sf_mp3) { FLOAT totalseconds = (sb.st_size*8.0/(1000.0*GetSndBitrate())); num_samples= totalseconds*GetSndSampleRate(); }else{ num_samples = sb.st_size/(2*GetSndChannels()); } } } return musicin; }
int main(int argc, char *argv[]) { FILE *in = stdin; FILE *out = stdout; FILE *sig = NULL; char output_name[MAXPATHLEN] = "(stdout)"; char input_name[MAXPATHLEN] = "(stdin)"; char signature_name[MAXPATHLEN]; int c; int row, col; int n; double quality = 0.0; int filter = 0; int method = -1; int level = 0; char filter_name[MAXPATHLEN] = ""; int seed; int verbose = 0; gray **image; Image_tree dwts; gray maxval; int rows, cols, colors, format; progname = argv[0]; pgm_init(&argc, argv); #ifdef __EMX__ _fsetmode(in, "b"); _fsetmode(out, "b"); #endif while ((c = getopt(argc, argv, "e:f:F:h?l:o:q:s:v:")) != EOF) { switch (c) { case 'e': method = atoi(optarg); if (method < 0) { fprintf(stderr, "%s: wavelet filtering method %d out of range\n", progname, method); exit(1); } break; case 'f': filter = atoi(optarg); if (filter <= 0) { fprintf(stderr, "%s: filter number %d out of range\n", progname, filter); exit(1); } break; case 'F': strcpy(filter_name, optarg); break; case 'h': case '?': usage(); break; case 'l': level = atoi(optarg); if (level < 1) { fprintf(stderr, "%s: embedding level out of range\n", progname); exit(1); } break; case 'o': if ((out = fopen(optarg, "wb")) == NULL) { fprintf(stderr, "%s: unable to open output file %s\n", progname, optarg); exit(1); } strcpy(output_name, optarg); break; case 'q': quality = atoi(optarg); if (quality <= 0) { fprintf(stderr, "%s: quality factor %d out of range\n", progname, quality); exit(1); } break; case 's': if ((sig = fopen(optarg, "r")) == NULL) { fprintf(stderr, "%s: unable to open signature file %s\n", progname, optarg); exit(1); } strcpy(signature_name, optarg); break; case 'v': verbose = atoi(optarg); if (verbose < 0) { fprintf(stderr, "%s: verbosity level %d out of range\n", progname, verbose); exit(1); } break; } } argc -= optind; argv += optind; if (argc > 1) { usage(); exit(1); } if (argc == 1 && *argv[0] != '-') if ((in = fopen(argv[0], "rb")) == NULL) { fprintf(stderr, "%s: unable to open input file %s\n", progname, argv[0]); exit(1); } else strcpy(input_name, argv[0]); if (sig) { char line[32]; fgets(line, sizeof(line), sig); if (strspn(line, "KDSG") >= 4) { fscanf(sig, "%d\n", &n); if (quality == 0.0) fscanf(sig, "%lf\n", &quality); else fscanf(sig, "%*f\n"); if (method < 0) fscanf(sig, "%d\n", &method); else fscanf(sig, "%*d\n"); if (filter == 0) fscanf(sig, "%d\n", &filter); else fscanf(sig, "%*d\n"); if (!strcmp(filter_name, "")) fscanf(sig, "%[^\n\r]\n", filter_name); else fscanf(sig, "%*[^\n\r]\n"); if (level == 0) fscanf(sig, "%d\n", &level); else fscanf(sig, "%*d\n"); fscanf(sig, "%d\n", &seed); srandom(seed); n_signature = NBITSTOBYTES(nbit_signature); fread(signature, sizeof(char), n_signature, sig); fscanf(sig, "\n"); } else { fprintf(stderr, "%s: invalid signature file %s\n", progname, signature_name); exit(1); } fclose(sig); } else { fprintf(stderr, "%s: signature file not specified, use -s file option\n", progname); exit(1); } pgm_readpgminit(in, &cols, &rows, &maxval, &format); image = pgm_allocarray(cols, rows); for (row = 0; row < rows; row++) pgm_readpgmrow(in, image[row], cols, maxval, format); fclose(in); // check watermark dimensions and decomposition level // decomposition of image init_dwt(cols, rows, filter_name, filter, level, method); #ifdef POLLEN_STUFF { double alpha, beta; char *alpha_str = getenv("POLLEN_ALPHA"), *beta_str = getenv("POLLEN_BETA"); if (alpha_str && beta_str) { alpha = atof(alpha_str); beta = atof(beta_str); if (alpha < -M_PI || alpha >= M_PI) { fprintf(stderr, "%s: pollen - alpha %f out of range\n", progname, alpha); exit(1); } if (beta < -M_PI || beta >= M_PI) { fprintf(stderr, "%s: pollen - beta %f out of range\n", progname, beta); exit(1); } if (verbose > 7) fprintf(stderr, "%s: pollen - alpha %f, beta %f\n", progname, alpha, beta); dwt_pollen_filter(alpha, beta); } } #endif dwts = fdwt(image); // create 'image' from binary watermark // decomposition of watermark init_dwt(cols, rows, filter_name, filter, 1, method); // dwts = fdwt(watermark); // calculate mean value of image and set alpha // setup of contrast sensitivity matrix // segment detail images at each level // calculate DFT of each segment // compute salience for each segment // calculate gamma or each detail image // embed watermark // reconstruction of watermarked image idwt(dwts, image); pgm_writepgminit(out, cols, rows, maxval, 0); for (row = 0; row < rows; row++) pgm_writepgmrow(out, image[row], cols, maxval, 0); fclose(out); pgm_freearray(image, rows); exit(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]; 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; }
int opusEncoder(int argc, char **argv) { static const input_format raw_format = {NULL, 0, raw_open, wav_close, "raw",N_("RAW file reader")}; int option_index=0; struct option long_options[] = { {"quiet", no_argument, NULL, 0}, {"bitrate", required_argument, NULL, 0}, {"hard-cbr",no_argument,NULL, 0}, {"vbr",no_argument,NULL, 0}, {"cvbr",no_argument,NULL, 0}, {"comp", required_argument, NULL, 0}, {"complexity", required_argument, NULL, 0}, {"framesize", required_argument, NULL, 0}, {"expect-loss", required_argument, NULL, 0}, {"downmix-mono",no_argument,NULL, 0}, {"downmix-stereo",no_argument,NULL, 0}, {"no-downmix",no_argument,NULL, 0}, {"max-delay", required_argument, NULL, 0}, {"serial", required_argument, NULL, 0}, {"save-range", required_argument, NULL, 0}, {"set-ctl-int", required_argument, NULL, 0}, {"help", no_argument, NULL, 0}, {"raw", no_argument, NULL, 0}, {"raw-bits", required_argument, NULL, 0}, {"raw-rate", required_argument, NULL, 0}, {"raw-chan", required_argument, NULL, 0}, {"raw-endianness", required_argument, NULL, 0}, {"ignorelength", 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}, {"artist", required_argument, NULL, 0}, {"title", required_argument, NULL, 0}, {"album", required_argument, NULL, 0}, {"date", required_argument, NULL, 0}, {"genre", required_argument, NULL, 0}, {"picture", required_argument, NULL, 0}, {"padding", required_argument, NULL, 0}, {"discard-comments", no_argument, NULL, 0}, {"discard-pictures", no_argument, NULL, 0}, {0, 0, 0, 0} }; int i, ret; int cline_size; OpusMSEncoder *st; const char *opus_version; unsigned char *packet; float *input; /*I/O*/ oe_enc_opt inopt; const input_format *in_format; char *inFile; char *outFile; char *range_file; FILE *fin; FILE *fout; FILE *frange; ogg_stream_state os; ogg_page og; ogg_packet op; ogg_int64_t last_granulepos=0; ogg_int64_t enc_granulepos=0; ogg_int64_t original_samples=0; ogg_int32_t id=-1; int last_segments=0; int eos=0; OpusHeader header; char ENCODER_string[1024]; /*Counters*/ opus_int64 nb_encoded=0; opus_int64 bytes_written=0; opus_int64 pages_out=0; opus_int64 total_bytes=0; opus_int64 total_samples=0; opus_int32 nbBytes; opus_int32 nb_samples; opus_int32 peak_bytes=0; opus_int32 min_bytes; time_t start_time; time_t stop_time; time_t last_spin=0; int last_spin_len=0; /*Settings*/ int quiet=0; int max_frame_bytes; opus_int32 bitrate=-1; opus_int32 rate=48000; opus_int32 coding_rate=48000; opus_int32 frame_size=960; int chan=2; int with_hard_cbr=0; int with_cvbr=0; int expect_loss=0; int complexity=10; int downmix=0; int *opt_ctls_ctlval; int opt_ctls=0; int max_ogg_delay=48000; /*48kHz samples*/ int seen_file_icons=0; int comment_padding=512; int serialno; opus_int32 lookahead=0; #ifdef WIN_UNICODE int argc_utf8; char **argv_utf8; #endif if(query_cpu_support()){ fprintf(stderr,"\n\n** WARNING: This program was compiled with SSE%s\n",query_cpu_support()>1?"2":""); fprintf(stderr," but this CPU claims to lack these instructions. **\n\n"); } #ifdef WIN_UNICODE (void)argc; (void)argv; init_commandline_arguments_utf8(&argc_utf8, &argv_utf8); #endif opt_ctls_ctlval=NULL; frange=NULL; range_file=NULL; in_format=NULL; inopt.channels=chan; inopt.rate=coding_rate=rate; /* 0 dB gain is recommended unless you know what you're doing */ inopt.gain=0; inopt.samplesize=16; inopt.endianness=0; inopt.rawmode=0; inopt.ignorelength=0; inopt.copy_comments=1; inopt.copy_pictures=1; start_time = time(NULL); srand(((getpid()&65535)<<15)^start_time); serialno=rand(); opus_version=opus_get_version_string(); /*Vendor string should just be the encoder library, the ENCODER comment specifies the tool used.*/ comment_init(&inopt.comments, &inopt.comments_length, opus_version); // snprintf(ENCODER_string, sizeof(ENCODER_string), "opusenc from %s %s",PACKAGE_NAME,PACKAGE_VERSION); comment_add(&inopt.comments, &inopt.comments_length, "ENCODER", ENCODER_string); /*Process command-line options*/ cline_size=0; while(1){ int c; int save_cmd=1; c=getopt_long(argc_utf8, argv_utf8, "hV", long_options, &option_index); if(c==-1) break; switch(c){ case 0: if(strcmp(long_options[option_index].name,"quiet")==0){ quiet=1; }else if(strcmp(long_options[option_index].name,"bitrate")==0){ bitrate=atof(optarg)*1000.; }else if(strcmp(long_options[option_index].name,"hard-cbr")==0){ with_hard_cbr=1; with_cvbr=0; }else if(strcmp(long_options[option_index].name,"cvbr")==0){ with_cvbr=1; with_hard_cbr=0; }else if(strcmp(long_options[option_index].name,"vbr")==0){ with_cvbr=0; with_hard_cbr=0; }else if(strcmp(long_options[option_index].name,"help")==0){ usage(); return 0;//exit(0); }else if(strcmp(long_options[option_index].name,"version")==0){ opustoolsversion(opus_version); return 0;//exit(0); }else if(strcmp(long_options[option_index].name,"version-short")==0){ opustoolsversion_short(opus_version); return 0;//exit(0); }else if(strcmp(long_options[option_index].name,"ignorelength")==0){ inopt.ignorelength=1; }else if(strcmp(long_options[option_index].name,"raw")==0){ inopt.rawmode=1; save_cmd=0; }else if(strcmp(long_options[option_index].name,"raw-bits")==0){ inopt.rawmode=1; inopt.samplesize=atoi(optarg); save_cmd=0; if(inopt.samplesize!=8&&inopt.samplesize!=16&&inopt.samplesize!=24){ fprintf(stderr,"Invalid bit-depth: %s\n",optarg); fprintf(stderr,"--raw-bits must be one of 8,16, or 24\n"); return 0;//exit(1); } }else if(strcmp(long_options[option_index].name,"raw-rate")==0){ inopt.rawmode=1; inopt.rate=atoi(optarg); save_cmd=0; }else if(strcmp(long_options[option_index].name,"raw-chan")==0){ inopt.rawmode=1; inopt.channels=atoi(optarg); save_cmd=0; }else if(strcmp(long_options[option_index].name,"raw-endianness")==0){ inopt.rawmode=1; inopt.endianness=atoi(optarg); save_cmd=0; }else if(strcmp(long_options[option_index].name,"downmix-mono")==0){ downmix=1; }else if(strcmp(long_options[option_index].name,"downmix-stereo")==0){ downmix=2; }else if(strcmp(long_options[option_index].name,"no-downmix")==0){ downmix=-1; }else if(strcmp(long_options[option_index].name,"expect-loss")==0){ expect_loss=atoi(optarg); if(expect_loss>100||expect_loss<0){ fprintf(stderr,"Invalid expect-loss: %s\n",optarg); fprintf(stderr,"Expected loss is a percent and must be 0-100.\n"); return 0;//exit(1); } }else if(strcmp(long_options[option_index].name,"comp")==0 || strcmp(long_options[option_index].name,"complexity")==0){ complexity=atoi(optarg); if(complexity>10||complexity<0){ fprintf(stderr,"Invalid complexity: %s\n",optarg); fprintf(stderr,"Complexity must be 0-10.\n"); return 0;//exit(1); } }else if(strcmp(long_options[option_index].name,"framesize")==0){ if(strcmp(optarg,"2.5")==0)frame_size=120; else if(strcmp(optarg,"5")==0)frame_size=240; else if(strcmp(optarg,"10")==0)frame_size=480; else if(strcmp(optarg,"20")==0)frame_size=960; else if(strcmp(optarg,"40")==0)frame_size=1920; else if(strcmp(optarg,"60")==0)frame_size=2880; else{ fprintf(stderr,"Invalid framesize: %s\n",optarg); fprintf(stderr,"Framesize must be 2.5, 5, 10, 20, 40, or 60.\n"); return 0;//exit(1); } }else if(strcmp(long_options[option_index].name,"max-delay")==0){ max_ogg_delay=floor(atof(optarg)*48.); if(max_ogg_delay<0||max_ogg_delay>48000){ fprintf(stderr,"Invalid max-delay: %s\n",optarg); fprintf(stderr,"max-delay 0-1000 ms.\n"); return 0;//exit(1); } }else if(strcmp(long_options[option_index].name,"serial")==0){ serialno=atoi(optarg); }else if(strcmp(long_options[option_index].name,"set-ctl-int")==0){ int len=strlen(optarg),target; char *spos,*tpos; spos=strchr(optarg,'='); if(len<3||spos==NULL||(spos-optarg)<1||(spos-optarg)>=len){ fprintf(stderr, "Invalid set-ctl-int: %s\n", optarg); fprintf(stderr, "Syntax is --set-ctl-int intX=intY or\n"); fprintf(stderr, "Syntax is --set-ctl-int intS:intX=intY\n"); return 0;//exit(1); } tpos=strchr(optarg,':'); if(tpos==NULL){ target=-1; tpos=optarg-1; }else target=atoi(optarg); if((atoi(tpos+1)&1)!=0){ fprintf(stderr, "Invalid set-ctl-int: %s\n", optarg); fprintf(stderr, "libopus set CTL values are even.\n"); return 0;//exit(1); } if(opt_ctls==0)opt_ctls_ctlval=malloc(sizeof(int)*3); else opt_ctls_ctlval=realloc(opt_ctls_ctlval,sizeof(int)*(opt_ctls+1)*3); opt_ctls_ctlval[opt_ctls*3]=target; opt_ctls_ctlval[opt_ctls*3+1]=atoi(tpos+1); opt_ctls_ctlval[opt_ctls*3+2]=atoi(spos+1); opt_ctls++; }else if(strcmp(long_options[option_index].name,"save-range")==0){ frange=fopen_utf8(optarg,"w"); save_cmd=0; if(frange==NULL){ perror(optarg); fprintf(stderr,"Could not open save-range file: %s\n",optarg); fprintf(stderr,"Must provide a writable file name.\n"); return 0;//exit(1); } range_file=optarg; }else if(strcmp(long_options[option_index].name,"comment")==0){ save_cmd=0; if(!strchr(optarg,'=')){ fprintf(stderr, "Invalid comment: %s\n", optarg); fprintf(stderr, "Comments must be of the form name=value\n"); return 0;//exit(1); } comment_add(&inopt.comments, &inopt.comments_length, NULL, optarg); }else if(strcmp(long_options[option_index].name,"artist")==0){ save_cmd=0; comment_add(&inopt.comments, &inopt.comments_length, "artist", optarg); } else if(strcmp(long_options[option_index].name,"title")==0){ save_cmd=0; comment_add(&inopt.comments, &inopt.comments_length, "title", optarg); } else if(strcmp(long_options[option_index].name,"album")==0){ save_cmd=0; comment_add(&inopt.comments, &inopt.comments_length, "album", optarg); } else if(strcmp(long_options[option_index].name,"date")==0){ save_cmd=0; comment_add(&inopt.comments, &inopt.comments_length, "date", optarg); } else if(strcmp(long_options[option_index].name,"genre")==0){ save_cmd=0; comment_add(&inopt.comments, &inopt.comments_length, "genre", optarg); } else if(strcmp(long_options[option_index].name,"picture")==0){ const char *error_message; char *picture_data; save_cmd=0; picture_data=parse_picture_specification(optarg,&error_message, &seen_file_icons); if(picture_data==NULL){ fprintf(stderr,"Error parsing picture option: %s\n",error_message); return 0;//exit(1); } comment_add(&inopt.comments,&inopt.comments_length, "METADATA_BLOCK_PICTURE",picture_data); free(picture_data); } else if(strcmp(long_options[option_index].name,"padding")==0){ comment_padding=atoi(optarg); } else if(strcmp(long_options[option_index].name,"discard-comments")==0){ inopt.copy_comments=0; inopt.copy_pictures=0; } else if(strcmp(long_options[option_index].name,"discard-pictures")==0){ inopt.copy_pictures=0; } /*Commands whos arguments would leak file paths or just end up as metadata should have save_cmd=0; to prevent them from being saved in the command-line tag.*/ break; case 'h': usage(); return 0;//exit(0); break; case 'V': opustoolsversion(opus_version); return 0;//exit(0); break; case '?': usage(); return 0;//exit(1); break; } if(save_cmd && cline_size<(int)sizeof(ENCODER_string)){ ret=snprintf(&ENCODER_string[cline_size], sizeof(ENCODER_string)-cline_size, "%s--%s",cline_size==0?"":" ",long_options[option_index].name); if(ret<0||ret>=((int)sizeof(ENCODER_string)-cline_size)){ cline_size=sizeof(ENCODER_string); } else { cline_size+=ret; if(optarg){ ret=snprintf(&ENCODER_string[cline_size], sizeof(ENCODER_string)-cline_size, " %s",optarg); if(ret<0||ret>=((int)sizeof(ENCODER_string)-cline_size)){ cline_size=sizeof(ENCODER_string); } else { cline_size+=ret; } } } } } if(argc_utf8-optind!=2){ usage(); return 0;//exit(1); } inFile=argv_utf8[optind]; outFile=argv_utf8[optind+1]; if(cline_size>0)comment_add(&inopt.comments, &inopt.comments_length, "ENCODER_OPTIONS", ENCODER_string); 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_utf8(inFile, "rb"); if(!fin){ perror(inFile); return 0;//exit(1); } } if(inopt.rawmode){ in_format = &raw_format; in_format->open_func(fin, &inopt, NULL, 0); }else in_format=open_audio_file(fin,&inopt); if(!in_format){ fprintf(stderr,"Error parsing input file: %s\n",inFile); return 0;//exit(1); } if(downmix==0&&inopt.channels>2&&bitrate>0&&bitrate<(16000*inopt.channels)){ if(!quiet)fprintf(stderr,"Notice: Surround bitrate less than 16kbit/sec/channel, downmixing.\n"); downmix=inopt.channels>8?1:2; } if(downmix>0&&downmix<inopt.channels)downmix=setup_downmix(&inopt,downmix); else downmix=0; rate=inopt.rate; chan=inopt.channels; inopt.skip=0; /*In order to code the complete length we'll need to do a little padding*/ setup_padder(&inopt,&original_samples); if(rate>24000)coding_rate=48000; else if(rate>16000)coding_rate=24000; else if(rate>12000)coding_rate=16000; else if(rate>8000)coding_rate=12000; else coding_rate=8000; frame_size=frame_size/(48000/coding_rate); /*Scale the resampler complexity, but only for 48000 output because the near-cutoff behavior matters a lot more at lower rates.*/ //if(rate!=coding_rate)setup_resample(&inopt,coding_rate==48000?(complexity+1)/2:5,coding_rate); if(rate!=coding_rate&&complexity!=10&&!quiet){ fprintf(stderr,"Notice: Using resampling with complexity<10.\n"); fprintf(stderr,"Opusenc is fastest with 48, 24, 16, 12, or 8kHz input.\n\n"); } /*OggOpus headers*/ /*FIXME: broke forcemono*/ header.channels=chan; header.channel_mapping=header.channels>8?255:chan>2; header.input_sample_rate=rate; header.gain=inopt.gain; /*Initialize OPUS encoder*/ /*Framesizes <10ms can only use the MDCT modes, so we switch on RESTRICTED_LOWDELAY to save the extra 2.5ms of codec lookahead when we'll be using only small frames.*/ st=opus_multistream_surround_encoder_create(coding_rate, chan, header.channel_mapping, &header.nb_streams, &header.nb_coupled, header.stream_map, frame_size<480/(48000/coding_rate)?OPUS_APPLICATION_RESTRICTED_LOWDELAY:OPUS_APPLICATION_AUDIO, &ret); if(ret!=OPUS_OK){ fprintf(stderr, "Error cannot create encoder: %s\n", opus_strerror(ret)); return 0;//exit(1); } min_bytes=max_frame_bytes=(1275*3+7)*header.nb_streams; packet=malloc(sizeof(unsigned char)*max_frame_bytes); if(packet==NULL){ fprintf(stderr,"Error allocating packet buffer.\n"); return 0;//exit(1); } if(bitrate<0){ /*Lower default rate for sampling rates [8000-44100) by a factor of (rate+16k)/(64k)*/ bitrate=((64000*header.nb_streams+32000*header.nb_coupled)* (IMIN(48,IMAX(8,((rate<44100?rate:48000)+1000)/1000))+16)+32)>>6; }
int main(int argc, char **argv) { char mp3buffer[LAME_MAXMP3BUFFER]; short int Buffer[2][1152]; int iread,imp3; lame_global_flags gf; FILE *outf; #ifdef __riscos__ int i; #endif lame_init(&gf); /* initialize libmp3lame */ if(argc==1) lame_usage(&gf,argv[0]); /* no command-line args, print usage, exit */ /* parse the command line arguments, setting various flags in the * struct 'gf'. If you want to parse your own arguments, * or call libmp3lame from a program which uses a GUI to set arguments, * skip this call and set the values of interest in the gf struct. * (see lame.h for documentation about these parameters) */ lame_parse_args(&gf,argc, argv); if (!gf.gtkflag) { /* open the MP3 output file */ if (!strcmp(gf.outPath, "-")) { #ifdef __EMX__ _fsetmode(stdout,"b"); #elif (defined __BORLANDC__) setmode(_fileno(stdout), O_BINARY); #elif (defined __CYGWIN__) setmode(fileno(stdout), _O_BINARY); #elif (defined _WIN32) _setmode(_fileno(stdout), _O_BINARY); #endif outf = stdout; } else { if ((outf = fopen(gf.outPath, "wb")) == NULL) { fprintf(stderr,"Could not create \"%s\".\n", gf.outPath); exit(1); } } #ifdef __riscos__ /* Assign correct file type */ for (i = 0; gf.outPath[i]; i++) if (gf.outPath[i] == '.') gf.outPath[i] = '/'; SetFiletype(gf.outPath, 0x1ad); #endif } /* open the wav/aiff/raw pcm or mp3 input file. This call will * open the file with name gf.inFile, try to parse the headers and * set gf.samplerate, gf.num_channels, gf.num_samples. * if you want to do your own file input, skip this call and set * these values yourself. */ lame_init_infile(&gf); /* Now that all the options are set, lame needs to analyze them and * set some more options */ lame_init_params(&gf); lame_print_config(&gf); /* print usefull information about options being used */ #ifdef HAVEGTK if (gf.gtkflag) gtk_init (&argc, &argv); if (gf.gtkflag) gtkcontrol(&gf); else #endif { /* encode until we hit eof */ do { /* read in 'iread' samples */ iread=lame_readframe(&gf,Buffer); /* encode */ imp3=lame_encode_buffer(&gf,Buffer[0],Buffer[1],iread, mp3buffer,(int)sizeof(mp3buffer)); /* was our output buffer big enough? */ if (imp3==-1) { fprintf(stderr,"mp3 buffer is not big enough... \n"); exit(1); } if (fwrite(mp3buffer,1,imp3,outf) != imp3) { fprintf(stderr,"Error writing mp3 output"); exit(1); } } while (iread); } imp3=lame_encode_finish(&gf,mp3buffer,(int)sizeof(mp3buffer)); /* may return one more mp3 frame */ fwrite(mp3buffer,1,imp3,outf); fclose(outf); lame_close_infile(&gf); /* close the input file */ lame_mp3_tags(&gf); /* add id3 or VBR tags to mp3 file */ 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 main(int argc, char **argv) { char **dirname = NULL; int i,j=0,k,n,optf,p,q,dtotal,ftotal,colored = FALSE; struct stat st; char sizebuf[64], *stmp; off_t size = 0; mode_t mt; bool needfulltree; q = p = dtotal = ftotal = 0; aflag = dflag = fflag = lflag = pflag = sflag = Fflag = uflag = gflag = FALSE; Dflag = qflag = Nflag = Qflag = Rflag = hflag = Hflag = siflag = cflag = FALSE; noindent = force_color = nocolor = xdev = noreport = nolinks = reverse = FALSE; ignorecase = matchdirs = dirsfirst = inodeflag = devflag = Xflag = Jflag = FALSE; duflag = pruneflag = FALSE; flimit = 0; dirs = xmalloc(sizeof(int) * (maxdirs=4096)); memset(dirs, 0, sizeof(int) * maxdirs); dirs[0] = 0; Level = -1; setlocale(LC_CTYPE, ""); setlocale(LC_COLLATE, ""); charset = getcharset(); if (charset == NULL) { charset = "UTF-8"; } /* Until I get rid of this hack, make it linux/cygwin/HP nonstop only: */ #if defined (LINUX) || defined (CYGWIN) || defined (__TANDEM) mb_cur_max = (int)MB_CUR_MAX; #else mb_cur_max = 1; #endif memset(utable,0,sizeof(utable)); memset(gtable,0,sizeof(gtable)); memset(itable,0,sizeof(itable)); optf = TRUE; for(n=i=1;i<argc;i=n) { n++; if (optf && argv[i][0] == '-' && argv[i][1]) { for(j=1;argv[i][j];j++) { switch(argv[i][j]) { case 'N': Nflag = TRUE; break; case 'q': qflag = TRUE; break; case 'Q': Qflag = TRUE; break; case 'd': dflag = TRUE; break; case 'l': lflag = TRUE; break; case 's': sflag = TRUE; break; case 'h': hflag = TRUE; sflag = TRUE; /* Assume they also want -s */ break; case 'u': uflag = TRUE; break; case 'g': gflag = TRUE; break; case 'f': fflag = TRUE; break; case 'F': Fflag = TRUE; break; case 'a': aflag = TRUE; break; case 'p': pflag = TRUE; break; case 'i': noindent = TRUE; _nl = ""; break; case 'C': force_color = TRUE; break; case 'n': nocolor = TRUE; break; case 'x': xdev = TRUE; break; case 'P': if (argv[n] == NULL) { fprintf(stderr,"tree: missing argument to -P option.\n"); exit(1); } pattern = argv[n++]; break; case 'I': if (argv[n] == NULL) { fprintf(stderr,"tree: missing argument to -I option.\n"); exit(1); } ipattern = argv[n++]; break; case 'A': ansilines = TRUE; break; case 'S': charset = "IBM437"; break; case 'D': Dflag = TRUE; break; case 't': cmpfunc = mtimesort; break; case 'c': cmpfunc = ctimesort; cflag = TRUE; break; case 'r': reverse = TRUE; break; case 'v': cmpfunc = versort; break; case 'U': cmpfunc = NULL; break; case 'X': Hflag = FALSE; Xflag = TRUE; break; case 'J': Jflag = TRUE; break; case 'H': Hflag = TRUE; Xflag = FALSE; if (argv[n] == NULL) { fprintf(stderr,"tree: missing argument to -H option.\n"); exit(1); } host = argv[n++]; sp = " "; break; case 'T': if (argv[n] == NULL) { fprintf(stderr,"tree: missing argument to -T option.\n"); exit(1); } title = argv[n++]; break; case 'R': Rflag = TRUE; break; case 'L': if ((sLevel = argv[n++]) == NULL) { fprintf(stderr,"tree: Missing argument to -L option.\n"); exit(1); } Level = strtoul(sLevel,NULL,0)-1; if (Level < 0) { fprintf(stderr,"tree: Invalid level, must be greater than 0.\n"); exit(1); } break; case 'o': if (argv[n] == NULL) { fprintf(stderr,"tree: missing argument to -o option.\n"); exit(1); } outfilename = argv[n++]; break; case '-': if (j == 1) { if (!strcmp("--", argv[i])) { optf = FALSE; break; } if (!strcmp("--help",argv[i])) { usage(2); exit(0); } if (!strcmp("--version",argv[i])) { char *v = version+12; printf("%.*s\n",(int)strlen(v)-1,v); exit(0); } if (!strcmp("--inodes",argv[i])) { j = strlen(argv[i])-1; inodeflag=TRUE; break; } if (!strcmp("--device",argv[i])) { j = strlen(argv[i])-1; devflag=TRUE; break; } if (!strcmp("--noreport",argv[i])) { j = strlen(argv[i])-1; noreport = TRUE; break; } if (!strcmp("--nolinks",argv[i])) { j = strlen(argv[i])-1; nolinks = TRUE; break; } if (!strcmp("--dirsfirst",argv[i])) { j = strlen(argv[i])-1; dirsfirst = TRUE; break; } if (!strncmp("--filelimit",argv[i],11)) { j = 11; if (*(argv[i]+11) == '=') { if (*(argv[i]+12)) { flimit=atoi(argv[i]+12); j = strlen(argv[i])-1; break; } } if (argv[n] != NULL) { flimit = atoi(argv[n++]); j = strlen(argv[i])-1; } else { fprintf(stderr,"tree: missing argument to --filelimit\n"); exit(1); } break; } if (!strncmp("--charset",argv[i],9)){ j = 9; if (*(argv[i]+j) == '=') { if (*(charset = (argv[i]+10))) { j = strlen(argv[i])-1; break; } } if (argv[n] != NULL) { charset = argv[n++]; j = strlen(argv[i])-1; } else { initlinedraw(1); exit(1); } break; } if (!strncmp("--si", argv[i], 4)) { j = strlen(argv[i])-1; sflag = TRUE; hflag = TRUE; siflag = TRUE; break; } if (!strncmp("--du",argv[i],4)) { j = strlen(argv[i])-1; sflag = TRUE; duflag = TRUE; break; } if (!strncmp("--prune",argv[i],7)) { j = strlen(argv[i])-1; pruneflag = TRUE; break; } if (!strncmp("--timefmt",argv[i],9)) { j = 9; if (*(argv[i]+j) == '=') { if (*(argv[i]+ (++j))) { timefmt=scopy(argv[i]+j); j = strlen(argv[i])-1; break; } } else if (argv[n] != NULL) { timefmt = scopy(argv[n]); n++; j = strlen(argv[i])-1; } else { fprintf(stderr,"tree: missing argument to --timefmt\n"); exit(1); } Dflag = TRUE; break; } if (!strncmp("--ignore-case",argv[i],13)) { j = strlen(argv[i])-1; ignorecase = TRUE; break; } if (!strncmp("--matchdirs",argv[i],11)) { j = strlen(argv[i])-1; matchdirs = TRUE; break; } if (!strncmp("--sort",argv[i],6)) { j = 6; if (*(argv[i]+j) == '=') { if (*(argv[i]+(++j))) { stmp = argv[i]+j; j = strlen(argv[i])-1; } else { fprintf(stderr,"tree: missing argument to --sort=\n"); exit(1); } } else if (argv[n] != NULL) { stmp = argv[n++]; } else { fprintf(stderr,"tree: missing argument to --sort\n"); exit(1); } cmpfunc = (void *)1; for(k=0;sorts[k].name;k++) { if (strcasecmp(sorts[k].name,stmp) == 0) { cmpfunc = sorts[k].cmpfunc; break; } } if (cmpfunc == (void *)1) { fprintf(stderr,"tree: sort type '%s' not valid, should be one of: ", stmp); for(k=0; sorts[k].name; k++) printf("%s%c", sorts[k].name, sorts[k+1].name? ',': '\n'); exit(1); } break; } } default: fprintf(stderr,"tree: Invalid argument -`%c'.\n",argv[i][j]); usage(1); exit(1); break; } } } else { if (!dirname) dirname = (char **)xmalloc(sizeof(char *) * (q=MINIT)); else if (p == (q-2)) dirname = (char **)xrealloc(dirname,sizeof(char *) * (q+=MINC)); dirname[p++] = scopy(argv[i]); } } if (p) dirname[p] = NULL; if (outfilename == NULL) { #ifdef __EMX__ _fsetmode(outfile=stdout,Hflag?"b":"t"); #else outfile = stdout; #endif } else { #ifdef __EMX__ outfile = fopen(outfilename,Hflag?"wb":"wt"); #else outfile = fopen(outfilename,"w"); #endif if (outfile == NULL) { fprintf(stderr,"tree: invalid filename '%s'\n",outfilename); exit(1); } } parse_dir_colors(); initlinedraw(0); needfulltree = duflag || pruneflag || matchdirs; /* Set our listdir function and sanity check options. */ if (Hflag) { listdir = needfulltree ? html_rlistdir : html_listdir; Xflag = FALSE; } else if (Xflag) { listdir = needfulltree ? xml_rlistdir : xml_listdir; colorize = FALSE; colored = FALSE; /* Do people want colored XML output? */ } else if (Jflag) { listdir = needfulltree ? json_rlistdir : json_listdir; colorize = FALSE; colored = FALSE; /* Do people want colored JSON output? */ } else { listdir = needfulltree ? unix_rlistdir : unix_listdir; } if (dflag) pruneflag = FALSE; /* You'll just get nothing otherwise. */ if (Rflag && (Level == -1)) Rflag = FALSE; if (Hflag) { emit_html_header(charset, title, version); fflag = FALSE; if (nolinks) { if (force_color) fprintf(outfile, "<b class=\"NORM\">%s</b>",host); else fprintf(outfile,"%s",host); } else { if (force_color) fprintf(outfile,"<a class=\"NORM\" href=\"%s\">%s</a>",host,host); else fprintf(outfile,"<a href=\"%s\">%s</a>",host,host); } curdir = gnu_getcwd(); } else if (Xflag) { fprintf(outfile,"<?xml version=\"1.0\""); if (charset) fprintf(outfile," encoding=\"%s\"",charset); fprintf(outfile,"?>%s<tree>%s",_nl,_nl); } else if (Jflag) fputc('[',outfile); if (dirname) { for(colored=i=0;dirname[i];i++,colored=0) { if (fflag) { do { j=strlen(dirname[i]); if (j > 1 && dirname[i][j-1] == '/') dirname[i][--j] = 0; } while (j > 1 && dirname[i][j-1] == '/'); } if ((n = lstat(dirname[i],&st)) >= 0) { saveino(st.st_ino, st.st_dev); if (colorize) colored = color(st.st_mode,dirname[i],n<0,FALSE); size += st.st_size; } if (Xflag || Jflag) { mt = st.st_mode & S_IFMT; for(j=0;ifmt[j];j++) if (ifmt[j] == mt) break; if (Xflag) fprintf(outfile,"%s<%s name=\"%s\">", noindent?"":" ", ftype[j], dirname[i]); else if (Jflag) { if (i) fprintf(outfile, ","); fprintf(outfile,"%s{\"type\":\"%s\",\"name\":\"%s\",\"contents\":[", noindent?"":"\n ", ftype[j], dirname[i]); } } else if (!Hflag) printit(dirname[i]); if (colored) fprintf(outfile,"%s",endcode); if (!Hflag) size += listdir(dirname[i],&dtotal,&ftotal,0,0); else { if (chdir(dirname[i])) { fprintf(outfile,"%s [error opening dir]\n",dirname[i]); exit(1); } else { size += listdir(".",&dtotal,&ftotal,0,0); chdir(curdir); } } if (Xflag) fprintf(outfile,"%s</%s>\n",noindent?"":" ", ftype[j]); if (Jflag) fprintf(outfile,"%s]}",noindent?"":" "); } } else { if ((n = lstat(".",&st)) >= 0) { saveino(st.st_ino, st.st_dev); if (colorize) colored = color(st.st_mode,".",n<0,FALSE); size = st.st_size; } if (Xflag) fprintf(outfile,"%s<directory name=\".\">",noindent?"":" "); else if (Jflag) fprintf(outfile, "{\"type\":\"directory\",\"name\": \".\",\"contents\":["); else if (!Hflag) fprintf(outfile,"."); if (colored) fprintf(outfile,"%s",endcode); size += listdir(".",&dtotal,&ftotal,0,0); if (Xflag) fprintf(outfile,"%s</directory>%s",noindent?"":" ", _nl); if (Jflag) fprintf(outfile,"%s]}",noindent?"":" "); } if (Hflag) fprintf(outfile,"\t<br><br>\n\t</p>\n\t<p>\n"); if (!noreport) { if (Xflag) { fprintf(outfile,"%s<report>%s",noindent?"":" ", _nl); if (duflag) fprintf(outfile,"%s<size>%lld</size>%s", noindent?"":" ", (long long int)size, _nl); fprintf(outfile,"%s<directories>%d</directories>%s", noindent?"":" ", dtotal, _nl); if (!dflag) fprintf(outfile,"%s<files>%d</files>%s", noindent?"":" ", ftotal, _nl); fprintf(outfile,"%s</report>%s",noindent?"":" ", _nl); } else if (Jflag) { fprintf(outfile, ",%s{\"type\":\"report\"",noindent?"":"\n "); if (duflag) fprintf(outfile,",\"size\":%lld", (long long int)size); fprintf(outfile,",\"directories\":%d", dtotal); if (!dflag) fprintf(outfile,",\"files\":%d", ftotal); fprintf(outfile, "}"); } else { if (duflag) { psize(sizebuf, size); fprintf(outfile,"\n%s%s used in ", sizebuf, hflag || siflag? "" : " bytes"); } else fputc('\n', outfile); if (dflag) fprintf(outfile,"%d director%s\n",dtotal,(dtotal==1? "y":"ies")); else fprintf(outfile,"%d director%s, %d file%s\n",dtotal,(dtotal==1? "y":"ies"),ftotal,(ftotal==1? "":"s")); } } if (Hflag) { fprintf(outfile,"\t<br><br>\n\t</p>\n"); fprintf(outfile,"\t<hr>\n"); fprintf(outfile,"\t<p class=\"VERSION\">\n"); fprintf(outfile,hversion,linedraw->copy, linedraw->copy, linedraw->copy, linedraw->copy); fprintf(outfile,"\t</p>\n"); fprintf(outfile,"</body>\n"); fprintf(outfile,"</html>\n"); } else if (Xflag) { fprintf(outfile,"</tree>\n"); } else if (Jflag) { fprintf(outfile, "%s]\n",_nl); } if (outfilename != NULL) fclose(outfile); return 0; }
FILE *out_file_open(char *outFile, int rate, int *channels) { FILE *fout=NULL; /*Open output file*/ if (strlen(outFile)==0) { #if defined HAVE_SYS_SOUNDCARD_H int audio_fd, format, stereo; audio_fd=open("/dev/dsp", O_WRONLY); if (audio_fd<0) { perror("Cannot open /dev/dsp"); exit(1); } format=AFMT_S16_NE; if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &format)==-1) { perror("SNDCTL_DSP_SETFMT"); close(audio_fd); exit(1); } stereo=0; if (*channels==2) stereo=1; if (ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo)==-1) { perror("SNDCTL_DSP_STEREO"); close(audio_fd); exit(1); } if (stereo!=0) { if (*channels==1) fprintf (stderr, "Cannot set mono mode, will decode in stereo\n"); *channels=2; } if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &rate)==-1) { perror("SNDCTL_DSP_SPEED"); close(audio_fd); exit(1); } fout = fdopen(audio_fd, "w"); #elif defined HAVE_SYS_AUDIOIO_H audio_info_t info; int audio_fd; audio_fd = open("/dev/audio", O_WRONLY); if (audio_fd<0) { perror("Cannot open /dev/audio"); exit(1); } AUDIO_INITINFO(&info); #ifdef AUMODE_PLAY /* NetBSD/OpenBSD */ info.mode = AUMODE_PLAY; #endif info.play.encoding = AUDIO_ENCODING_SLINEAR; info.play.precision = 16; info.play.sample_rate = rate; info.play.channels = *channels; if (ioctl(audio_fd, AUDIO_SETINFO, &info) < 0) { perror ("AUDIO_SETINFO"); exit(1); } fout = fdopen(audio_fd, "w"); #elif defined WIN32 || defined _WIN32 { unsigned int speex_channels = *channels; if (Set_WIN_Params (INVALID_FILEDESC, rate, SAMPLE_SIZE, speex_channels)) { fprintf (stderr, "Can't access %s\n", "WAVE OUT"); exit(1); } } #else fprintf (stderr, "No soundcard support\n"); exit(1); #endif } else { if (strcmp(outFile,"-")==0) { #if defined WIN32 || defined _WIN32 _setmode(_fileno(stdout), _O_BINARY); #elif defined OS2 _fsetmode(stdout,"b"); #endif fout=stdout; } else { fout = fopen(outFile, "wb"); if (!fout) { perror(outFile); exit(1); } if (strcmp(outFile+strlen(outFile)-4,".wav")==0 || strcmp(outFile+strlen(outFile)-4,".WAV")==0) write_wav_header(fout, rate, *channels, 0, 0); } } return fout; }
int main(int argc, char *argv[]) { FILE *in = stdin; FILE *out = stdout; FILE *sig = NULL; char output_name[MAXPATHLEN] = "(stdout)"; char input_name[MAXPATHLEN] = "(stdin)"; char signature_name[MAXPATHLEN]; int c; int i; int n = 100, nb; double a = 0.25; double g = 1.0; int s = 0; progname = argv[0]; #ifdef __EMX__ _fsetmode(in, "b"); _fsetmode(out, "b"); #endif while ((c = getopt(argc, argv, "a:g:h?n:o:s:S:")) != EOF) { switch (c) { case 'a': a = atof(optarg); if (a <= 0.0) { fprintf(stderr, "%s: alpha factor %f out of range\n", progname, a); exit(1); } break; case 'g': g = atof(optarg); if (g <= 0.0) { fprintf(stderr, "%s: gamma factor %f out of range\n", progname, a); exit(1); } break; case 'h': case '?': usage(); break; case 'n': n = atoi(optarg); if (n < 1 || n > 1000) { fprintf(stderr, "%s: watermark length %d out of range\n", progname, n); exit(1); } break; case 'o': if ((out = fopen(optarg, "w")) == NULL) { fprintf(stderr, "%s: unable to open output file %s\n", progname, optarg); exit(1); } strcpy(output_name, optarg); break; case 's': if ((sig = fopen(optarg, "r")) == NULL) { fprintf(stderr, "%s: unable to open signature file %s\n", progname, optarg); exit(1); } strcpy(signature_name, optarg); break; case 'S': s = atoi(optarg); break; } } argc -= optind; argv += optind; if (argc > 1) { usage(); exit(1); } if (argc == 1 && *argv[0] != '-') { if ((in = fopen(argv[0], "rb")) == NULL) { fprintf(stderr, "%s: unable to open input file %s\n", progname, argv[0]); exit(1); } else strcpy(input_name, argv[0]); } if (!s) s = time(NULL) * getpid(); srandom(s); if (sig) { char line[128]; fgets(line, sizeof(line), sig); if (strspn(line, "FR2SG") >= 5) { } else { fprintf(stderr, "%s: invalid signature file %s\n", progname, signature_name); exit(1); } fclose(sig); } if (n > 0) { nb = fread(signature, sizeof(char), i = NBITSTOBYTES(n), in); if (nb < i) { fprintf(stderr, "%s: failed to read all %d signature bits from %s\n", progname, n, input_name); exit(1); } } else { if (fscanf(in, "%128[^\n\r]", signature) == EOF) { fprintf(stderr, "%s: failed to read signature bits from %s\n", progname, input_name); exit(1); } nb = strlen(signature); n = NBYTESTOBITS(nb); fprintf(stderr, "%s: got %d signature bits\n", progname, n); } fprintf(out, "FR2SG\n"); fprintf(out, "%d\n", n); fprintf(out, "%f\n", a); fprintf(out, "%f\n", g); fprintf(out, "%d\n", s); fwrite(signature, sizeof(char), nb, out); fprintf(out, "\n"); fclose(out); exit(0); }