Esempio n. 1
0
int 
main(int argc, char **argv)
{
    int sockfd;
    int newfd;
    int portno;
    int ready;
    fd_set read_set;
    socklen_t socklen;
    struct sockaddr_in serv_addr;
    struct sockaddr_in cli_addr;
    thread_args_t *thread_args;
    pthread_t stream_thread;
    mpg123_handle *mh;
    char buffer[32];
    int bytes_read;

    if (argc < 2) {
      fprintf(stderr, "specify port to listen too\n");
      return 1;
    }
    sockfd = -1;
    newfd = -1;
    stream_thread = -1;

    fprintf(stderr, "bring up ao\n");
    ao_initialize();

    fprintf(stderr, "bring up mpg123\n");
    mpg123_init();
    mh = mpg123_new(NULL, NULL);
    if (!mh) {
        fprintf(stderr, "error mpg123_new()\n");
        goto cleanup;
    }

    fprintf(stderr, "mpg123 initialized\n");
    mpg123_param(mh, MPG123_VERBOSE, 2, 0);

    signal(SIGINT, handle_sigint);

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket");
        goto cleanup;
    }
    memset(&serv_addr, 0, sizeof(serv_addr));
    portno = atoi(argv[1]);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);
    if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("bind");
        goto cleanup;
    }

    if (listen(sockfd, 5) < 0) {
        perror("listen");
        goto cleanup;
    }
    socklen = sizeof(cli_addr);
    g_go_on = 1;
    g_cmd_sock = -1;
    g_busy = 0;
    g_stop = 0;
    FD_ZERO(&g_read_master);
    FD_SET(sockfd, &g_read_master);
    while (g_go_on) {
        read_set = g_read_master;
        ready = select(10, &read_set, NULL, NULL, NULL);
        if (ready < 0) {
            perror("select!!!!");
            //g_go_on = 0;
        } else if (ready > 0) {
            if (FD_ISSET(sockfd, &read_set)) {
                newfd = accept(sockfd, (struct sockaddr *)&cli_addr, &socklen);
                if (newfd < 0) {
                    perror("accept");
                } else {
                    bytes_read = read(newfd, buffer, sizeof(buffer));
                    if (bytes_read > 0) {
                        if (bytes_read >= strlen(IDENT_STREAM_SOCK) &&
                            strncmp(buffer, 
                                    IDENT_STREAM_SOCK,
                                    strlen(IDENT_STREAM_SOCK)) == 0) {
                              fprintf(stderr, "stream sock %d connected\n", newfd);
                              thread_args = malloc(sizeof(thread_args_t));
                              thread_args->mh = mh;
                              thread_args->stream_socket = newfd;
                              if (stream_thread != -1) {
                                  pthread_detach(stream_thread);
                                  stream_thread = -1;
                              }
                              if (pthread_create(&stream_thread, 
                                                 NULL, 
                                                 stream_thread_main,
                                                 thread_args) < 0) {
                                  free(thread_args);
                                  perror("pthread create");
                                  break;
                              }
                        } else if (bytes_read >= strlen(IDENT_CMD_SOCK) &&
                                   strncmp(buffer, 
                                           IDENT_CMD_SOCK,
                                           strlen(IDENT_CMD_SOCK)) == 0) {
                            make_socket_nonblock(newfd);
                            FD_SET(newfd, &g_read_master);
                            g_cmd_sock = newfd;
                            fprintf(stderr, "cmd sock %d connected\n", newfd);
                        }
                    }
                }
            }
            if (FD_ISSET(g_cmd_sock, &read_set)) {
                memset(buffer, 0, sizeof(buffer));
                bytes_read = read(g_cmd_sock, buffer, sizeof(buffer));
                if (bytes_read <= 0) {
                    fprintf(stderr, "read() - lost cmd_sock\n");
                    close_cmd_sock();
                    /* reset paused state here.. otherwise we get in dead lock */
                    /* and stop that bitch */
                    g_paused = 0;
                    g_stop = 1;
                    if (bytes_read != 0) {
                        perror("cmd_sock read");
                    }
                } else {
                    handle_command(buffer, bytes_read);
                }
            }
        }
    }
    fprintf(stderr, "shutdown... waiting for thread\n");

    if (stream_thread != -1 ) {
        pthread_join(stream_thread, NULL);
        pthread_detach(stream_thread);
    }
    
    fprintf(stderr, "shutdown\n");

cleanup:
    if (g_cmd_sock != -1) {
        close_cmd_sock();
    }
    if (sockfd != -1) {
        close(sockfd);
    }
    
    if (mh) {
        fprintf(stderr, "close mpg123\n");
        mpg123_close(mh);
        mpg123_delete(mh);
    }
    mpg123_exit();

    fprintf(stderr, "shutdown ao\n");
    ao_shutdown();

    return 0;
}
JNIEXPORT jint JNICALL Java_com_axelby_mp3decoders_MPG123_init
	(JNIEnv *env, jclass c)
{
	return mpg123_init();
}
Esempio n. 3
0
int main(int argc, char *argv[])
{
	SNDFILE* sndfile = NULL;
	SF_INFO sfinfo;
	mpg123_handle *mh = NULL;
	unsigned char* buffer = NULL;
	size_t buffer_size = 0;
	size_t done = 0;
	int  channels = 0, encoding = 0;
	long rate = 0;
	int  err  = MPG123_OK;
	off_t samples = 0;

	if (argc<3) usage();
	printf( "Input file: %s\n", argv[1]);
	printf( "Output file: %s\n", argv[2]);
	
	err = mpg123_init();
	if(err != MPG123_OK || (mh = mpg123_new(NULL, &err)) == NULL)
	{
		fprintf(stderr, "Basic setup goes wrong: %s", mpg123_plain_strerror(err));
		cleanup(mh);
		return -1;
	}

	/* Simple hack to enable floating point output. */
	if(argc >= 4 && !strcmp(argv[3], "f32")) mpg123_param(mh, MPG123_ADD_FLAGS, MPG123_FORCE_FLOAT, 0.);

	    /* Let mpg123 work with the file, that excludes MPG123_NEED_MORE messages. */
	if(    mpg123_open(mh, argv[1]) != MPG123_OK
	    /* Peek into track and get first output format. */
	    || mpg123_getformat(mh, &rate, &channels, &encoding) != MPG123_OK )
	{
		fprintf( stderr, "Trouble with mpg123: %s\n", mpg123_strerror(mh) );
		cleanup(mh);
		return -1;
	}

	if(encoding != MPG123_ENC_SIGNED_16 && encoding != MPG123_ENC_FLOAT_32)
	{ /* Signed 16 is the default output format anyways; it would actually by only different if we forced it.
	     So this check is here just for this explanation. */
		cleanup(mh);
		fprintf(stderr, "Bad encoding: 0x%x!\n", encoding);
		return -2;
	}
	/* Ensure that this output format will not change (it could, when we allow it). */
	mpg123_format_none(mh);
	mpg123_format(mh, rate, channels, encoding);

	bzero(&sfinfo, sizeof(sfinfo) );
	sfinfo.samplerate = rate;
	sfinfo.channels = channels;
	sfinfo.format = SF_FORMAT_WAV|(encoding == MPG123_ENC_SIGNED_16 ? SF_FORMAT_PCM_16 : SF_FORMAT_FLOAT);
	printf("Creating WAV with %i channels and %liHz.\n", channels, rate);

	sndfile = sf_open(argv[2], SFM_WRITE, &sfinfo);
	if(sndfile == NULL){ fprintf(stderr, "Cannot open output file!\n"); cleanup(mh); return -2; }

	/* Buffer could be almost any size here, mpg123_outblock() is just some recommendation.
	   Important, especially for sndfile writing, is that the size is a multiple of sample size. */
	buffer_size = argc >= 5 ? atol(argv[4]) : mpg123_outblock(mh);
	buffer = malloc( buffer_size );

	do
	{
		sf_count_t more_samples;
		err = mpg123_read( mh, buffer, buffer_size, &done );
		more_samples = encoding == MPG123_ENC_SIGNED_16
			? sf_write_short(sndfile, (short*)buffer, done/sizeof(short))
			: sf_write_float(sndfile, (float*)buffer, done/sizeof(float));
		if(more_samples < 0 || more_samples*mpg123_encsize(encoding) != done)
		{
			fprintf(stderr, "Warning: Written number of samples does not match the byte count we got from libmpg123: %li != %li\n", (long)(more_samples*mpg123_encsize(encoding)), (long)done);
		}
		samples += more_samples;
		/* We are not in feeder mode, so MPG123_OK, MPG123_ERR and MPG123_NEW_FORMAT are the only possibilities.
		   We do not handle a new format, MPG123_DONE is the end... so abort on anything not MPG123_OK. */
	} while (err==MPG123_OK);

	if(err != MPG123_DONE)
	fprintf( stderr, "Warning: Decoding ended prematurely because: %s\n",
	         err == MPG123_ERR ? mpg123_strerror(mh) : mpg123_plain_strerror(err) );

	sf_close( sndfile );

	samples /= channels;
	printf("%li samples written.\n", (long)samples);
	cleanup(mh);
	return 0;
}
Esempio n. 4
0
/***********************************************************************
 *           MPEG3_drvOpen
 */
static LRESULT MPEG3_drvOpen(LPCSTR str)
{
    mpg123_init();
    return 1;
}
Esempio n. 5
0
bool DecoderMPG123::initialize()
{
    if (input()->isSequential ()) //for streams only
    {
        TagExtractor extractor(input());
        if(!extractor.id3v2tag().isEmpty())
            addMetaData(extractor.id3v2tag());
    }

    int err = mpg123_init();
    if(err != MPG123_OK)
    {
        qWarning("DecoderMPG123: basic setup goes wrong: %s", mpg123_plain_strerror(err));
        return false;
    }
    int channels = 0;

    if(!(m_handle = mpg123_new(0, &err)))
    {
        qWarning("DecoderMPG123: basic setup goes wrong: %s", mpg123_plain_strerror(err));
        return false;
    }

    mpg123_param (m_handle, MPG123_ADD_FLAGS, MPG123_SEEKBUFFER | MPG123_FUZZY, 0);

    if((err = mpg123_replace_reader_handle(m_handle, mpg123_read_cb, mpg123_seek_cb, 0)) != MPG123_OK)
    {
        qWarning("DecoderMPG123: mpg123 error: %s", mpg123_plain_strerror(err));
        cleanup(m_handle);
        m_handle = 0;
        return false;
    }
    setMPG123Format(MPG123_ENC_FLOAT_32);

    if((err = mpg123_open_handle(m_handle, this)) != MPG123_OK)
    {
        qWarning("DecoderMPG123: mpg123 error: %s", mpg123_plain_strerror(err));
        cleanup(m_handle);
        m_handle = 0;
        return false;
    }

    if((err = mpg123_getformat(m_handle, &m_rate, &channels, &m_mpg123_encoding)) != MPG123_OK)
    {
        qWarning("DecoderMPG123: mpg123 error: %s", mpg123_plain_strerror(err));
        cleanup(m_handle);
        m_handle = 0;
        return false;
    }
    //check format
    if(m_mpg123_encoding != MPG123_ENC_FLOAT_32)
    {
        cleanup(m_handle);
        qWarning("DecoderMPG123: bad encoding: 0x%x!\n", m_mpg123_encoding);
        m_handle = 0;
        return false;
    }

    if(!input()->isSequential())
    {
        if((err = mpg123_scan(m_handle)) != MPG123_OK)
            qWarning("DecoderMPG123: mpg123 error: %s", mpg123_plain_strerror(err));
        //duration
        m_totalTime = (qint64) mpg123_length(m_handle) * 1000 / m_rate;
    }
    else
        m_totalTime = 0;

    configure(m_rate, channels, Qmmp::PCM_FLOAT);
    return true;
}
Esempio n. 6
0
/* This initializes libmpg123 and prepares the handle, including funky
 * parameters. */
static int preinit(sh_audio_t *sh)
{
    int err, flag;
    struct ad_mpg123_context *con;
    /* Assumption: You always call preinit + init + uninit, on every file.
     * But you stop at preinit in case it fails.
     * If that is not true, one must ensure not to call mpg123_init / exit
     * twice in a row. */
    if (mpg123_init() != MPG123_OK)
        return 0;

    sh->context = malloc(sizeof(struct ad_mpg123_context));
    con = sh->context;
    /* Auto-choice of optimized decoder (first argument NULL). */
    con->handle = mpg123_new(NULL, &err);
    if (!con->handle)
        goto bad_end;

    /* Guessing here: Default value triggers forced upmix of mono to stereo. */
    flag = fakemono == 0 ? MPG123_FORCE_STEREO :
           fakemono == 1 ? MPG123_MONO_LEFT    :
           fakemono == 2 ? MPG123_MONO_RIGHT   : 0;
    if (mpg123_param(con->handle, MPG123_ADD_FLAGS, flag, 0.0) != MPG123_OK)
        goto bad_end;

    /* Basic settings.
     * Don't spill messages, enable better resync with non-seekable streams.
     * Give both flags individually without error checking to keep going with
     * old libmpg123. Generally, it is not fatal if the flags are not
     * honored */
    mpg123_param(con->handle, MPG123_ADD_FLAGS, MPG123_QUIET, 0.0);
    /* Do not bail out on malformed streams at all.
     * MPlayer does not handle a decoder throwing the towel on crappy input. */
    mpg123_param(con->handle, MPG123_RESYNC_LIMIT, -1, 0.0);

    /* Open decisions: Configure libmpg123 to force encoding (or stay open about
     * library builds that support only float or int32 output), (de)configure
     * gapless decoding (won't work with seeking in MPlayer, though).
     * Don't forget to eventually enable ReplayGain/RVA support, too.
     * Let's try to run with the default for now. */

    /* That would produce floating point output.
     * You can get 32 and 24 bit ints, even 8 bit via format matrix. */
    /* mpg123_param(con->handle, MPG123_ADD_FLAGS, MPG123_FORCE_FLOAT, 0.); */

    /* Example for RVA choice (available since libmpg123 1.0.0):
    mpg123_param(con->handle, MPG123_RVA, MPG123_RVA_MIX, 0.0) */

#ifdef AD_MPG123_FRAMEWISE
    /* Prevent funky automatic resampling.
     * This way, we can be sure that one frame will never produce
     * more than 1152 stereo samples. */
    mpg123_param(con->handle, MPG123_REMOVE_FLAGS, MPG123_AUTO_RESAMPLE, 0.);
#else
    /* Older mpg123 is vulnerable to concatenated streams when gapless cutting
     * is enabled (will only play the jingle of a badly constructed radio
     * stream). The versions using framewise decoding are fine with that. */
    mpg123_param(con->handle, MPG123_REMOVE_FLAGS, MPG123_GAPLESS, 0.);
#endif

    return 1;

  bad_end:
    if (!con->handle)
        mp_msg(MSGT_DECAUDIO, MSGL_ERR, "mpg123 preinit error: %s\n",
               mpg123_plain_strerror(err));
    else
        mp_msg(MSGT_DECAUDIO, MSGL_ERR, "mpg123 preinit error: %s\n",
               mpg123_strerror(con->handle));

    if (con->handle)
        mpg123_delete(con->handle);
    mpg123_exit();
    free(sh->context);
    sh->context = NULL;
    return 0;
}
Esempio n. 7
0
int main(int sys_argc, char ** sys_argv)
{
	int result;
	char end_of_files = FALSE;
	long parr;
	char *fname;
	int libpar = 0;
	mpg123_pars *mp;
#if !defined(WIN32) && !defined(GENERIC)
	struct timeval start_time;
#endif
	aux_out = stdout; /* Need to initialize here because stdout is not a constant?! */
#if defined (WANT_WIN32_UNICODE)
	if(win32_cmdline_utf8(&argc, &argv) != 0)
	{
		error("Cannot convert command line to UTF8!");
		safe_exit(76);
	}
#else
	argv = sys_argv;
	argc = sys_argc;
#endif
#if defined (WANT_WIN32_SOCKETS)
	win32_net_init();
#endif

	/* Extract binary and path, take stuff before/after last / or \ . */
	if((prgName = strrchr(argv[0], '/')) || (prgName = strrchr(argv[0], '\\')))
	{
		/* There is some explicit path. */
		prgName[0] = 0; /* End byte for path. */
		prgName++;
		binpath = argv[0];
	}
	else
	{
		prgName = argv[0]; /* No path separators there. */
		binpath = NULL; /* No path at all. */
	}

	/* Need to initialize mpg123 lib here for default parameter values. */

	result = mpg123_init();
	if(result != MPG123_OK)
	{
		error1("Cannot initialize mpg123 library: %s", mpg123_plain_strerror(result));
		safe_exit(77);
	}
	cleanup_mpg123 = TRUE;

	mp = mpg123_new_pars(&result); /* This may get leaked on premature exit(), which is mainly a cosmetic issue... */
	if(mp == NULL)
	{
		error1("Crap! Cannot get mpg123 parameters: %s", mpg123_plain_strerror(result));
		safe_exit(78);
	}

	/* get default values */
	mpg123_getpar(mp, MPG123_DOWN_SAMPLE, &parr, NULL);
	param.down_sample = (int) parr;
	mpg123_getpar(mp, MPG123_RVA, &param.rva, NULL);
	mpg123_getpar(mp, MPG123_DOWNSPEED, &param.halfspeed, NULL);
	mpg123_getpar(mp, MPG123_UPSPEED, &param.doublespeed, NULL);
	mpg123_getpar(mp, MPG123_OUTSCALE, &param.outscale, NULL);
	mpg123_getpar(mp, MPG123_FLAGS, &parr, NULL);
	mpg123_getpar(mp, MPG123_INDEX_SIZE, &param.index_size, NULL);
	param.flags = (int) parr;
	param.flags |= MPG123_SEEKBUFFER; /* Default on, for HTTP streams. */
	mpg123_getpar(mp, MPG123_RESYNC_LIMIT, &param.resync_limit, NULL);
	mpg123_getpar(mp, MPG123_PREFRAMES, &param.preframes, NULL);

#ifdef OS2
        _wildcard(&argc,&argv);
#endif

	while ((result = getlopt(argc, argv, opts)))
	switch (result) {
		case GLO_UNKNOWN:
			fprintf (stderr, "%s: Unknown option \"%s\".\n", 
				prgName, loptarg);
			usage(1);
		case GLO_NOARG:
			fprintf (stderr, "%s: Missing argument for option \"%s\".\n",
				prgName, loptarg);
			usage(1);
	}
	/* Do this _after_ parameter parsing. */
	check_locale(); /* Check/set locale; store if it uses UTF-8. */

	if(param.list_cpu)
	{
		const char **all_dec = mpg123_decoders();
		printf("Builtin decoders:");
		while(*all_dec != NULL){ printf(" %s", *all_dec); ++all_dec; }
		printf("\n");
		mpg123_delete_pars(mp);
		return 0;
	}
	if(param.test_cpu)
	{
		const char **all_dec = mpg123_supported_decoders();
		printf("Supported decoders:");
		while(*all_dec != NULL){ printf(" %s", *all_dec); ++all_dec; }
		printf("\n");
		mpg123_delete_pars(mp);
		return 0;
	}
	if(param.gain != -1)
	{
	    warning("The parameter -g is deprecated and may be removed in the future.");
	}

	if (loptind >= argc && !param.listname && !param.remote) usage(1);
	/* Init audio as early as possible.
	   If there is the buffer process to be spawned, it shouldn't carry the mpg123_handle with it. */
	bufferblock = mpg123_safe_buffer(); /* Can call that before mpg123_init(), it's stateless. */
	if(init_output(&ao) < 0)
	{
		error("Failed to initialize output, goodbye.");
		mpg123_delete_pars(mp);
		return 99; /* It's safe here... nothing nasty happened yet. */
	}
	have_output = TRUE;

	/* ========================================================================================================= */
	/* Enterning the leaking zone... we start messing with stuff here that should be taken care of when leaving. */
	/* Don't just exit() or return out...                                                                        */
	/* ========================================================================================================= */

	httpdata_init(&htd);

#if !defined(WIN32) && !defined(GENERIC)
	if (param.remote)
	{
		param.verbose = 0;
		param.quiet = 1;
		param.flags |= MPG123_QUIET;
	}
#endif

	/* Set the frame parameters from command line options */
	if(param.quiet) param.flags |= MPG123_QUIET;

#ifdef OPT_3DNOW
	if(dnow != 0) param.cpu = (dnow == SET_3DNOW) ? "3dnow" : "i586";
#endif
	if(param.cpu != NULL && (!strcmp(param.cpu, "auto") || !strcmp(param.cpu, ""))) param.cpu = NULL;
	if(!(  MPG123_OK == (result = mpg123_par(mp, MPG123_VERBOSE, param.verbose, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_FLAGS, param.flags, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_DOWN_SAMPLE, param.down_sample, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_RVA, param.rva, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_FORCE_RATE, param.force_rate, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_DOWNSPEED, param.halfspeed, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_UPSPEED, param.doublespeed, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_ICY_INTERVAL, 0, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_RESYNC_LIMIT, param.resync_limit, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_TIMEOUT, param.timeout, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_OUTSCALE, param.outscale, 0))
	    && ++libpar
	    && MPG123_OK == (result = mpg123_par(mp, MPG123_PREFRAMES, param.preframes, 0))
			))
	{
		error2("Cannot set library parameter %i: %s", libpar, mpg123_plain_strerror(result));
		safe_exit(45);
	}
	if (!(param.listentry < 0) && !param.quiet) print_title(stderr); /* do not pollute stdout! */

	{
		long default_index;
		mpg123_getpar(mp, MPG123_INDEX_SIZE, &default_index, NULL);
		if( param.index_size != default_index && (result = mpg123_par(mp, MPG123_INDEX_SIZE, param.index_size, 0.)) != MPG123_OK )
		error1("Setting of frame index size failed: %s", mpg123_plain_strerror(result));
	}

	if(param.force_rate && param.down_sample)
	{
		error("Down sampling and fixed rate options not allowed together!");
		safe_exit(1);
	}

	/* Now actually get an mpg123_handle. */
	mh = mpg123_parnew(mp, param.cpu, &result);
	if(mh == NULL)
	{
		error1("Crap! Cannot get a mpg123 handle: %s", mpg123_plain_strerror(result));
		safe_exit(77);
	}
	mpg123_delete_pars(mp); /* Don't need the parameters anymore ,they're in the handle now. */

	/* Prepare stream dumping, possibly replacing mpg123 reader. */
	if(dump_open(mh) != 0) safe_exit(78);

	/* Now either check caps myself or query buffer for that. */
	audio_capabilities(ao, mh);

	load_equalizer(mh);

#ifdef HAVE_SETPRIORITY
	if(param.aggressive) { /* tst */
		int mypid = getpid();
		setpriority(PRIO_PROCESS,mypid,-20);
	}
#endif

#if defined (HAVE_SCHED_SETSCHEDULER) && !defined (__CYGWIN__) && !defined (HAVE_WINDOWS_H)
/* Cygwin --realtime seems to fail when accessing network, using win32 set priority instead */
/* MinGW may have pthread installed, we prefer win32API */
	if (param.realtime) {  /* Get real-time priority */
	  struct sched_param sp;
	  fprintf(stderr,"Getting real-time priority\n");
	  memset(&sp, 0, sizeof(struct sched_param));
	  sp.sched_priority = sched_get_priority_min(SCHED_FIFO);
	  if (sched_setscheduler(0, SCHED_RR, &sp) == -1)
	    fprintf(stderr,"Can't get real-time priority\n");
	}
#endif

#ifdef HAVE_WINDOWS_H
	/* argument "3" is equivalent to realtime priority class */
	win32_set_priority( param.realtime ? 3 : param.w32_priority);
#endif

	if(!param.remote) prepare_playlist(argc, argv);

#if !defined(WIN32) && !defined(GENERIC)
	/* Remote mode is special... but normal console and terminal-controlled operation needs to catch the SIGINT.
	   For one it serves for track skip when not in terminal control mode.
	   The more important use being a graceful exit, including telling the buffer process what's going on. */
	if(!param.remote) catchsignal (SIGINT, catch_interrupt);
#endif

	if(param.remote) {
		int ret;
		ret = control_generic(mh);
		safe_exit(ret);
	}
#ifdef HAVE_TERMIOS
		debug1("param.term_ctrl: %i", param.term_ctrl);
		if(param.term_ctrl)
			term_init();
#endif
	if(APPFLAG(MPG123APP_CONTINUE)) frames_left = param.frame_number;

	while ((fname = get_next_file()))
	{
		char *dirname, *filename;
		int newdir;
		/* skip_tracks includes the previous one. */
		if(skip_tracks) --skip_tracks;
		if(skip_tracks)
		{
			debug("Skipping this track.");
			continue;
		}
		if(param.delay > 0)
		{
			/* One should enable terminal control during that sleeping phase! */
			if(param.verbose > 2) fprintf(stderr, "Note: pausing %i seconds before next track.\n", param.delay);
			output_pause(ao);
#ifdef WIN32
			Sleep(param.delay*1000);
#else
			sleep(param.delay);
#endif
			output_unpause(ao);
		}
		if(!APPFLAG(MPG123APP_CONTINUE)) frames_left = param.frame_number;

		debug1("Going to play %s", strcmp(fname, "-") ? fname : "standard input");

		if(intflag || !open_track(fname))
		{
#ifdef HAVE_TERMIOS
			/* We need the opportunity to cancel in case of --loop -1 . */
			if(param.term_ctrl) term_control(mh, ao);
#endif
			/* No wait for a second interrupt before we started playing. */
			if(intflag) break;

			continue;
		}

		if(!param.quiet) fprintf(stderr, "\n");
		if(param.index)
		{
			if(param.verbose) fprintf(stderr, "indexing...\r");
			mpg123_scan(mh);
		}
		/*
			Only trigger a seek if we do not want to start with the first frame.
			Rationale: Because of libmpg123 sample accuracy, this could cause an unnecessary backwards seek, that even may fail on non-seekable streams.
			For start frame of 0, we are already at the correct position!
		*/
		framenum = 0;
		if(param.start_frame > 0)
		framenum = mpg123_seek_frame(mh, param.start_frame, SEEK_SET);

		if(APPFLAG(MPG123APP_CONTINUE)) param.start_frame = 0;

		if(framenum < 0)
		{
			error1("Initial seek failed: %s", mpg123_strerror(mh));
			if(mpg123_errcode(mh) == MPG123_BAD_OUTFORMAT)
			{
				fprintf(stderr, "%s", "So, you have trouble getting an output format... this is the matrix of currently possible formats:\n");
				print_capabilities(ao, mh);
				fprintf(stderr, "%s", "Somehow the input data and your choices don't allow one of these.\n");
			}
			mpg123_close(mh);
			continue;
		}

		/* Prinout and xterm title need this, possibly independently. */
		newdir = split_dir_file(fname ? fname : "standard input", &dirname, &filename);

		if (!param.quiet)
		{
			if(newdir) fprintf(stderr, "Directory: %s\n", dirname);

#ifdef HAVE_TERMIOS
		/* Reminder about terminal usage. */
		if(param.term_ctrl) term_hint();
#endif


			fprintf(stderr, "Playing MPEG stream %lu of %lu: %s ...\n", (unsigned long)pl.pos, (unsigned long)pl.fill, filename);
			if(htd.icy_name.fill) fprintf(stderr, "ICY-NAME: %s\n", htd.icy_name.p);
			if(htd.icy_url.fill)  fprintf(stderr, "ICY-URL: %s\n",  htd.icy_url.p);
		}
#if !defined(GENERIC)
{
	const char *term_type;
	term_type = getenv("TERM");
	if(term_type && param.xterm_title)
	{
		if(!strncmp(term_type,"xterm",5) || !strncmp(term_type,"rxvt",4))
		fprintf(stderr, "\033]0;%s\007", filename);
		else if(!strncmp(term_type,"screen",6))
		fprintf(stderr, "\033k%s\033\\", filename);
		else if(!strncmp(term_type,"iris-ansi",9))
		fprintf(stderr, "\033P1.y %s\033\\\033P3.y%s\033\\", filename, filename);

		fflush(stderr); /* Paranoia: will the buffer buffer the escapes? */
	}
}
#endif

/* Rethink that SIGINT logic... */
#if !defined(WIN32) && !defined(GENERIC)
#ifdef HAVE_TERMIOS
		if(!param.term_ctrl)
#endif
			gettimeofday (&start_time, NULL);
#endif

		while(!intflag)
		{
			int meta;
			if(param.frame_number > -1)
			{
				debug1("frames left: %li", (long) frames_left);
				if(!frames_left)
				{
					if(APPFLAG(MPG123APP_CONTINUE)) end_of_files = TRUE;

					break;
				}
			}
			if(!play_frame()) break;
			if(!param.quiet)
			{
				meta = mpg123_meta_check(mh);
				if(meta & (MPG123_NEW_ID3|MPG123_NEW_ICY))
				{
					if(meta & MPG123_NEW_ID3) print_id3_tag(mh, param.long_id3, stderr);
					if(meta & MPG123_NEW_ICY) print_icy(mh, stderr);

					mpg123_meta_free(mh); /* Do not waste memory after delivering. */
				}
			}
			if(!fresh && param.verbose)
			{
#ifndef NOXFERMEM
				if (param.verbose > 1 || !(framenum & 0x7))
					print_stat(mh,0,xfermem_get_usedspace(buffermem)); 
#else
				if(param.verbose > 1 || !(framenum & 0x7))	print_stat(mh,0,0);
#endif
			}
#ifdef HAVE_TERMIOS
			if(!param.term_ctrl) continue;
			else term_control(mh, ao);
#endif
		}

	if(!param.smooth && param.usebuffer) buffer_drain();
	if(param.verbose) print_stat(mh,0,xfermem_get_usedspace(buffermem)); 

	if(!param.quiet)
	{
		double secs;
		long frank;
		fprintf(stderr, "\n");
		if(mpg123_getstate(mh, MPG123_FRANKENSTEIN, &frank, NULL) == MPG123_OK && frank)
		fprintf(stderr, "This was a Frankenstein track.\n");

		mpg123_position(mh, 0, 0, NULL, NULL, &secs, NULL);
		fprintf(stderr,"[%d:%02d] Decoding of %s finished.\n", (int)(secs / 60), ((int)secs) % 60, filename);
	}
	else if(param.verbose) fprintf(stderr, "\n");

	mpg123_close(mh);

	if (intflag)
	{
		if(!skip_or_die(&start_time)) break;

        intflag = FALSE;

#ifndef NOXFERMEM
        if(!param.smooth && param.usebuffer) buffer_resync();
#endif
	}

		if(end_of_files) break;
	} /* end of loop over input files */

	/* Ensure we played everything. */
	if(param.smooth && param.usebuffer)
	{
		buffer_drain();
		buffer_resync();
	}

	if(APPFLAG(MPG123APP_CONTINUE))
	{
		continue_msg("CONTINUE");
	}

	/* Free up memory used by playlist */    
	if(!param.remote) free_playlist();

	safe_exit(0); /* That closes output and restores terminal, too. */
	return 0;
}
Esempio n. 8
0
void fm_player_init()
{
    ao_initialize();
    mpg123_init();
}
Esempio n. 9
0
static
float* readaudio_mp3(const char *filename,long *sr, const float nbsecs, unsigned int *buflen) {
    mpg123_handle *m;
    int ret;

    if (mpg123_init() != MPG123_OK || ((m = mpg123_new(NULL,&ret)) == NULL)|| \
            mpg123_open(m, filename) != MPG123_OK) {
        fprintf(stderr,"unable to init mpg\n");
        return NULL;
    }

    /*turn off logging */
    mpg123_param(m, MPG123_ADD_FLAGS, MPG123_QUIET, 0);

    off_t totalsamples;

    mpg123_scan(m);
    totalsamples = mpg123_length(m);

    int meta = mpg123_meta_check(m);

    int channels, encoding;

    if (mpg123_getformat(m, sr, &channels, &encoding) != MPG123_OK) {
        fprintf(stderr,"unable to get format\n");
        return NULL;
    }

    mpg123_format_none(m);
    mpg123_format(m, *sr, channels, encoding);

    size_t decbuflen = mpg123_outblock(m);
    unsigned char *decbuf = (unsigned char*)malloc(decbuflen);
    if (decbuf == NULL) {
        printf("mem alloc error\n");
        return NULL;
    }

    unsigned int nbsamples = (nbsecs <= 0) ? totalsamples : nbsecs*(*sr);
    nbsamples = (nbsamples < totalsamples) ? nbsamples : totalsamples;

    size_t i, j, index = 0, done;


    float *buffer = (float*)malloc(nbsamples*sizeof(float));
    *buflen = nbsamples;

    do {

        ret = mpg123_read(m, decbuf, decbuflen, &done);
        switch (encoding) {
        case MPG123_ENC_SIGNED_16 :
            for (i = 0; i < done/sizeof(short); i+=channels) {
                buffer[index] = 0.0f;
                for (j = 0; j < channels ; j++) {
                    buffer[index] += (float)(((short*)decbuf)[i+j])/(float)SHRT_MAX;
                }
                buffer[index++] /= channels;
                if (index >= nbsamples) break;
            }
            break;
        case MPG123_ENC_SIGNED_8:
            for (i = 0; i < done/sizeof(char); i+=channels) {
                buffer[index] = 0.0f;
                for (j = 0; j < channels ; j++) {
                    buffer[index] += (float)(((char*)decbuf)[i+j])/(float)SCHAR_MAX;
                }
                buffer[index++] /= channels;
                if (index >= nbsamples) break;
            }
            break;
        case MPG123_ENC_FLOAT_32:
            for (i = 0; i < done/sizeof(float); i+=channels) {
                buffer[index] = 0.0f;
                for (j = 0; j < channels; j++) {
                    buffer[index] += ((float*)decbuf)[i+j];
                }
                buffer[index++] /= channels;
                if (index >= nbsamples) break;
            }
            break;
        default:
            done = 0;
        }

    } while (ret == MPG123_OK && index < nbsamples);

    free(decbuf);
    mpg123_close(m);
    mpg123_delete(m);
    mpg123_exit();

    return buffer;
}
Esempio n. 10
0
static void
gst_mpg123_audio_dec_class_init (GstMpg123AudioDecClass * klass)
{
  GObjectClass *object_class;
  GstAudioDecoderClass *base_class;
  GstElementClass *element_class;
  GstPadTemplate *src_template;
  int error;

  GST_DEBUG_CATEGORY_INIT (mpg123_debug, "mpg123", 0, "mpg123 mp3 decoder");

  object_class = G_OBJECT_CLASS (klass);
  base_class = GST_AUDIO_DECODER_CLASS (klass);
  element_class = GST_ELEMENT_CLASS (klass);

  object_class->finalize = gst_mpg123_audio_dec_finalize;

  gst_element_class_set_static_metadata (element_class,
      "mpg123 mp3 decoder",
      "Codec/Decoder/Audio",
      "Decodes mp3 streams using the mpg123 library",
      "Carlos Rafael Giani <[email protected]>");

  /*
     Not using static pad template for srccaps, since the comma-separated list of formats needs to be
     created depending on whatever mpg123 supports
   */
  {
    const int *format_list;
    const long *rates_list;
    size_t num, i;
    GString *s;

    s = g_string_new ("audio/x-raw, ");

    mpg123_encodings (&format_list, &num);
    g_string_append (s, "format = { ");
    for (i = 0; i < num; ++i) {
      switch (format_list[i]) {
        case MPG123_ENC_SIGNED_16:
          g_string_append (s, (i > 0) ? ", " : "");
          g_string_append (s, GST_AUDIO_NE (S16));
          break;
        case MPG123_ENC_UNSIGNED_16:
          g_string_append (s, (i > 0) ? ", " : "");
          g_string_append (s, GST_AUDIO_NE (U16));
          break;
        case MPG123_ENC_SIGNED_24:
          g_string_append (s, (i > 0) ? ", " : "");
          g_string_append (s, GST_AUDIO_NE (S24));
          break;
        case MPG123_ENC_UNSIGNED_24:
          g_string_append (s, (i > 0) ? ", " : "");
          g_string_append (s, GST_AUDIO_NE (U24));
          break;
        case MPG123_ENC_SIGNED_32:
          g_string_append (s, (i > 0) ? ", " : "");
          g_string_append (s, GST_AUDIO_NE (S32));
          break;
        case MPG123_ENC_UNSIGNED_32:
          g_string_append (s, (i > 0) ? ", " : "");
          g_string_append (s, GST_AUDIO_NE (U32));
          break;
        case MPG123_ENC_FLOAT_32:
          g_string_append (s, (i > 0) ? ", " : "");
          g_string_append (s, GST_AUDIO_NE (F32));
          break;
        default:
          GST_DEBUG ("Ignoring mpg123 format %d", format_list[i]);
          break;
      }
    }
    g_string_append (s, " }, ");

    mpg123_rates (&rates_list, &num);
    g_string_append (s, "rate = (int) { ");
    for (i = 0; i < num; ++i) {
      g_string_append_printf (s, "%s%lu", (i > 0) ? ", " : "", rates_list[i]);
    }
    g_string_append (s, "}, ");

    g_string_append (s, "channels = (int) [ 1, 2 ], ");
    g_string_append (s, "layout = (string) interleaved");

    src_template = gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
        gst_caps_from_string (s->str));

    g_string_free (s, TRUE);
  }

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&sink_template));
  gst_element_class_add_pad_template (element_class, src_template);

  base_class->start = GST_DEBUG_FUNCPTR (gst_mpg123_audio_dec_start);
  base_class->stop = GST_DEBUG_FUNCPTR (gst_mpg123_audio_dec_stop);
  base_class->handle_frame =
      GST_DEBUG_FUNCPTR (gst_mpg123_audio_dec_handle_frame);
  base_class->set_format = GST_DEBUG_FUNCPTR (gst_mpg123_audio_dec_set_format);
  base_class->flush = GST_DEBUG_FUNCPTR (gst_mpg123_audio_dec_flush);

  error = mpg123_init ();
  if (G_UNLIKELY (error != MPG123_OK))
    GST_ERROR ("Could not initialize mpg123 library: %s",
        mpg123_plain_strerror (error));
  else
    GST_TRACE ("mpg123 library initialized");
}
Esempio n. 11
0
void SYS_InitSound()
{
	
#ifdef SYS_SOUNDDEBUG
	soundsLoaded = 0;
	soundsFree = SIZEOFWAVEPOOL;
	soundLog = fopen( soundLogFileName, "w" );
	fprintf(soundLog, "SYS_InitSound() - OpenAL SKU - %d sounds in pool\n", soundsFree);
	
	if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT") == AL_TRUE)
	{
		const char* devicesStr = alcGetString(0, ALC_DEVICE_SPECIFIER);
		const char* defaultDeviceStr = alcGetString(0, ALC_DEFAULT_DEVICE_SPECIFIER);
		fprintf(soundLog, "OpenAL default device = %s\n", defaultDeviceStr);
		
		fprintf(soundLog, "All devices:\n");
		const char* p = devicesStr;
		while( *p )
		{
			fprintf(soundLog, "%s\n", p);
			p += (strlen(p) + 1);
		}
	}
#endif

	// open device
	ALCdevice* device = alcOpenDevice(0);
	if ( !device )
	{
		SYS_Error("Error opening OpenAL device\n");
		return;
	}
	
#ifdef SYS_SOUNDDEBUG
	const char* extStr = alcGetString(device, ALC_EXTENSIONS);
	fprintf(soundLog, "OpenAL extentions : %s\n", extStr);
#endif

	alGetError(); // clear error code

	// create context
	ALCcontext* context = alcCreateContext(device,0);
	alcMakeContextCurrent(context);
	CheckForErrors();
	
	// use linear distance model & disable doppler.
	alDistanceModel(AL_LINEAR_DISTANCE_CLAMPED);
	alDopplerFactor(0.0f);

	// init wave pools
	memset(wavePool, 0, sizeof(struct SYS_Wave) * SIZEOFWAVEPOOL);
	freeList = wavePool;
	usedList = 0;
	for ( int i = 0; i < SIZEOFWAVEPOOL; ++i )
	{
		freeList[i].prev = (i == 0) ? 0 : &wavePool[i-1];
		freeList[i].next = (i == SIZEOFWAVEPOOL-1) ? 0 : &wavePool[i+1];
	}

	// init source pool
	memset(sourcePool, 0, sizeof(ALuint) * SIZEOFSOURCEPOOL);
	CheckForErrors();
	
	int error = mpg123_init();
	if (error != MPG123_OK)
	{
		printf("Error mpg123_init() : %s\n", mpg123_plain_strerror(error));
	}
}
Esempio n. 12
0
void GGAudioManager::systemInit()
{
    mpg123_init();
}
Esempio n. 13
0
DWORD InitSerivce()
{
	DWORD ret;
	DWORD i;
	char ip[20] = {0};
	int port;
	WSADATA wsaData;
	SOCKADDR_IN inAddr;
	char configFile[MAX_PATH] = {0};
	char *q;
	FILE *f;

	GetModuleFileName(NULL, configFile, sizeof(configFile));
	q = strrchr(configFile, '\\');
	if(q == NULL)
	{
		return 10;
	}
	q++;
	*q = '\0';
	strcat(configFile, CONFIG_FILE);

	ret = GetPrivateProfileString("music", "dir", "", dir, sizeof(dir), configFile);
	if (ret == 0)
	{
		return 1;
	}

	ret = GetPrivateProfileString("network", "ip", "", ip, sizeof(ip), configFile);
	if (ret == 0)
	{
		return 1;
	}

	port = GetPrivateProfileInt("network", "port", 0, configFile);
	if(port == 0)
	{
		return 1;
	}

	_snprintf(glob_file, sizeof(glob_file), "%s\\*.mp3", dir);	

	ret = mpg123_init();
	if(ret != MPG123_OK)
	{
		return 2;
	}

	mh = mpg123_new(NULL, &ret);
	if(mh == NULL)
	{
		return 3;
	}

	for(i = 0; i < HEAD_NUM; i++)
	{
		p[i] = (LPSTR)malloc(SOUND_BUFFER_LEN);
		pHeader[i] = (LPWAVEHDR)malloc(sizeof(WAVEHDR));
		if(p[i] == NULL ||
			pHeader[i] == NULL)
		{
			return 4;
		}
	}

	ret = WSAStartup(0x0202, &wsaData);
	if(ret != 0)
	{
		return 5;
	}

	sock = socket(AF_INET, SOCK_STREAM, 0);
	if(sock == INVALID_SOCKET)
	{
		return 6;	
	}

	inAddr.sin_family = AF_INET;
	inAddr.sin_addr.s_addr = inet_addr(ip);
	inAddr.sin_port = htons(port);

	ret = bind(sock, (const struct sockaddr *)&inAddr, sizeof(inAddr));
	if(ret == SOCKET_ERROR)
	{
		return 7;
	}

	ret = listen(sock, 1);
	if(ret == SOCKET_ERROR)
	{
		return 8;
	}

	if(!PathFileExists(dir))
	{
		return 9;
	}

	InitializeCriticalSection(&cs);

	return 0;
}
Esempio n. 14
0
/* Open an MPEG stream and prepare for decode */
static int libmpg123_init(const char *fn) {
	int err;
	uint32	fd;
	
	/* Open the file */
#ifdef BS_SIZE
	mp3_fd = fd = fs_open(fn, O_RDONLY);
#else
	fd = fs_open(fn, O_RDONLY);
#endif
	
	if (fd < 0) {
		printf("Can't open input file %s\r\n", fn);
		printf("getwd() returns '%s'\r\n", fs_getwd());
		return -1;
	}
	
#ifndef BS_SIZE	
	fs_close(fd);
#endif
	
	if (fn != mp3_last_fn) {
		if (fn[0] != '/') {
			strcpy(mp3_last_fn, fs_getwd());
			strcat(mp3_last_fn, "/");
			strcat(mp3_last_fn, fn);
		} else {
			strcpy(mp3_last_fn, fn);
		}
	}

	/* Allocate buffers */
	if (pcm_buffer == NULL)
		pcm_buffer = malloc(PCM_SIZE);
	pcm_ptr = pcm_buffer; pcm_count = pcm_discard = 0;

	
#ifdef BS_SIZE

	if (bs_buffer == NULL)
		bs_buffer = malloc(BS_SIZE);
	bs_ptr = bs_buffer; bs_count = 0;

	/* Fill bitstream buffer */
	if (bs_fill() < 0) {
		printf("Can't read file header\r\n");
		goto errorout;
	}

	/* Are we looking at a RIFF file? (stupid Windows encoders) */
	if (bs_ptr[0] == 'R' && bs_ptr[1] == 'I' && bs_ptr[2] == 'F' && bs_ptr[3] == 'F') {
		/* Found a RIFF header, scan through it until we find the data section */
		printf("Skipping stupid RIFF header\r\n");
		while (bs_ptr[0] != 'd' || bs_ptr[1] != 'a' || bs_ptr[2] != 't'	|| bs_ptr[3] != 'a') {
			bs_ptr++;
			if (bs_ptr >= (bs_buffer + BS_SIZE)) {
				printf("Indeterminately long RIFF header\r\n");
				goto errorout;
			}
		}

		/* Skip 'data' and length */
		bs_ptr += 8;
		bs_count -= (bs_ptr - bs_buffer);
		printf("Final index is %d\r\n", (bs_ptr - bs_buffer));
	}

	if (((uint8)bs_ptr[0] != 0xff) && (!((uint8)bs_ptr[1] & 0xe0))) {
		printf("Definitely not an MPEG file\r\n");
		goto errorout;
	}
#endif
	
	mpg123_init();
    mh = mpg123_new(NULL, &err);

	if(mh == NULL) {
		printf("Can't init mpg123: %s\n", mpg123_strerror(mh));
		goto errorout;
	}
   
    /* Open the MP3 context in open_fd mode */
#ifdef BS_SIZE
    err = mpg123_open_fd(mh, mp3_fd);
#else
	err = mpg123_open(mh, fn);
#endif
 
	if(err != MPG123_OK) {
		printf("Can't open mpg123\n");
		mpg123_exit();
		goto errorout;
	}

	int enc;

	mpg123_getformat(mh, &rate, &channels, &enc);
	mpg123_info(mh, &decinfo);
	
	printf("Output Sampling rate = %ld\r\n", decinfo.rate);
	printf("Output Bitrate       = %d\r\n", decinfo.bitrate);
	printf("Output Frame size    = %d\r\n", decinfo.framesize);

	printf("mpg123 initialized successfully\r\n");
	return 0;

errorout:
	printf("Exiting on error\r\n");
#ifdef BS_SIZE
	if (bs_buffer) {
		free(bs_buffer);
		bs_buffer = NULL;
	}
#endif
	if (pcm_buffer) {
		free(pcm_buffer);
		pcm_buffer = NULL;
	}
#ifdef BS_SIZE
	fs_close(fd);
	mp3_fd = 0;
#endif
	return -1;
}
Esempio n. 15
0
	Mpeg123Initializer()
	{
		mpg123_init();
	}
Esempio n. 16
0
VGMSTREAM * init_vgmstream_genh(STREAMFILE *streamFile) {
    
	VGMSTREAM * vgmstream = NULL;
    
	int32_t channel_count;
    int32_t interleave;
    int32_t sample_rate;
    int32_t loop_start;
    int32_t loop_end;
    int32_t start_offset;
    int32_t header_size;
	int32_t coef[2];
	int32_t dsp_interleave_type;
	
    char filename[260];
    int coding;
#ifdef VGM_USE_MPEG
    mpeg_codec_data *data = NULL;
#endif

    /* check extension, case insensitive */
    streamFile->get_name(streamFile,filename,sizeof(filename));
    if (strcasecmp("genh",filename_extension(filename))) goto fail;

    /* check header magic */
    if (read_32bitBE(0x0,streamFile) != 0x47454e48) goto fail;

    /* check channel count (needed for ADP/DTK check) */
    channel_count = read_32bitLE(0x4,streamFile);
    if (channel_count < 1) goto fail;

    /* check format */
    /* 0 = PSX ADPCM */
    /* 1 = XBOX IMA ADPCM */
    /* 2 = NGC ADP/DTK ADPCM */
    /* 3 = 16bit big endian PCM */
    /* 4 = 16bit little endian PCM */
    /* 5 = 8bit PCM */
    /* 6 = SDX2 */
    /* 7 = DVI IMA */
    /* 8 = MPEG-1 Layer III, possibly also the MPEG-2 and 2.5 extensions */
    /* 9 = IMA */
    /* 10 = AICA ADPCM */
    /* 11 = MS ADPCM */
    /* 12 = NGC DSP */
    /* 13 = 8bit unsingned PCM */
	/* 14 = PSX ADPCM (bad flagged) */
    /* ... others to come */
    switch (read_32bitLE(0x18,streamFile)) {
        case 0:
            coding = coding_PSX;
            break;
        case 1:
            coding = coding_XBOX;
            break;
        case 2:
            coding = coding_NGC_DTK;
            if (channel_count != 2) goto fail;
            break;
        case 3:
            coding = coding_PCM16BE;
            break;
        case 4:
            coding = coding_PCM16LE;
            break;
        case 5:
            coding = coding_PCM8;
            break;
        case 6:
            coding = coding_SDX2;
            break;
        case 7:
            coding = coding_DVI_IMA;
            break;
#ifdef VGM_USE_MPEG
        case 8:
            /* we say MPEG-1 L3 here, but later find out exactly which */
            coding = coding_MPEG1_L3;
            break;
#endif
        case 9:
            coding = coding_IMA;
            break;
        case 10:
            coding = coding_AICA;
            break;
        case 11:
            coding = coding_MSADPCM;
            break;
        case 12:
            coding = coding_NGC_DSP;
            break;
		case 13:
            coding = coding_PCM8_U_int;
            break;
		case 14:
            coding = coding_PSX_badflags;
            break;
        default:
            goto fail;
    }

    start_offset = read_32bitLE(0x1C,streamFile);
    header_size = read_32bitLE(0x20,streamFile);

    /* HACK to support old genh */
    if (header_size == 0) {
        start_offset = 0x800;
        header_size = 0x800;
    }

    /* check for audio data start past header end */
    if (header_size > start_offset) goto fail;

    interleave = read_32bitLE(0x8,streamFile);
    sample_rate = read_32bitLE(0xc,streamFile);
    loop_start = read_32bitLE(0x10,streamFile);
    loop_end = read_32bitLE(0x14,streamFile);
	
	coef[0] = read_32bitLE(0x24,streamFile);
	coef[1] = read_32bitLE(0x28,streamFile);
	dsp_interleave_type = read_32bitLE(0x2C,streamFile);

    //if (coding == coding_XBOX && channel_count != 2) goto fail;

    /* build the VGMSTREAM */
    vgmstream = allocate_vgmstream(channel_count,(loop_start!=-1));
    if (!vgmstream) goto fail;

    /* fill in the vital information */

    vgmstream->channels = channel_count;
    vgmstream->sample_rate = sample_rate;
    vgmstream->num_samples = loop_end;
    vgmstream->loop_start_sample = loop_start;
    vgmstream->loop_end_sample = loop_end;
    vgmstream->loop_flag = (loop_start != -1);

    switch (coding) {
        case coding_PCM8_U_int:
			vgmstream->layout_type=layout_none;
			break;
		case coding_PCM16LE:
        case coding_PCM16BE:
        case coding_PCM8:
        case coding_SDX2:
        case coding_PSX:
		case coding_PSX_badflags:
        case coding_DVI_IMA:
        case coding_IMA:
        case coding_AICA:
            vgmstream->interleave_block_size = interleave;
            if (channel_count > 1)
            {
                if (coding == coding_SDX2) {
                    coding = coding_SDX2_int;
                    vgmstream->coding_type = coding_SDX2_int;
                }
				if(vgmstream->interleave_block_size==0xffffffff)
					vgmstream->layout_type=layout_none;
				else {
					vgmstream->layout_type = layout_interleave;
					if(coding==coding_DVI_IMA)
						coding=coding_INT_DVI_IMA;
					if(coding==coding_IMA)
						coding=coding_INT_IMA;
				}
            } else {
                vgmstream->layout_type = layout_none;
            }
            break;
        case coding_MSADPCM:
            if (channel_count != 2) goto fail;
            vgmstream->interleave_block_size = interleave;
            vgmstream->layout_type = layout_none;
            break;
        case coding_XBOX:
            vgmstream->layout_type = layout_none;
            break;
        case coding_NGC_DTK:
            vgmstream->layout_type = layout_dtk_interleave;
            break;
        case coding_NGC_DSP:
        	if (dsp_interleave_type == 0) {
				vgmstream->layout_type = layout_interleave;
            	vgmstream->interleave_block_size = interleave;
			} else if (dsp_interleave_type == 1) {
        		vgmstream->layout_type = layout_interleave_byte;
            	vgmstream->interleave_block_size = interleave;
			} else if (dsp_interleave_type == 2) {
            	vgmstream->layout_type = layout_none;
			}
			break;
            
#ifdef VGM_USE_MPEG
        case coding_MPEG1_L3:
            vgmstream->layout_type = layout_mpeg;
            break;
#endif
    }
    
	vgmstream->coding_type = coding;
	vgmstream->meta_type = meta_GENH;
    
    /* open the file for reading by each channel */
    {
        int i;
		int j;

        STREAMFILE * chstreamfile = NULL;

        for (i=0;i<channel_count;i++) {
            off_t chstart_offset = start_offset;

            switch (coding) {
                case coding_PSX:
				case coding_PSX_badflags:
                case coding_PCM16BE:
                case coding_PCM16LE:
                case coding_SDX2:
                case coding_SDX2_int:
                case coding_DVI_IMA:
                case coding_IMA:
                case coding_PCM8:
                case coding_PCM8_U_int:
                case coding_AICA:
				case coding_INT_DVI_IMA:
				case coding_INT_IMA:
                    if (vgmstream->layout_type == layout_interleave) {
                        if (interleave >= 512) {
                            chstreamfile =
                                streamFile->open(streamFile,filename,interleave);
                        } else {
                            if (!chstreamfile)
                                chstreamfile =
                                    streamFile->open(streamFile,filename,STREAMFILE_DEFAULT_BUFFER_SIZE);
                        }
                        chstart_offset =
                            start_offset+vgmstream->interleave_block_size*i;
                    } else {
                        chstreamfile =
                            streamFile->open(streamFile,filename,
                                    STREAMFILE_DEFAULT_BUFFER_SIZE);
                    }
                    break;
                case coding_XBOX:
                case coding_MSADPCM:
                    /* xbox's "interleave" is a lie, all channels start at same
                     * offset */
                    chstreamfile =
                        streamFile->open(streamFile,filename,
                                STREAMFILE_DEFAULT_BUFFER_SIZE);
                    break;
                case coding_NGC_DTK:
                    if (!chstreamfile) 
                        chstreamfile =
                            streamFile->open(streamFile,filename,32*0x400);
                    break;
                case coding_NGC_DSP:
                    if (!chstreamfile) 
                        chstreamfile =
                            streamFile->open(streamFile,filename,STREAMFILE_DEFAULT_BUFFER_SIZE);

					for (j=0;j<16;j++) 
            			vgmstream->ch[i].adpcm_coef[j] = read_16bitBE(coef[i]+j*2,streamFile);
							chstart_offset =start_offset+vgmstream->interleave_block_size*i;
					break;

#ifdef VGM_USE_MPEG
                case coding_MPEG1_L3:
                    if (!chstreamfile)
                        chstreamfile =
                            streamFile->open(streamFile,filename,MPEG_BUFFER_SIZE);
                    break;
#endif
            }

            if (!chstreamfile) goto fail;

            vgmstream->ch[i].streamfile = chstreamfile;

            vgmstream->ch[i].channel_start_offset=
                vgmstream->ch[i].offset=chstart_offset;
        }
    }

#ifdef VGM_USE_MPEG
    if (coding == coding_MPEG1_L3) {
        int rc;
        off_t read_offset;
        data = calloc(1,sizeof(mpeg_codec_data));
        if (!data) goto mpeg_fail;

        data->m = mpg123_new(NULL,&rc);
        if (rc==MPG123_NOT_INITIALIZED) {
            if (mpg123_init()!=MPG123_OK) goto mpeg_fail;
            data->m = mpg123_new(NULL,&rc);
            if (rc!=MPG123_OK) goto mpeg_fail;
        } else if (rc!=MPG123_OK) {
            goto mpeg_fail;
        }

        mpg123_param(data->m,MPG123_REMOVE_FLAGS,MPG123_GAPLESS,0.0);

        if (mpg123_open_feed(data->m)!=MPG123_OK) {
            goto mpeg_fail;
        }

        /* check format */
        read_offset=0;
        do {
            size_t bytes_done;
            if (read_streamfile(data->buffer, start_offset+read_offset,
                    MPEG_BUFFER_SIZE,vgmstream->ch[0].streamfile) !=
                    MPEG_BUFFER_SIZE) goto mpeg_fail;
            read_offset+=1;
            rc = mpg123_decode(data->m,data->buffer,MPEG_BUFFER_SIZE,
                    NULL,0,&bytes_done);
            if (rc != MPG123_OK && rc != MPG123_NEW_FORMAT &&
                    rc != MPG123_NEED_MORE) goto mpeg_fail;
        } while (rc != MPG123_NEW_FORMAT);

        {
            long rate;
            int channels,encoding;
            struct mpg123_frameinfo mi;
            rc = mpg123_getformat(data->m,&rate,&channels,&encoding);
            if (rc != MPG123_OK) goto mpeg_fail;
            if (rate != vgmstream->sample_rate ||
                    channels != vgmstream->channels ||
                    encoding != MPG123_ENC_SIGNED_16) goto mpeg_fail;
            mpg123_info(data->m,&mi);
            if (mi.rate != vgmstream->sample_rate) goto mpeg_fail;
            if (mi.version == MPG123_1_0 && mi.layer == 1)
                vgmstream->coding_type = coding_MPEG1_L1;
            else if (mi.version == MPG123_1_0 && mi.layer == 2)
                vgmstream->coding_type = coding_MPEG1_L2;
            else if (mi.version == MPG123_1_0 && mi.layer == 3)
                vgmstream->coding_type = coding_MPEG1_L3;
            else if (mi.version == MPG123_2_0 && mi.layer == 1)
                vgmstream->coding_type = coding_MPEG2_L1;
            else if (mi.version == MPG123_2_0 && mi.layer == 2)
                vgmstream->coding_type = coding_MPEG2_L2;
            else if (mi.version == MPG123_2_0 && mi.layer == 3)
                vgmstream->coding_type = coding_MPEG2_L3;
            else if (mi.version == MPG123_2_5 && mi.layer == 1)
                vgmstream->coding_type = coding_MPEG25_L1;
            else if (mi.version == MPG123_2_5 && mi.layer == 2)
                vgmstream->coding_type = coding_MPEG25_L2;
            else if (mi.version == MPG123_2_5 && mi.layer == 3)
                vgmstream->coding_type = coding_MPEG25_L3;
            else goto mpeg_fail;
        }

        /* reinit, to ignore the reading we've done so far */
        mpg123_open_feed(data->m);

        vgmstream->codec_data = data;
    }
#endif

    return vgmstream;

    /* clean up anything we may have opened */
#ifdef VGM_USE_MPEG
mpeg_fail:
    if (data) {
        mpg123_delete(data->m);
        free(data);
    }
#endif
fail:
    if (vgmstream) close_vgmstream(vgmstream);
    return NULL;
}
Esempio n. 17
0
static audio_result_t init(audio_worker_t* worker, const char* file_or_url, el_bool file)
{
  static int mp3_initialized = 0;
  static int mp3_error = 0;
  
  if (!mp3_initialized) {
    mp3_initialized = 1;
    if (mpg123_init() != MPG123_OK) {
      mp3_error = 1;
    } else {
      atexit(mpg123_exit);
    }
  }

  if (mp3_error) {
    return AUDIO_CANNOT_INITIALIZE;
  }
  
  mp3_t* mp3=(mp3_t*) mc_malloc(sizeof(mp3_t));
  
  worker->can_seek = can_seek;
  worker->play = play;
  worker->pause = mp3_pause;
  worker->seek = seek;
  worker->guard = guard;
  worker->destroy = destroy;
  worker->length_in_ms = length_in_ms;
  worker->load_file = load_file;
  worker->load_url = load_url;
  worker->set_volume = set_volume;
  worker->worker_data = (void*) mp3;
    
  int error;
  mp3->handle = mpg123_new(NULL, &error);
  mp3->buffer_size = mpg123_outblock(mp3->handle);
  mp3->buffer = mc_malloc(mp3->buffer_size * sizeof(char));
  
  mpg123_volume(mp3->handle, 1.0);
  
  mp3->client_notification = worker->fifo;
  mp3->player_control = audio_event_fifo_new();
  
  // http streams
  mp3->stream_fifo = mp3_stream_fifo_new();
  mp3->continue_streaming = el_true;
  mp3->current_block = NULL;
  //sem_init(&mp3->stream_ready, 0, 0);
  mp3->stream_ready = psem_new(0);
  mp3->streaming = el_false;
  
  // etc.  
  mp3->is_open = el_false;
  mp3->length  = -1;
  //sem_init(&mp3->length_set, 0, 0);
  mp3->length_set = psem_new(0);
  
  mp3->ao_handle = aodev_new();

  if (file) {
    mp3->can_seek = el_true;
    mp3->is_file = el_true;
    mp3->file_or_url = mc_strdup(file_or_url);
    post_event(mp3->player_control, INTERNAL_CMD_LOAD_FILE, -1); 
  } else { // URL
    mp3->can_seek = el_false;
    mp3->is_file = el_true;   // we check this later 
    mp3->file_or_url = mc_strdup(file_or_url);
    post_event(mp3->player_control, INTERNAL_CMD_LOAD_URL, -1);
  }
  
  int thread_id = pthread_create(&mp3->player_thread, NULL, player_thread, mp3);

  // wait until fully loaded (length is set)
  psem_wait(mp3->length_set);
  
  log_debug("INIT OK");

  return AUDIO_OK;
}
Esempio n. 18
0
// Open Media file and return elapsed time in millseconds
int Waveform::OpenfileMediaFile(const wxString &filename, wxString& error)
{
    mpg123_handle *mh = NULL;
    int err;
    size_t buffer_size;
    int channels, encoding;
    long rate;

    err = mpg123_init();
    if(err != MPG123_OK || (mh = mpg123_new(NULL, &err)) == NULL)
    {
        error = wxString::Format("Basic setup goes wrong: %s", mpg123_plain_strerror(err));
        if (mh != NULL) {
            cleanup(mh);
        }
        return -1;
    }

    /* open the file and get the decoding format */
    if( mpg123_open(mh, filename.c_str()) != MPG123_OK ||
        mpg123_getformat(mh, &rate, &channels, &encoding) != MPG123_OK )
    {
        error = wxString::Format("Trouble with mpg123: %s", mpg123_strerror(mh));
        cleanup(mh);
        return -1;
    }

    if( encoding != MPG123_ENC_SIGNED_16 )
    {
        error = "Encoding unsupported.  Must be signed 16 bit.";
        cleanup(mh);
        return -2;
    }

    /* set the output format and open the output device */
    m_bits = mpg123_encsize(encoding);
    m_rate = rate;
    m_channels = channels;
    /* Get Track Size */
    mMediaTrackSize = GetTrackSize(mh,m_bits,m_channels);
    buffer_size = mpg123_outblock(mh);
    int size = (mMediaTrackSize+buffer_size)*m_bits*m_channels;
    char * trackData = (char*)malloc(size);
    LoadTrackData(mh,trackData, size);
    // Split data into left and right and normalize -1 to 1
    m_left_data = (float*)malloc(sizeof(float)*mMediaTrackSize);
    if( m_channels == 2 )
    {
        m_right_data = (float*)malloc(sizeof(float)*mMediaTrackSize);
        SplitTrackDataAndNormalize((signed short*)trackData,mMediaTrackSize,m_left_data,m_right_data);
    }
    else if( m_channels == 1 )
    {
        NormalizeMonoTrackData((signed short*)trackData,mMediaTrackSize,m_left_data);
    }
    else
    {
        error = "More than 2 audio channels is not supported yet.";
    }
    views.clear();
    float samplesPerLine = GetSamplesPerLineFromZoomLevel(mZoomLevel);
    WaveView wv(mZoomLevel,samplesPerLine,m_left_data,mMediaTrackSize);
    views.push_back(wv);
    mCurrentWaveView = 0;

    mpg123_close(mh);
    mpg123_delete(mh);
    mpg123_exit();
    free(trackData);
    float seconds = (float)mMediaTrackSize * ((float)1/(float)rate);
    mAudioIsLoaded = true;
    return (int)(seconds * (float)1000);
}
Esempio n. 19
0
float* readaudio_mp3(const char *filename,long *sr, unsigned int *buflen,\
		     const float nbsecs, AudioMetaData *mdata, int *error){
  mpg123_handle *m;
  int ret = 0;
  mpg123_id3v1 *v1 = NULL;
  mpg123_id3v2 *v2 = NULL;

  if ((ret = mpg123_init()) != MPG123_OK || ((m = mpg123_new(NULL,&ret)) == NULL)|| \
      (ret = mpg123_open(m, filename)) != MPG123_OK){
    *error = (ret != 0) ? ret : PHERR_MP3NEW;
    return NULL;
  }

  /*turn off logging */
  mpg123_param(m, MPG123_ADD_FLAGS, MPG123_QUIET, 0);

  off_t totalsamples;
  
  mpg123_scan(m);
  totalsamples = mpg123_length(m);
  if (totalsamples <= 0){
    *error = PHERR_NOSAMPLES;
    return NULL;
  }
  
  int meta = mpg123_meta_check(m);

  if (mdata)init_mdata(mdata);
  if (mdata && (meta & MPG123_ID3) && mpg123_id3(m, &v1, &v2) == MPG123_OK){
    if (v2){
      get_v2_data(v2, mdata);
    } else if (v1){
      get_v1_data(v1, mdata);
    } 
  }

  int channels, encoding;
    
  if (mpg123_getformat(m, sr, &channels, &encoding) != MPG123_OK){
    *error = PHERR_NOFORMAT;
    return NULL;
  }
  
  mpg123_format_none(m);
  mpg123_format(m, *sr, channels, encoding);
  if (channels <= 0 || encoding <= 0){
    *error = PHERR_NOENCODING;
    return NULL;
  }


  size_t decbuflen = mpg123_outblock(m);
  if (decbuflen == 0){
    /* take a guess */ 
    decbuflen = 1<<16;
  }

  unsigned char *decbuf = (unsigned char*)malloc(decbuflen);  
  if (decbuf == NULL){
    *error = PHERR_MEMALLOC;
    return NULL;
  }

  unsigned int nbsamples = (nbsecs <= 0) ? totalsamples : nbsecs*(*sr);
  nbsamples = (nbsamples <= totalsamples) ? nbsamples : totalsamples;

  size_t i, j, index = 0, done;


  float *buffer = (float*)malloc(nbsamples*sizeof(float));
  if (buffer == NULL){
    *error = PHERR_MEMALLOC;
    return NULL;
  }
  *buflen = nbsamples;

  do {
    ret = mpg123_read(m, decbuf, decbuflen, &done);
    switch (encoding) {
    case MPG123_ENC_SIGNED_16 :
      for (i = 0; i < done/sizeof(short); i+=channels){
	buffer[index] = 0.0f;
	for (j = 0; j < channels ; j++){
	  buffer[index] += (float)(((short*)decbuf)[i+j])/(float)SHRT_MAX;
	}
	buffer[index++] /= channels;
	if (index >= nbsamples) break;
      }
      break;
    case MPG123_ENC_SIGNED_8:
      for (i = 0; i < done/sizeof(char); i+=channels){
	buffer[index] = 0.0f;
	for (j = 0; j < channels ; j++){
	  buffer[index] += (float)(((char*)decbuf)[i+j])/(float)SCHAR_MAX;
	}
	buffer[index++] /= channels;
	if (index >= nbsamples) break;
      }
      break;
    case MPG123_ENC_FLOAT_32:
      for (i = 0; i < done/sizeof(float); i+=channels){
	buffer[index] = 0.0f;
	for (j = 0; j < channels; j++){
	  buffer[index] += ((float*)decbuf)[i+j];
	}
	buffer[index++] /= channels;
	if (index >= nbsamples) break;
      }
      break;
    default:
	done = 0;
    }

  } while (ret == MPG123_OK && index < nbsamples);

  if (ret != MPG123_DONE && ret != MPG123_OK && index < nbsamples){
    free(buffer);
    *error = ret;
    buffer=NULL;
  }
  free(decbuf);
  mpg123_close(m);
  mpg123_delete(m);
  mpg123_exit();

  return buffer;
}
Esempio n. 20
0
int _tmain(int argc, TCHAR **argv)
{
	unsigned char buf[INBUFF];
	unsigned char *audio;
	FILE *in;
	mpg123_handle *m;
	int ret, state;
	size_t inc, outc;
	off_t len, num;
	size_t bytes;
	off_t inoffset;
	size_t nrates;
	const long *rates;
	size_t i;
	inc = outc = 0;
	nrates = 0;
	rates = NULL;

	if(argc < 3)
	{
		fprintf(stderr,"Please supply in and out filenames\n");
		return -1;
	}

	mpg123_init();

	m = mpg123_new(NULL, &ret);
	if(m == NULL)
	{
		fprintf(stderr,"Unable to create mpg123 handle: %s\n", mpg123_plain_strerror(ret));
		return -1;
	}

	mpg123_param(m, MPG123_VERBOSE, 4, 0);

	ret = mpg123_param(m, MPG123_FLAGS, MPG123_FUZZY | MPG123_SEEKBUFFER | MPG123_GAPLESS, 0);
	if(ret != MPG123_OK)
	{
		fprintf(stderr,"Unable to set library options: %s\n", mpg123_plain_strerror(ret));
		return -1;
	}

	// Let the seek index auto-grow and contain an entry for every frame
	ret = mpg123_param(m, MPG123_INDEX_SIZE, -1, 0);
	if(ret != MPG123_OK)
	{
		fprintf(stderr,"Unable to set index size: %s\n", mpg123_plain_strerror(ret));
		return -1;
	}

	// Use float output formats only
	ret = mpg123_format_none(m);
	if(ret != MPG123_OK)
	{
		fprintf(stderr,"Unable to disable all output formats: %s\n", mpg123_plain_strerror(ret));
		return -1;
	}
	
	mpg123_rates(&rates, &nrates);
	for(i=0; i<nrates; i++)
	{
		ret = mpg123_format(m, rates[i], MPG123_MONO | MPG123_STEREO,  MPG123_ENC_FLOAT_32);
		if(ret != MPG123_OK)
		{
			fprintf(stderr,"Unable to set float output formats: %s\n", mpg123_plain_strerror(ret));
			return -1;
		}
	}

	ret = mpg123_open_feed(m);
	if(ret != MPG123_OK)
	{
		fprintf(stderr,"Unable open feed: %s\n", mpg123_plain_strerror(ret));
		return -1;
	}

	in = _tfopen(argv[1], __T("rb"));
	if(in == NULL)
	{
		_ftprintf(stderr,__T("Unable to open input file %s\n"), argv[1]);
		return -1;
	}
	
	out = _tfopen(argv[2], __T("wb"));
	if(out == NULL)
	{
		_ftprintf(stderr,__T("Unable to open output file %s\n"), argv[2]);
		return -1;
	}
	
	while(ret = mpg123_feedseek(m, 95000, SEEK_SET, &inoffset) == MPG123_NEED_MORE)
	{
		len = fread(buf, sizeof(unsigned char), INBUFF, in);
		if(len <= 0)
			break;
		inc += len;

		state = mpg123_feed(m, buf, len);
		if(state == MPG123_ERR)
		{
			fprintf(stderr, "Error: %s", mpg123_strerror(m));
			return -1; 
		}
	}
	
	fseek(in, inoffset, SEEK_SET);
	
	while(1)
	{
		len = fread(buf, sizeof(unsigned char), INBUFF, in);
		if(len <= 0)
			break;
		inc += len;
		ret = mpg123_feed(m, buf, len);

		while(ret != MPG123_ERR && ret != MPG123_NEED_MORE)
		{
			ret = mpg123_decode_frame(m, &num, &audio, &bytes);
			if(ret == MPG123_NEW_FORMAT)
			{
				mpg123_getformat(m, &rate, &channels, &enc);
				initwavformat();
				initwav();
				fprintf(stderr, "New format: %li Hz, %i channels, encoding value %i\n", rate, channels, enc);
			}
			fwrite(audio, sizeof(unsigned char), bytes, out);
			outc += bytes;
		}

		if(ret == MPG123_ERR)
		{
			fprintf(stderr, "Error: %s", mpg123_strerror(m));
			break; 
		}
	}

	fprintf(stderr, "Finished read %lu, decoded %lu\n", (unsigned long)inc, (unsigned long)outc);

	closewav();
	fclose(out);
	fclose(in);
	mpg123_delete(m);
	mpg123_exit();
	return 0;
}
Esempio n. 21
0
int _tmain(int argc, _TCHAR* argv[])
{
    mpg123_handle *m;
    int i;
    if (argc < 3)
    {
        fprintf(stderr, "\nI will give you the estimated and exact sample lengths of MPEG audio files.\n");
        fprintf(stderr, "\nUsage: %s <mpeg audio file list>\n\n", argv[0]);
        return -1;
    }
    mpg123_init();
    m = mpg123_new(NULL, NULL);
    mpg123_param(m, MPG123_RESYNC_LIMIT, -1, 0); /* New in library version 0.0.1 . */

    off_t a, b;
    if (MPG123_OK != mpg123_open_feed(m)) {
        fprintf(stderr, "open feed failed");
        return -1;
    }

    FILE* file = _tfopen(argv[1], TEXT("rb"));
    if (!file) {
        fprintf(stderr, "open file failed");
        return -1;
    }

    _stat64i32 st = { 0 };
    _tstat(argv[1], &st);
    if (st.st_size <= 0) {
        fprintf(stderr, "file size is zero");
        return -1;
    }
    char* pDataBuf = new char[st.st_size];
    memset(pDataBuf, 0, st.st_size);
    if (st.st_size != fread(pDataBuf, 1, st.st_size, file)) {
        fprintf(stderr, "read file error");
        return -1;
    }
    if (MPG123_OK != mpg123_feed(m, (const unsigned char*)pDataBuf, st.st_size)) {
        fprintf(stderr, "feed failed");
        return -1;
    }

    // channels;
    bool bSaved = false;
    size_t nDone = 0;
    int res = mpg123_decode(m, NULL, 0, NULL, 0, &nDone);
    if (res == MPG123_NEW_FORMAT) {
        long rate = 0;
        int channels = 0;
        int enc = 0;
        mpg123_getformat(m, &rate, &channels, &enc);

        if (MPG123_ENC_SIGNED_16 == enc) {
            int nSamples = mpg123_length(m);
            int nBufCount = nSamples * channels;
            int nBufSize = nBufCount * sizeof(short);
            short* pBuf = new short[nBufCount];

            res = mpg123_decode(m, NULL, 0, (unsigned char*)pBuf, nBufSize, &nDone);
            if (res == MPG123_OK) {
                KWavFile file;
                file.Init(pBuf, nDone, rate, "");
                file.Save(CT2A(argv[2]));
                bSaved = true;
            }
            if (pBuf) {
                delete[] pBuf;
                pBuf = NULL;
            }
        }
    }


    mpg123_tclose(m);
    mpg123_delete(m);
    mpg123_exit();
    return 0;
}
Esempio n. 22
0
PyMODINIT_FUNC
initdecoders(void)
{
    PyObject* m;

    decoders_FlacDecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_FlacDecoderType) < 0)
        return;

    decoders_OggFlacDecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_OggFlacDecoderType) < 0)
        return;

    decoders_SHNDecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_SHNDecoderType) < 0)
        return;

    decoders_ALACDecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_ALACDecoderType) < 0)
        return;

    decoders_WavPackDecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_WavPackDecoderType) < 0)
        return;

    #ifdef HAS_VORBIS
    decoders_VorbisDecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_VorbisDecoderType) < 0)
        return;
    #endif

    #ifdef HAS_MP3
    decoders_MP3DecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_MP3DecoderType) < 0)
        return;
    #endif

    #ifdef HAS_OPUS
    decoders_OpusDecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_OpusDecoderType) < 0)
        return;
    #endif

    decoders_TTADecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_TTADecoderType) < 0)
        return;

    decoders_CPPMDecoderType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_CPPMDecoderType) < 0)
        return;

    decoders_DVDA_Title_Type.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_DVDA_Title_Type) < 0)
        return;

    decoders_Sine_Mono_Type.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_Sine_Mono_Type) < 0)
        return;

    decoders_Sine_Stereo_Type.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_Sine_Stereo_Type) < 0)
        return;

    decoders_Sine_Simple_Type.tp_new = PyType_GenericNew;
    if (PyType_Ready(&decoders_Sine_Simple_Type) < 0)
        return;

    m = Py_InitModule3("decoders", module_methods,
                       "Low-level audio format decoders");

    Py_INCREF(&decoders_FlacDecoderType);
    PyModule_AddObject(m, "FlacDecoder",
                       (PyObject *)&decoders_FlacDecoderType);

    Py_INCREF(&decoders_OggFlacDecoderType);
    PyModule_AddObject(m, "OggFlacDecoder",
                       (PyObject *)&decoders_OggFlacDecoderType);

    Py_INCREF(&decoders_SHNDecoderType);
    PyModule_AddObject(m, "SHNDecoder",
                       (PyObject *)&decoders_SHNDecoderType);

    Py_INCREF(&decoders_ALACDecoderType);
    PyModule_AddObject(m, "ALACDecoder",
                       (PyObject *)&decoders_ALACDecoderType);

    Py_INCREF(&decoders_WavPackDecoderType);
    PyModule_AddObject(m, "WavPackDecoder",
                       (PyObject *)&decoders_WavPackDecoderType);

    #ifdef HAS_VORBIS
    Py_INCREF(&decoders_VorbisDecoderType);
    PyModule_AddObject(m, "VorbisDecoder",
                       (PyObject *)&decoders_VorbisDecoderType);
    #endif

    #ifdef HAS_MP3
    Py_INCREF(&decoders_MP3DecoderType);
    PyModule_AddObject(m, "MP3Decoder",
                       (PyObject *)&decoders_MP3DecoderType);
    #endif

    #ifdef HAS_OPUS
    Py_INCREF(&decoders_OpusDecoderType);
    PyModule_AddObject(m, "OpusDecoder",
                       (PyObject *)&decoders_OpusDecoderType);
    #endif

    Py_INCREF(&decoders_TTADecoderType);
    PyModule_AddObject(m, "TTADecoder",
                       (PyObject *)&decoders_TTADecoderType);

    Py_INCREF(&decoders_CPPMDecoderType);
    PyModule_AddObject(m, "CPPMDecoder",
                       (PyObject *)&decoders_CPPMDecoderType);

    Py_INCREF(&decoders_DVDA_Title_Type);
    PyModule_AddObject(m, "DVDA_Title",
                       (PyObject *)&decoders_DVDA_Title_Type);

    Py_INCREF(&decoders_Sine_Mono_Type);
    PyModule_AddObject(m, "Sine_Mono",
                       (PyObject *)&decoders_Sine_Mono_Type);

    Py_INCREF(&decoders_Sine_Stereo_Type);
    PyModule_AddObject(m, "Sine_Stereo",
                       (PyObject *)&decoders_Sine_Stereo_Type);

    Py_INCREF(&decoders_Sine_Simple_Type);
    PyModule_AddObject(m, "Sine_Simple",
                       (PyObject *)&decoders_Sine_Simple_Type);

    #ifdef HAS_MP3
    /*this initializes the library's static decoding tables

      although the library has an mpg123_exit() function
      to be called at shutdown-time, it's currenly a noop
      so we won't worry about it*/
    mpg123_init();
    #endif
}
Esempio n. 23
0
/* This initializes libmpg123 and prepares the handle, including funky
 * parameters. */
static int init(struct dec_audio *da, const char *decoder)
{
    int err;
    struct ad_mpg123_context *con;
    /* Assumption: You always call preinit + init + uninit, on every file.
     * But you stop at preinit in case it fails.
     * If that is not true, one must ensure not to call mpg123_init / exit
     * twice in a row. */
    if (mpg123_init() != MPG123_OK)
        return 0;

    da->priv = talloc_zero(NULL, struct ad_mpg123_context);
    con = da->priv;
    /* Auto-choice of optimized decoder (first argument NULL). */
    con->handle = mpg123_new(NULL, &err);
    if (!con->handle)
        goto bad_end;

    /* Basic settings.
     * Don't spill messages, enable better resync with non-seekable streams.
     * Give both flags individually without error checking to keep going with
     * old libmpg123. Generally, it is not fatal if the flags are not
     * honored */
    mpg123_param(con->handle, MPG123_ADD_FLAGS, MPG123_QUIET, 0.0);
    /* Do not bail out on malformed streams at all.
     * MPlayer does not handle a decoder throwing the towel on crappy input. */
    mpg123_param(con->handle, MPG123_RESYNC_LIMIT, -1, 0.0);

    /* Open decisions: Configure libmpg123 to force encoding (or stay open about
     * library builds that support only float or int32 output), (de)configure
     * gapless decoding (won't work with seeking in MPlayer, though).
     * Don't forget to eventually enable ReplayGain/RVA support, too.
     * Let's try to run with the default for now. */

    /* That would produce floating point output.
     * You can get 32 and 24 bit ints, even 8 bit via format matrix.
     * If wanting a specific encoding here, configure format matrix and
     * make sure it is in set_format(). */
    /* mpg123_param(con->handle, MPG123_ADD_FLAGS, MPG123_FORCE_FLOAT, 0.); */

    /* Example for RVA choice (available since libmpg123 1.0.0):
    mpg123_param(con->handle, MPG123_RVA, MPG123_RVA_MIX, 0.0) */

    /* Prevent funky automatic resampling.
     * This way, we can be sure that one frame will never produce
     * more than 1152 stereo samples.
     * Background:
     * Going to decode directly to the output buffer. It is important to have
     * MPG123_AUTO_RESAMPLE disabled for the buffer size being an all-time
     * limit.
     * We need at least 1152 samples. dec_audio.c normally guarantees this. */
    mpg123_param(con->handle, MPG123_REMOVE_FLAGS, MPG123_AUTO_RESAMPLE, 0.);

    err = mpg123_open_feed(con->handle);
    if (err != MPG123_OK)
        goto bad_end;

    return 1;

  bad_end:
    if (!con->handle) {
        MP_ERR(da, "mpg123 preinit error: %s\n", mpg123_plain_strerror(err));
    } else {
        MP_ERR(da, "mpg123 preinit error: %s\n", mpg123_strerror(con->handle));
    }

    uninit(da);
    return 0;
}
Esempio n. 24
0
static void decoder_library_init()
    {
    if((decoder_library_ok = (mpg123_init() == MPG123_OK)))
        atexit(mpg123_exit);
    }
Esempio n. 25
0
JNIEXPORT jint JNICALL Java_com_axelby_podax_player_MPG123_init
	(JNIEnv *env, jclass c)
{
	return mpg123_init();
}