コード例 #1
0
ファイル: main.c プロジェクト: texane/aspect
int main(int ac, char** av)
{
  wav_handle_t iw;
  wav_handle_t ow;
  cmd_handle_t cmd;
  int err = -1;

  if (cmd_init(&cmd, ac - 1, av + 1))
  {
    PERROR();
    goto on_error_0;
  }

  if ((cmd.flags & CMD_FLAG_IPATH) == 0)
  {
    PERROR();
    goto on_error_0;
  }

  if ((cmd.flags & CMD_FLAG_OPATH) == 0)
  {
    PERROR();
    goto on_error_0;
  }

  if (wav_open(&iw, cmd.ipath))
  {
    PERROR();
    goto on_error_0;
  }

  if (wav_copy(&ow, &iw))
  {
    PERROR();
    goto on_error_1;
  }

  if (wav_write(&ow, cmd.opath))
  {
    PERROR();
    goto on_error_2;
  }

  err = 0;
 on_error_2:
  wav_close(&ow);
 on_error_1:
  wav_close(&iw);
 on_error_0:
  return err;
}
コード例 #2
0
ファイル: sound.c プロジェクト: broftkd/historic-mame
static void sound_exit(running_machine *machine)
{
	int sndnum;

	/* close any open WAV file */
	if (wavfile != NULL)
		wav_close(wavfile);

#ifdef MAME_DEBUG
{
	int spknum;

	/* log the maximum sample values for all speakers */
	for (spknum = 0; spknum < totalspeakers; spknum++)
		if (speaker[spknum].max_sample > 0)
		{
			speaker_info *spk = &speaker[spknum];
			mame_printf_debug("Speaker \"%s\" - max = %d (gain *= %f) - %d%% samples clipped\n", spk->speaker->tag, spk->max_sample, 32767.0 / (spk->max_sample ? spk->max_sample : 1), (int)((double)spk->clipped_samples * 100.0 / spk->total_samples));
		}
}
#endif /* MAME_DEBUG */

	/* stop all the sound chips */
	for (sndnum = 0; sndnum < MAX_SOUND; sndnum++)
		if (Machine->drv->sound[sndnum].type != SOUND_DUMMY)
			sndintrf_exit_sound(sndnum);

	/* reset variables */
	totalspeakers = 0;
	totalsnd = 0;
	memset(&speaker, 0, sizeof(speaker));
	memset(&sound, 0, sizeof(sound));
}
コード例 #3
0
static int yw_stop(TCModuleInstance *self)
{
    YWPrivateData *pd = NULL;
    int verr, aerr;

    TC_MODULE_SELF_CHECK(self, "stop");

    pd = self->userdata;

    if (pd->fd_vid != -1) {
        verr = close(pd->fd_vid);
        if (verr) {
            tc_log_error(MOD_NAME, "closing video file: %s",
                                   strerror(errno));
            return TC_ERROR;
        }
        y4m_fini_frame_info(&pd->frameinfo);
        y4m_fini_stream_info(&(pd->streaminfo));
   
        pd->fd_vid = -1;
    }

    if (pd->wav != NULL) {
        aerr = wav_close(pd->wav);
        if (aerr != 0) {
            tc_log_error(MOD_NAME, "closing audio file: %s",
                                   wav_strerror(wav_last_error(pd->wav)));
            return TC_ERROR;
        }
        pd->wav = NULL;
    }

    return TC_OK;
}
コード例 #4
0
ファイル: discrete.c プロジェクト: mp-lee/pinmame
void discrete_sh_stop (void)
{
	int loop=0;
	if(!init_ok) return;

#ifdef DISCRETE_WAVELOG
	wav_close(wav_file);
#endif

	for(loop=0;loop<node_count;loop++)
	{
	/* Destruct all of the objects */
		discrete_log("discrete_sh_stop() - Calling stop for %s",module_list[node_list[loop].module].name);
		if(module_list[node_list[loop].module].kill) (*module_list[node_list[loop].module].kill)(&node_list[loop]);
	}
	if(node_list) free(node_list);
	if(running_order) free(running_order);
	node_count=0;
	node_list=NULL;
	running_order=NULL;

#ifdef DISCRETE_DEBUGLOG
    if(disclogfile) fclose(disclogfile);
	disclogfile=NULL;
#endif
}
コード例 #5
0
/* errors not fatal (silently ignored) */
static int yw_close_audio(YWPrivateData *pd)
{
    if (pd->wav != NULL) {
        wav_close(pd->wav);
        pd->wav = NULL;
    }
    return(TC_IMPORT_OK);
}
コード例 #6
0
ファイル: testmess.c プロジェクト: Synapseware/coco
void osd_stop_audio_stream(void)
{
	if (wavptr)
	{
		wav_close(wavptr);
		wavptr = NULL;
	}
}
コード例 #7
0
ファイル: sound.c プロジェクト: DarrenBranford/MAME4iOS
static void sound_exit(running_machine &machine)
{
	sound_private *global = machine.sound_data;

	/* close any open WAV file */
	if (global->wavfile != NULL)
		wav_close(global->wavfile);
	global->wavfile = NULL;

	/* reset variables */
	global->totalsnd = 0;
}
コード例 #8
0
ファイル: encode_file.c プロジェクト: jdstroy/quiet
int encode_to_wav(FILE *payload, const char *out_fname,
                  const quiet_encoder_options *opt) {
    SNDFILE *wav = wav_open(out_fname, sample_rate);

    if (wav == NULL) {
        printf("failed to open wav file for writing\n");
        return 1;
    }

    quiet_encoder *e = quiet_encoder_create(opt, sample_rate);

    size_t block_len = 16384;
    uint8_t *readbuf = malloc(block_len * sizeof(uint8_t));
    size_t samplebuf_len = 16384;
    quiet_sample_t *samplebuf = malloc(samplebuf_len * sizeof(quiet_sample_t));
    quiet_encoder_clamp_frame_len(e, samplebuf_len);
    bool done = false;
    if (readbuf == NULL) {
        return 1;
    }
    if (samplebuf == NULL) {
        return 1;
    }

    while (!done) {
        size_t nread = fread(readbuf, sizeof(uint8_t), block_len, payload);
        if (nread == 0) {
            break;
        } else if (nread < block_len) {
            done = true;
        }

        size_t frame_len = quiet_encoder_get_frame_len(e);
        for (size_t i = 0; i < nread; i += frame_len) {
            frame_len = (frame_len > (nread - i)) ? (nread - i) : frame_len;
            quiet_encoder_send(e, readbuf + i, frame_len);
        }

        size_t written = samplebuf_len;
        while (written == samplebuf_len) {
            written = quiet_encoder_emit(e, samplebuf, samplebuf_len);
            wav_write(wav, samplebuf, written);
        }
    }

    quiet_encoder_destroy(e);
    free(readbuf);
    free(samplebuf);
    wav_close(wav);
    return 0;
}
コード例 #9
0
ファイル: audio.c プロジェクト: dreamerc/mpg123
static int builtin_close(struct audio_output_struct *ao)
{
	switch(param.outmode)
	{
		case DECODE_WAV:
		wav_close();
		break;
		case DECODE_AU:
		au_close();
		break;
		case DECODE_CDR:
		cdr_close();
		break;
	}
	return 0;
}
コード例 #10
0
ファイル: sound.c プロジェクト: cdenix/ps3-mame-0125
static void sound_exit(running_machine *machine)
{
	int sndnum;

	/* close any open WAV file */
	if (wavfile != NULL)
		wav_close(wavfile);

	/* stop all the sound chips */
	for (sndnum = 0; sndnum < MAX_SOUND; sndnum++)
		if (machine->config->sound[sndnum].type != SOUND_DUMMY)
			sndintrf_exit_sound(sndnum);

	/* reset variables */
	totalsnd = 0;
	memset(&sound, 0, sizeof(sound));
}
コード例 #11
0
ファイル: wav_stream.c プロジェクト: cshengqun/raop
int wav_open(auds_t *auds, char *fname)
{
	wav_t *wav=malloc(sizeof(wav_t));
	if(!wav) return -1;
	memset(wav,0,sizeof(wav_t));
	auds->stream=(void *)wav;
	wav->inf=fopen(fname,"r");
	if(!wav->inf) goto erexit;
	if(read_wave_header(wav, &auds->sample_rate, &auds->channels)==-1) goto erexit;
	auds->chunk_size=aud_clac_chunk_size(auds->sample_rate);
	wav->buffer=(__u8 *)malloc(MAX_SAMPLES_IN_CHUNK*4+16);
	if(!wav->buffer) goto erexit;
	return 0;
 erexit:
	wav_close(auds);
	return -1;
}
コード例 #12
0
ファイル: audiograph.c プロジェクト: nick-prater/audiograph
int main(int argc, char **argv)
{
    int width, height;
    double colour[3];

    struct wav_file *wav;
    float samples[CHUNK_SIZE];
    int sample_count;

    struct graph *gr;
    cairo_surface_t *surface;


    /* Validate and parse command-line arguments */
    if(parse_arguments(argc, argv, &width, &height, colour) != 0)
        return 1;

    /* Open input file */
    if( !(wav = wav_open(argv[1])))
    {
        fprintf(stderr, "Unable to open input audio file %s\n", argv[1]);
        return 1;
    }

    /* Buffer all samples from input file. */
    gr = graph_init();
    while((sample_count = wav_read_samples(wav, samples, CHUNK_SIZE)) > 0)
        graph_buffer_samples(gr, samples, sample_count);

    /* Close input file */
    wav_close(wav);

    /* Draw graph and output to PNG file using Cairo */
    surface = graph_draw(gr, width, height, colour);
    if(cairo_surface_write_to_png(surface, argv[2]) != CAIRO_STATUS_SUCCESS)
    {
        fprintf(stderr, "Error writing graph to PNG file\n");
        return 1;
    }

    graph_surface_destroy(surface);
    graph_destroy(gr);

    return 0;
}
コード例 #13
0
void osd_stop_audio_stream(void)
{
	if( wavptr != NULL )
	{
		wav_close( wavptr );
		wavptr = NULL;
	}

	// kill the buffers and dsound
	dsound_destroy_buffers();
	dsound_kill();

	// print out over/underflow stats
	if (buffer_overflows || buffer_underflows)
		verbose_printf("Sound: buffer overflows=%d underflows=%d\n", buffer_overflows, buffer_underflows);

#if LOG_SOUND
	if (sound_log)
		fprintf(sound_log, "Sound buffer: overflows=%d underflows=%d\n", buffer_overflows, buffer_underflows);
	fclose(sound_log);
#endif
}
コード例 #14
0
ファイル: wav_stream.c プロジェクト: chevil/raop2_play
int wav_open(auds_t *auds, char *fname)
{
        struct stat finfo;
	wav_t *wav=malloc(sizeof(wav_t));
	if(!wav) return -1;
	memset(wav,0,sizeof(wav_t));
	auds->stream=(void *)wav;
	wav->inf=fopen(fname,"r");
	if(!wav->inf) goto erexit;
        if ( csync!=0 )
        {
	   wav->inf2=fopen(fname,"r");
	   if(!wav->inf2) goto erexit;
        }
	if(read_wave_header(wav, &auds->sample_rate, &auds->channels)==-1) goto erexit;
	auds->chunk_size=aud_clac_chunk_size(auds->sample_rate);
	wav->buffer=(uint8_t *)malloc(MAX_SAMPLES_IN_CHUNK*4+16);
	if(!wav->buffer) goto erexit;

        if(stat(fname,&finfo)<0)
        {
          ERRMSG( "Couldn't get file size\n" );
          fduration=0;
        }
        else
        {
          fduration=(finfo.st_size-sizeof(wave_header_t))/(sizeof(short)*auds->channels*auds->sample_rate);
          flength=(finfo.st_size-sizeof(wave_header_t))/(sizeof(short)*auds->channels);
          DBGMSG( "duration in seconds : %d\n", fduration );
        }

        DBGMSG( "Start time is %ld\n", startinms );
        if ( startinms != -1 )
        {
           long nbbytes = sizeof(short)*auds->channels*auds->sample_rate;
           nbbytes *= startinms/1000;
           DBGMSG( "inf : Seeking to %ld bytes\n", nbbytes );

           if ( fseek( wav->inf, nbbytes, SEEK_CUR ) < 0 )
           {
              ERRMSG( "Couldn't seek specified start time : %s", strerror( errno ) );
              wav_close(auds);
              return -1;
           }

           if ( csync!=0 )
           {
              nbbytes = sizeof(short)*auds->channels*auds->sample_rate;
              int mcsync = (int)(csync*1000.0);
              nbbytes *= (startinms+mcsync)/1000;
              DBGMSG( "inf2 : seeking to %ld from current\n", nbbytes );

              if ( fseek( wav->inf2, nbbytes, SEEK_CUR ) < 0 )
              {
                 ERRMSG( "Couldn't seek specified start time : %s", strerror( errno ) );
                 wav_close(auds);
                 return -1;
              }
           }
        }
        else
        {
           if ( csync!=0 )
           {
              int nbbytes = sizeof(short)*auds->channels*auds->sample_rate;
              int mcsync = (int)(csync*1000.0);
              nbbytes *= mcsync/1000;
              DBGMSG( "inf2 : seeking to %d from current\n", nbbytes );
              if ( fseek( wav->inf2, nbbytes, SEEK_CUR ) < 0 )
              {
                 ERRMSG( "fseek ahead failed : reason : %s", strerror( errno ) );
                 goto erexit;
              }
           }
        }

	return 0;
 erexit:
	wav_close(auds);
	return -1;
}
コード例 #15
0
ファイル: tap2wav.c プロジェクト: bitfixer/bitfixer
int main(int argc, char **argv)
{
	struct tap tapfile;
	struct wav wavfile;
	FILE *infile;
	long pulse;
	long i;
	fixedpoint len, accum;
	long channels[2];
	int wave[2];
	int sample;
	
	getopts(argc, argv);
	if (invert) {
		wave[0] = LOW;
		wave[1] = HIGH;
	} else {
		wave[0] = HIGH;
		wave[1] = LOW;
	}
	
	if (optind == argc) {
		infile = stdin;
	} else if (optind == argc - 1) {
		if (!strcmp(argv[optind], "-")) {
			infile = stdin;
		} else {
			infile = fopen(argv[optind], "rb");
			if (!infile) {
				perror(argv[optind]);
				return 1;
			}
		}
	} else {
		fprintf(stderr, "%s: too many arguments\n", argv0);
		usage();
		return 1;
	}
	if (tap_read_header(&tapfile, infile)) {
		fprintf(stderr, "%s: error reading TAP file\n", argv0);
		return 1;
	}
	wavfile.SampleRate = samplerate;
	wavfile.BitsPerSample = 8;
	wavfile.NumChannels = 1;
	if (wav_write_header(&wavfile, stdout)) {
		fprintf(stderr, "%s: error writing WAV file\n", argv0);
		return 1;
	}
	filter_init(&lowpass_filter, lowpass_freq, wavfile.SampleRate);
#if 0
	/* put one initial sample so the first pulse is recognized */
	channels[0] = wave[1];
	wav_put_sample(&wavfile, channels);
	accum = TO_FIXED(1.5);
#else
	accum = TO_FIXED(2);
#endif
	while ((pulse = tap_get_pulse(&tapfile)) >= 0) {
		//fprintf(stderr, "pulse: %6ld (%04lx)\n", pulse, pulse);
		//if (pulse < 8*256)
			//++pulsehist[pulse/8];
		len = TO_FIXED(((double)pulse * samplerate / PAL_MHZ / speed / 1000000));

		if (len < TO_FIXED(2)) {
			fprintf(stderr, "%s: warning: pulse length (%ld) is less than 2 samples\n", argv0, pulse);
		}
#if 0
		accum = FIXED_F(len + accum);
#else
		len += accum;
		accum = FIXED_F(len);
#endif
#if 0
		fprintf(stderr, "%ld.%03ld 0.%03ld \n",
		        FIXED_I(len),
		        FIXED_F(len) * 1000 / FIXED_ONE,
		        FIXED_F(accum) * 1000 / FIXED_ONE);
#endif
		
		for (i = 0; i < FIXED_I(len) / 2 - 1; ++i) {
			channels[0] = filter_lowpass(&lowpass_filter, wave[0]) << 16;
			wav_put_sample(&wavfile, channels);
		}
		
		for (; i < FIXED_I(len) - 2; ++i) {
			channels[0] = filter_lowpass(&lowpass_filter, wave[1]) << 16;
			wav_put_sample(&wavfile, channels);
		}
#if 0
		channels[0] = FIXED_MUL(wave[1], accum) +
		              FIXED_MUL(wave[0], FIXED_ONE - accum);
		wav_put_sample(&wavfile, channels);
#else
		sample = FIXED_MUL(wave[1], accum);
		channels[0] = filter_lowpass(&lowpass_filter, sample) << 16;
		wav_put_sample(&wavfile, channels);
		sample -= wave[1];
		channels[0] = filter_lowpass(&lowpass_filter, sample) << 16;
		wav_put_sample(&wavfile, channels);
#endif
	}
	wav_close(&wavfile);
	return 0;
}
コード例 #16
0
ファイル: fft_compare.c プロジェクト: umgupta/fft_all_algo
int main(int argc,  char *argv[]){
	if(argc < 4){
        printf(USAGE);
        exit(1);
    }

    pcmfile_t   *wav_inp;
    
	wav_inp = wav_open_read(argv[1], 0);
    if(wav_inp == NULL){
        printf("wav_open_read failed\n");
        exit(1);
    }
    if(wav_inp->channels == 2){
        printf("Input file is stereo. NOT SUPPRTED\n");
        exit(1);
    }
	int         block_size 	= atoi(argv[3]);
	FILE        *fp_fft_out	= fopen(argv[2],"w");
// 	FILE		*fp_ifft_out= fopen(argv[4],"w");	
	short       *pcm 		= malloc(block_size*wav_inp->channels*sizeof(short));

#ifdef KISS_FFT
    void        		*fft_cfg	= 	kiss_fftr_alloc(block_size ,0,0,0 );
	kiss_fft_scalar*    fft_in		= 	(kiss_fft_scalar*)malloc(sizeof(kiss_fft_scalar)*(block_size));
	kiss_fft_cpx*      	fft_out		= 	(kiss_fft_cpx*)malloc(sizeof(kiss_fft_cpx)*(block_size));
#elif GST_FFT
	gint16* 			fft_in		= 	(gint16*)malloc(sizeof(gint16)*block_size);		
	GstFFTS16Complex*	fft_out		= 	(GstFFTS16Complex*)malloc(sizeof(GstFFTS16Complex*)*block_size);
	GstFFTS16*			fft_self	=	gst_fft_s16_new(block_size,FALSE);
#elif ALLGO_FFT
	int     *fft_in					=	(int*)malloc(sizeof(int)*block_size);
//	int     *fft_out				=	(int*)malloc(2*sizeof(int)*block_size);
//	short   *out_pcm				=	(short*)malloc(sizeof(short)*block_size);
#endif

    int 			i;
	int         	num_samples_read;
	long 			time=0;
	struct timeval 	start,end;

    while(1){
        num_samples_read = wav_read_int16(wav_inp, pcm, (block_size*wav_inp->channels), NULL);
		if(num_samples_read != block_size){
            printf("END of wav file reached\n");
            break;
        }
	
		for(i=0;i<block_size;i++){
#ifdef ALLGO_FFT
			fft_in[i] = (int)((pcm[i]));
	    //    fft_in[2*i+1] = 0;
#elif KISS_FFT
        	fft_in[i] =(kiss_fft_scalar)pcm[i];
#elif GST_FFT
			fft_in[i] =(gint16)pcm[i];		
#endif	
		}

		gettimeofday(&start,NULL);
#ifdef KISS_FFT
    	kiss_fftr(fft_cfg , fft_in, fft_out);
#elif GST_FFT
        gst_fft_s16_fft(fft_self,fft_in,fft_out);
#elif ALLGO_FFT
		FFT(fft_in, block_size);
#endif
		gettimeofday(&end,NULL);   

		time=time+(end.tv_usec+end.tv_sec*1000000-start.tv_usec-start.tv_sec*1000000);

#ifdef FIXED_POINT
#ifdef ALLGO_FFT
		for(i = 0; i < (block_size); i+=2){
        	fprintf(fp_fft_out, "%d\t", fft_in[i]);
        	fprintf(fp_fft_out, "%d\n", fft_in[i+1]);
        }
#else	
		for(i=0;i<(block_size/2);i++){
        	fprintf(fp_fft_out,"%d\t%d\n",(int)fft_out[i].r,(int)fft_out[i].i);
		}
#endif
#else
	for(i=0;i<(block_size/2);i++){
            fprintf(fp_fft_out,"%d\t%d\n",(int)((fft_out[i].r)/block_size),(int)((fft_out[i].i/block_size)));
	}
#endif
    }

   	printf("%ld time elapsed\n\n",time); 
	wav_close(wav_inp);
    fclose(fp_fft_out);
return 0;
}
コード例 #17
0
ファイル: main.c プロジェクト: 12307/PushRTMPStreamSync
int main(int argc, char *argv[])
{
    int frames, currentFrame;
    faacEncHandle hEncoder;
    pcmfile_t *infile = NULL;

    unsigned long samplesInput, maxBytesOutput, totalBytesWritten=0;

    faacEncConfigurationPtr myFormat;
    unsigned int mpegVersion = MPEG2;
    unsigned int objectType = LOW;
    unsigned int useMidSide = 1;
    static unsigned int useTns = DEFAULT_TNS;
    enum container_format container = NO_CONTAINER;
    int optimizeFlag = 0;
    enum stream_format stream = ADTS_STREAM;
    int cutOff = -1;
    int bitRate = 0;
    unsigned long quantqual = 0;
    int chanC = 3;
    int chanLF = 4;

    char *audioFileName = NULL;
    char *aacFileName = NULL;
    char *aacFileExt = NULL;
    int aacFileNameGiven = 0;

    float *pcmbuf;
    int *chanmap = NULL;

    unsigned char *bitbuf;
    int samplesRead = 0;
    const char *dieMessage = NULL;

    int rawChans = 0; // disabled by default
    int rawBits = 16;
    int rawRate = 44100;
    int rawEndian = 1;

    int shortctl = SHORTCTL_NORMAL;

    FILE *outfile = NULL;

#ifdef HAVE_LIBMP4V2
    MP4FileHandle MP4hFile = MP4_INVALID_FILE_HANDLE;
    MP4TrackId MP4track = 0;
    unsigned int ntracks = 0, trackno = 0;
    unsigned int ndiscs = 0, discno = 0;
    u_int8_t compilation = 0;
    const char *artist = NULL, *title = NULL, *album = NULL, *year = NULL,
      *genre = NULL, *comment = NULL, *writer = NULL;
    u_int8_t *art = NULL;
    u_int64_t artSize = 0;
    u_int64_t total_samples = 0;
    u_int64_t encoded_samples = 0;
    unsigned int delay_samples;
    unsigned int frameSize;
#endif
    char *faac_id_string;
    char *faac_copyright_string;

#ifndef _WIN32
    // install signal handler
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
#endif

    // get faac version
    if (faacEncGetVersion(&faac_id_string, &faac_copyright_string) == FAAC_CFG_VERSION)
    {
        fprintf(stderr, "Freeware Advanced Audio Coder\nFAAC %s\n\n", faac_id_string);
    }
    else
    {
        fprintf(stderr, __FILE__ "(%d): wrong libfaac version\n", __LINE__);
        return 1;
    }

    /* begin process command line */
    progName = argv[0];
    while (1) {
        static struct option long_options[] = {
            { "help", 0, 0, 'h'},
            { "long-help", 0, 0, 'H'},
            { "raw", 0, 0, 'r'},
            { "no-midside", 0, 0, NO_MIDSIDE_FLAG},
            { "cutoff", 1, 0, 'c'},
            { "quality", 1, 0, 'q'},
            { "pcmraw", 0, 0, 'P'},
            { "pcmsamplerate", 1, 0, 'R'},
            { "pcmsamplebits", 1, 0, 'B'},
            { "pcmchannels", 1, 0, 'C'},
            { "shortctl", 1, 0, SHORTCTL_FLAG},
            { "tns", 0, 0, TNS_FLAG},
            { "no-tns", 0, 0, NO_TNS_FLAG},
            { "mpeg-version", 1, 0, MPEGVERS_FLAG},
            { "obj-type", 1, 0, OBJTYPE_FLAG},
            { "license", 0, 0, 'L'},
#ifdef HAVE_LIBMP4V2
            { "createmp4", 0, 0, 'w'},
            { "optimize", 0, 0, 's'},
            { "artist", 1, 0, ARTIST_FLAG},
            { "title", 1, 0, TITLE_FLAG},
            { "album", 1, 0, ALBUM_FLAG},
            { "track", 1, 0, TRACK_FLAG},
            { "disc", 1, 0, DISC_FLAG},
            { "genre", 1, 0, GENRE_FLAG},
            { "year", 1, 0, YEAR_FLAG},
            { "cover-art", 1, 0, COVER_ART_FLAG},
            { "comment", 1, 0, COMMENT_FLAG},
        { "writer", 1, 0, WRITER_FLAG},
        { "compilation", 0, 0, COMPILATION_FLAG},
#endif
        { "pcmswapbytes", 0, 0, 'X'},
            { 0, 0, 0, 0}
        };
        int c = -1;
        int option_index = 0;

        c = getopt_long(argc, argv, "Hhb:m:o:rnc:q:PR:B:C:I:X"
#ifdef HAVE_LIBMP4V2
                        "ws"
#endif
            ,long_options, &option_index);

        if (c == -1)
            break;

        if (!c)
        {
          dieMessage = usage;
          break;
        }

        switch (c) {
    case 'o':
        {
            int l = strlen(optarg);
        aacFileName = malloc(l+1);
        memcpy(aacFileName, optarg, l);
        aacFileName[l] = '\0';
        aacFileNameGiven = 1;
        }
        break;
        case 'r': {
            stream = RAW_STREAM;
            break;
        }
        case NO_MIDSIDE_FLAG: {
            useMidSide = 0;
            break;
        }
        case 'c': {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0) {
                cutOff = i;
            }
            break;
        }
        case 'b': {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
            {
                bitRate = 1000 * i;
            }
            break;
        }
        case 'q':
        {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
            {
                if (i > 0 && i < 1000)
                    quantqual = i;
            }
            break;
        }
        case 'I':
            sscanf(optarg, "%d,%d", &chanC, &chanLF);
            break;
        case 'P':
            rawChans = 2; // enable raw input
            break;
        case 'R':
        {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
            {
                rawRate = i;
                rawChans = (rawChans > 0) ? rawChans : 2;
            }
            break;
        }
        case 'B':
        {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
            {
                if (i > 32)
                    i = 32;
                if (i < 8)
                    i = 8;
                rawBits = i;
                rawChans = (rawChans > 0) ? rawChans : 2;
            }
            break;
        }
        case 'C':
        {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
                rawChans = i;
            break;
        }
#ifdef HAVE_LIBMP4V2
        case 'w':
        container = MP4_CONTAINER;
            break;
        case 's':
        optimizeFlag = 1;
            break;
    case ARTIST_FLAG:
        artist = optarg;
        break;
    case WRITER_FLAG:
        writer = optarg;
        break;
    case TITLE_FLAG:
        title = optarg;
        break;
    case ALBUM_FLAG:
        album = optarg;
        break;
    case TRACK_FLAG:
        sscanf(optarg, "%d/%d", &trackno, &ntracks);
        break;
    case DISC_FLAG:
        sscanf(optarg, "%d/%d", &discno, &ndiscs);
        break;
    case COMPILATION_FLAG:
        compilation = 0x1;
        break;
    case GENRE_FLAG:
        genre = optarg;
        break;
    case YEAR_FLAG:
        year = optarg;
        break;
    case COMMENT_FLAG:
        comment = optarg;
        break;
    case COVER_ART_FLAG: {
        FILE *artFile = fopen(optarg, "rb");

        if(artFile) {
            u_int64_t r;

            fseek(artFile, 0, SEEK_END);
        artSize = ftell(artFile);

        art = malloc(artSize);

            fseek(artFile, 0, SEEK_SET);
        clearerr(artFile);

        r = fread(art, artSize, 1, artFile);

        if (r != 1) {
            dieMessage = "Error reading cover art file!\n";
            free(art);
            art = NULL;
        } else if (artSize < 12 || !check_image_header(art)) {
            /* the above expression checks the image signature */
            dieMessage = "Unsupported cover image file format!\n";
            free(art);
            art = NULL;
        }

        fclose(artFile);
        } else {
            dieMessage = "Error opening cover art file!\n";
        }

        break;
    }
#endif
        case SHORTCTL_FLAG:
            shortctl = atoi(optarg);
            break;
        case TNS_FLAG:
            useTns = 1;
            break;
        case NO_TNS_FLAG:
            useTns = 0;
            break;
    case MPEGVERS_FLAG:
            mpegVersion = atoi(optarg);
            switch(mpegVersion)
            {
            case 2:
                mpegVersion = MPEG2;
                break;
            case 4:
                mpegVersion = MPEG4;
                break;
            default:
            dieMessage = "Unrecognised MPEG version!\n";
            }
            break;
#if 0
    case OBJTYPE_FLAG:
        if (!strcasecmp(optarg, "LC"))
                objectType = LOW;
        else if (!strcasecmp(optarg, "Main"))
            objectType = MAIN;
        else if (!strcasecmp(optarg, "LTP")) {
            mpegVersion = MPEG4;
        objectType = LTP;
        } else
            dieMessage = "Unrecognised object type!\n";
        break;
#endif
        case 'L':
        fprintf(stderr, faac_copyright_string);
        dieMessage = license;
        break;
    case 'X':
      rawEndian = 0;
      break;
    case 'H':
      dieMessage = long_help;
      break;
    case 'h':
          dieMessage = short_help;
      break;
    case '?':
        default:
      dieMessage = usage;
          break;
        }
    }

    /* check that we have at least one non-option arguments */
    if (!dieMessage && (argc - optind) > 1 && aacFileNameGiven)
        dieMessage = "Cannot encode several input files to one output file.\n";

    if (argc - optind < 1 || dieMessage)
    {
        fprintf(stderr, dieMessage ? dieMessage : usage,
           progName, progName, progName, progName);
        return 1;
    }

    while (argc - optind > 0) {

    /* get the input file name */
    audioFileName = argv[optind++];

    /* generate the output file name, if necessary */
    if (!aacFileNameGiven) {
        char *t = strrchr(audioFileName, '.');
    int l = t ? strlen(audioFileName) - strlen(t) : strlen(audioFileName);

#ifdef HAVE_LIBMP4V2
    aacFileExt = container == MP4_CONTAINER ? ".m4a" : ".aac";
#else
    aacFileExt = ".aac";
#endif

    aacFileName = malloc(l+1+4);
    memcpy(aacFileName, audioFileName, l);
    memcpy(aacFileName + l, aacFileExt, 4);
    aacFileName[l+4] = '\0';
    } else {
        aacFileExt = strrchr(aacFileName, '.');

        if (aacFileExt && (!strcmp(".m4a", aacFileExt) || !strcmp(".m4b", aacFileExt) || !strcmp(".mp4", aacFileExt)))
#ifndef HAVE_LIBMP4V2
        fprintf(stderr, "WARNING: MP4 support unavailable!\n");
#else
        container = MP4_CONTAINER;
#endif
    }

    /* open the audio input file */
    if (rawChans > 0) // use raw input
    {
        infile = wav_open_read(audioFileName, 1);
    if (infile)
    {
        infile->bigendian = rawEndian;
        infile->channels = rawChans;
        infile->samplebytes = rawBits / 8;
        infile->samplerate = rawRate;
        infile->samples /= (infile->channels * infile->samplebytes);
    }
    }
    else // header input
        infile = wav_open_read(audioFileName, 0);

    if (infile == NULL)
    {
        fprintf(stderr, "Couldn't open input file %s\n", audioFileName);
    return 1;
    }


    /* open the encoder library */
    hEncoder = faacEncOpen(infile->samplerate, infile->channels,
        &samplesInput, &maxBytesOutput);

#ifdef HAVE_LIBMP4V2
    if (container != MP4_CONTAINER && (ntracks || trackno || artist ||
                       title ||  album || year || art ||
                       genre || comment || discno || ndiscs ||
                       writer || compilation))
    {
        fprintf(stderr, "Metadata requires MP4 output!\n");
    return 1;
    }

    if (container == MP4_CONTAINER)
    {
        mpegVersion = MPEG4;
    stream = RAW_STREAM;
    }

    frameSize = samplesInput/infile->channels;
    delay_samples = frameSize; // encoder delay 1024 samples
#endif
    pcmbuf = (float *)malloc(samplesInput*sizeof(float));
    bitbuf = (unsigned char*)malloc(maxBytesOutput*sizeof(unsigned char));
    chanmap = mkChanMap(infile->channels, chanC, chanLF);
    if (chanmap)
    {
        fprintf(stderr, "Remapping input channels: Center=%d, LFE=%d\n",
            chanC, chanLF);
    }

    if (cutOff <= 0)
    {
        if (cutOff < 0) // default
            cutOff = 0;
        else // disabled
            cutOff = infile->samplerate / 2;
    }
    if (cutOff > (infile->samplerate / 2))
        cutOff = infile->samplerate / 2;

    /* put the options in the configuration struct */
    myFormat = faacEncGetCurrentConfiguration(hEncoder);
    myFormat->aacObjectType = objectType;
    myFormat->mpegVersion = mpegVersion;
    myFormat->useTns = useTns;
    switch (shortctl)
    {
    case SHORTCTL_NOSHORT:
      fprintf(stderr, "disabling short blocks\n");
      myFormat->shortctl = shortctl;
      break;
    case SHORTCTL_NOLONG:
      fprintf(stderr, "disabling long blocks\n");
      myFormat->shortctl = shortctl;
      break;
    }
    if (infile->channels >= 6)
        myFormat->useLfe = 1;
    myFormat->allowMidside = useMidSide;
    if (bitRate)
        myFormat->bitRate = bitRate / infile->channels;
    myFormat->bandWidth = cutOff;
    if (quantqual > 0)
        myFormat->quantqual = quantqual;
    myFormat->outputFormat = stream;
    myFormat->inputFormat = FAAC_INPUT_FLOAT;
    if (!faacEncSetConfiguration(hEncoder, myFormat)) {
        fprintf(stderr, "Unsupported output format!\n");
#ifdef HAVE_LIBMP4V2
        if (container == MP4_CONTAINER) MP4Close(MP4hFile);
#endif
        return 1;
    }

#ifdef HAVE_LIBMP4V2
    /* initialize MP4 creation */
    if (container == MP4_CONTAINER) {
        unsigned char *ASC = 0;
        unsigned long ASCLength = 0;
    char *version_string;

#ifdef MP4_CREATE_EXTENSIBLE_FORMAT
    /* hack to compile against libmp4v2 >= 1.0RC3
     * why is there no version identifier in mp4.h? */
        MP4hFile = MP4Create(aacFileName, MP4_DETAILS_ERROR, 0);
#else
    MP4hFile = MP4Create(aacFileName, MP4_DETAILS_ERROR, 0, 0);
#endif
        if (!MP4_IS_VALID_FILE_HANDLE(MP4hFile)) {
            fprintf(stderr, "Couldn't create output file %s\n", aacFileName);
            return 1;
        }

        MP4SetTimeScale(MP4hFile, 90000);
        MP4track = MP4AddAudioTrack(MP4hFile, infile->samplerate, MP4_INVALID_DURATION, MP4_MPEG4_AUDIO_TYPE);
        MP4SetAudioProfileLevel(MP4hFile, 0x0F);
        faacEncGetDecoderSpecificInfo(hEncoder, &ASC, &ASCLength);
        MP4SetTrackESConfiguration(MP4hFile, MP4track, ASC, ASCLength);
    free(ASC);

    /* set metadata */
    version_string = malloc(strlen(faac_id_string) + 6);
    strcpy(version_string, "FAAC ");
    strcpy(version_string + 5, faac_id_string);
    MP4SetMetadataTool(MP4hFile, version_string);
    free(version_string);

    if (artist) MP4SetMetadataArtist(MP4hFile, artist);
    if (writer) MP4SetMetadataWriter(MP4hFile, writer);
    if (title) MP4SetMetadataName(MP4hFile, title);
    if (album) MP4SetMetadataAlbum(MP4hFile, album);
    if (trackno > 0) MP4SetMetadataTrack(MP4hFile, trackno, ntracks);
    if (discno > 0) MP4SetMetadataDisk(MP4hFile, discno, ndiscs);
    if (compilation) MP4SetMetadataCompilation(MP4hFile, compilation);
    if (year) MP4SetMetadataYear(MP4hFile, year);
    if (genre) MP4SetMetadataGenre(MP4hFile, genre);
    if (comment) MP4SetMetadataComment(MP4hFile, comment);
        if (artSize) {
        MP4SetMetadataCoverArt(MP4hFile, art, artSize);
        free(art);
    }
    }
    else
    {
#endif
        /* open the aac output file */
        if (!strcmp(aacFileName, "-"))
        {
            outfile = stdout;
        }
        else
        {
            outfile = fopen(aacFileName, "wb");
        }
        if (!outfile)
        {
            fprintf(stderr, "Couldn't create output file %s\n", aacFileName);
            return 1;
        }
#ifdef HAVE_LIBMP4V2
    }
#endif

    cutOff = myFormat->bandWidth;
    quantqual = myFormat->quantqual;
    bitRate = myFormat->bitRate;
    if (bitRate)
      fprintf(stderr, "Average bitrate: %d kbps\n",
          (bitRate + 500)/1000*infile->channels);
    fprintf(stderr, "Quantization quality: %ld\n", quantqual);
    fprintf(stderr, "Bandwidth: %d Hz\n", cutOff);
    fprintf(stderr, "Object type: ");
    switch(objectType)
    {
    case LOW:
        fprintf(stderr, "Low Complexity");
        break;
    case MAIN:
        fprintf(stderr, "Main");
        break;
    case LTP:
        fprintf(stderr, "LTP");
        break;
    }
    fprintf(stderr, "(MPEG-%d)", (mpegVersion == MPEG4) ? 4 : 2);
    if (myFormat->useTns)
        fprintf(stderr, " + TNS");
    if (myFormat->allowMidside)
        fprintf(stderr, " + M/S");
    fprintf(stderr, "\n");

    fprintf(stderr, "Container format: ");
    switch(container)
    {
    case NO_CONTAINER:
      switch(stream)
    {
    case RAW_STREAM:
      fprintf(stderr, "Headerless AAC (RAW)\n");
      break;
    case ADTS_STREAM:
      fprintf(stderr, "Transport Stream (ADTS)\n");
      break;
    }
        break;
#ifdef HAVE_LIBMP4V2
    case MP4_CONTAINER:
        fprintf(stderr, "MPEG-4 File Format (MP4)\n");
        break;
#endif
    }

    if (outfile
#ifdef HAVE_LIBMP4V2
        || MP4hFile != MP4_INVALID_FILE_HANDLE
#endif
       )
    {
        int showcnt = 0;
#ifdef _WIN32
        long begin = GetTickCount();
#endif
        if (infile->samples)
            frames = ((infile->samples + 1023) / 1024) + 1;
        else
            frames = 0;
        currentFrame = 0;

        fprintf(stderr, "Encoding %s to %s\n", audioFileName, aacFileName);
        if (frames != 0)
            fprintf(stderr, "   frame          | bitrate | elapsed/estim | "
            "play/CPU | ETA\n");
        else
            fprintf(stderr, " frame | elapsed | play/CPU\n");

        /* encoding loop */
#ifdef _WIN32
    for (;;)
#else
        while (running)
#endif
        {
            int bytesWritten;

            samplesRead = wav_read_float32(infile, pcmbuf, samplesInput, chanmap);

#ifdef HAVE_LIBMP4V2
            total_samples += samplesRead / infile->channels;
#endif

            /* call the actual encoding routine */
            bytesWritten = faacEncEncode(hEncoder,
                (int32_t *)pcmbuf,
                samplesRead,
                bitbuf,
                maxBytesOutput);

            if (bytesWritten)
            {
                currentFrame++;
                showcnt--;
        totalBytesWritten += bytesWritten;
            }

            if ((showcnt <= 0) || !bytesWritten)
            {
                double timeused;
#ifdef __unix__
                struct rusage usage;
#endif
#ifdef _WIN32
                char percent[MAX_PATH + 20];
                timeused = (GetTickCount() - begin) * 1e-3;
#else
#ifdef __unix__
                if (getrusage(RUSAGE_SELF, &usage) == 0) {
                    timeused = (double)usage.ru_utime.tv_sec +
                        (double)usage.ru_utime.tv_usec * 1e-6;
                }
                else
                    timeused = 0;
#else
                timeused = (double)clock() * (1.0 / CLOCKS_PER_SEC);
#endif
#endif
                if (currentFrame && (timeused > 0.1))
                {
                    showcnt += 50;

                    if (frames != 0)
                        fprintf(stderr,
                            "\r%5d/%-5d (%3d%%)|  %5.1f  | %6.1f/%-6.1f | %7.2fx | %.1f ",
                            currentFrame, frames, currentFrame*100/frames,
                ((double)totalBytesWritten * 8.0 / 1000.0) /
                ((double)infile->samples / infile->samplerate * currentFrame / frames),
                            timeused,
                            timeused * frames / currentFrame,
                            (1024.0 * currentFrame / infile->samplerate) / timeused,
                            timeused  * (frames - currentFrame) / currentFrame);
                    else
                        fprintf(stderr,
                            "\r %5d |  %6.1f | %7.2fx ",
                            currentFrame,
                            timeused,
                            (1024.0 * currentFrame / infile->samplerate) / timeused);

                    fflush(stderr);
#ifdef _WIN32
                    if (frames != 0)
                    {
                        sprintf(percent, "%.2f%% encoding %s",
                            100.0 * currentFrame / frames, audioFileName);
                        SetConsoleTitle(percent);
                    }
#endif
                }
            }

            /* all done, bail out */
            if (!samplesRead && !bytesWritten)
                break ;

            if (bytesWritten < 0)
            {
                fprintf(stderr, "faacEncEncode() failed\n");
                break ;
            }

            if (bytesWritten > 0)
            {
#ifdef HAVE_LIBMP4V2
                u_int64_t samples_left = total_samples - encoded_samples + delay_samples;
                MP4Duration dur = samples_left > frameSize ? frameSize : samples_left;
                MP4Duration ofs = encoded_samples > 0 ? 0 : delay_samples;

                if (container == MP4_CONTAINER)
                {
                    /* write bitstream to mp4 file */
                    MP4WriteSample(MP4hFile, MP4track, bitbuf, bytesWritten, dur, ofs, 1);
                }
                else
                {
#endif
                    /* write bitstream to aac file */
                    fwrite(bitbuf, 1, bytesWritten, outfile);
#ifdef HAVE_LIBMP4V2
                }

                encoded_samples += dur;
#endif
            }
        }

#ifdef HAVE_LIBMP4V2
        /* clean up */
        if (container == MP4_CONTAINER)
        {
            MP4Close(MP4hFile);
            if (optimizeFlag == 1)
            {
                fprintf(stderr, "\n\nMP4 format optimization... ");
                MP4Optimize(aacFileName, NULL, 0);
                fprintf(stderr, "Done!");
            }
        } else
#endif
            fclose(outfile);

        fprintf(stderr, "\n\n");
    }

    faacEncClose(hEncoder);

    wav_close(infile);

    if (pcmbuf) free(pcmbuf);
    if (bitbuf) free(bitbuf);
    if (aacFileNameGiven) free(aacFileName);

    }

    return 0;
}
コード例 #18
0
ファイル: wav.c プロジェクト: jbmulligan/quip
static void _wav_fatal_error(QSP_ARG_DECL  const char *msg, Image_File *ifp)
{
	wav_error(msg,ifp);
	wav_close(QSP_ARG  ifp);
}