예제 #1
0
/* 0 on error */
static int nas_createFlow(out123_handle *ao)
{
    AuDeviceID      device = AuNone;
    AuElement       elements[2];
    unsigned char   format;
    AuUint32        buf_samples;
    int             i;
 

    switch(ao->format) {
    case MPG123_ENC_SIGNED_16:
    default:
		if (((char) *(short *)"x")=='x') /* ugly, but painless */
			format = AuFormatLinearSigned16LSB; /* little endian */
		else
		format = AuFormatLinearSigned16MSB; /* big endian */
        break;
    case MPG123_ENC_UNSIGNED_8:
        format = AuFormatLinearUnsigned8;
        break;
    case MPG123_ENC_SIGNED_8:
        format = AuFormatLinearSigned8;
        break;
    case MPG123_ENC_ULAW_8:
        format = AuFormatULAW8;
        break;
    }
    /* look for an output device */
    for (i = 0; i < AuServerNumDevices(info.aud); i++)
       if (((AuDeviceKind(AuServerDevice(info.aud, i)) ==
              AuComponentKindPhysicalOutput) &&
             AuDeviceNumTracks(AuServerDevice(info.aud, i))
             ==  ao->channels )) {
            device = AuDeviceIdentifier(AuServerDevice(info.aud, i));
            break;
       }
    if (device == AuNone) {
       if(!AOQUIET)
         error1( "Couldn't find an output device providing %d channels."
               , ao->channels );
       return 0;
    }

    /* set gain */
    if(ao->gain >= 0) {
        info.da = AuGetDeviceAttributes(info.aud, device, NULL);
        if ((info.da)!=NULL) {
            AuDeviceGain(info.da) = AuFixedPointFromSum(ao->gain, 0);
            AuSetDeviceAttributes(info.aud, AuDeviceIdentifier(info.da),
                                  AuCompDeviceGainMask, info.da, NULL);
        }
        else if(!AOQUIET)
            error("audio/gain: setable Volume/PCM-Level not supported");
    }
    
    if (!(info.flow = AuCreateFlow(info.aud, NULL))) {
        if(!AOQUIET)
          error("Couldn't create flow");
        return 0;
    }

    buf_samples = ao->rate * NAS_SOUND_PORT_DURATION;

    AuMakeElementImportClient(&elements[0],        /* element */
                              (unsigned short) ao->rate,
                                                   /* rate */
                              format,              /* format */
                              ao->channels,        /* channels */
                              AuTrue,              /* ??? */
                              buf_samples,         /* max samples */
                              (AuUint32) (buf_samples / 100
                                  * NAS_SOUND_LOW_WATER_MARK),
                                                   /* low water mark */
                              0,                   /* num actions */
                              NULL);               /* actions */
    AuMakeElementExportDevice(&elements[1],        /* element */
                              0,                   /* input */
                              device,              /* device */
                              (unsigned short) ao->rate,
                                                   /* rate */
                              AuUnlimitedSamples,  /* num samples */
                              0,                   /* num actions */
                              NULL);               /* actions */
    AuSetElements(info.aud,                        /* Au server */
                  info.flow,                       /* flow ID */
                  AuTrue,                          /* clocked */
                  2,                               /* num elements */
                  elements,                        /* elements */
                  NULL);                           /* return status */

    AuRegisterEventHandler(info.aud,               /* Au server */
                           AuEventHandlerIDMask,   /* value mask */
                           0,                      /* type */
                           info.flow,              /* id */
                           nas_eventHandler,       /* callback */
                           (AuPointer) &info);     /* data */

    info.buf_size = buf_samples * ao->channels * AuSizeofFormat(format);
    info.buf = (char *) malloc(info.buf_size);
    if (info.buf == NULL) {
        if(!AOQUIET)
          error1("Unable to allocate input/output buffer of size %ld",
            (long)info.buf_size);
        return 0;
    }
    info.buf_cnt = 0;
    info.data_sent = AuFalse;
    info.finished = AuFalse;
    
    AuStartFlow(info.aud,                          /* Au server */
                info.flow,                         /* id */
                NULL);                             /* status */
    return 1; /* success */
}
예제 #2
0
파일: mpg123.c 프로젝트: flatmax/mpg123
/* return 1 on success, 0 on failure */
int play_frame(void)
{
	unsigned char *audio;
	int mc;
	long new_header = 0;
	size_t bytes;
	debug("play_frame");
	/* The first call will not decode anything but return MPG123_NEW_FORMAT! */
	mc = mpg123_decode_frame(mh, &framenum, &audio, &bytes);
	mpg123_getstate(mh, MPG123_FRESH_DECODER, &new_header, NULL);

	/* Play what is there to play (starting with second decode_frame call!) */
	if(bytes)
	{
		if(param.frame_number > -1) --frames_left;
		if(fresh && framenum >= param.start_frame)
		{
			fresh = FALSE;
		}
		/* Normal flushing of data, includes buffer decoding. */
		if(flush_output(ao, audio, bytes) < (int)bytes && !intflag)
		{
			error("Deep trouble! Cannot flush to my output anymore!");
			safe_exit(133);
		}
		if(param.checkrange)
		{
			long clip = mpg123_clip(mh);
			if(clip > 0) fprintf(stderr,"%ld samples clipped\n", clip);
		}
	}
	/* Special actions and errors. */
	if(mc != MPG123_OK)
	{
		if(mc == MPG123_ERR || mc == MPG123_DONE)
		{
			if(mc == MPG123_ERR) error1("...in decoding next frame: %s", mpg123_strerror(mh));
			return 0;
		}
		if(mc == MPG123_NO_SPACE)
		{
			error("I have not enough output space? I didn't plan for this.");
			return 0;
		}
		if(mc == MPG123_NEW_FORMAT)
		{
			long rate;
			int channels, format;
			mpg123_getformat(mh, &rate, &channels, &format);
			if(param.verbose > 2) fprintf(stderr, "\nNote: New output format %liHz %ich, format %i\n", rate, channels, format);

			new_header = 1;
			reset_audio(rate, channels, format);
		}
	}
	if(new_header && !param.quiet)
	{
		fprintf(stderr, "\n");
		if(param.verbose) print_header(mh);
		else print_header_compact(mh);
	}
	return 1;
}
예제 #3
0
파일: mpg123.c 프로젝트: flatmax/mpg123
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

/* make sure not Cygwin, it doesn't need it */
#if defined(WIN32) && defined(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");

	close_track();

	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;
}
예제 #4
0
파일: win32_net.c 프로젝트: 5py/libmpg123
int win32_net_http_open(char* url, struct httpdata *hd)
{
	mpg123_string purl, host, port, path;
	mpg123_string request, response, request_url;
	mpg123_string httpauth1;
	ws.local_socket = SOCKET_ERROR;
	int oom  = 0;
	int relocate, numrelocs = 0;
	int got_location = FALSE;
	/*
		workaround for http://www.global24music.com/rautemusik/files/extreme/isdn.pls
		this site's apache gives me a relocation to the same place when I give the port in Host request field
		for the record: Apache/2.0.51 (Fedora)
	*/
	int try_without_port = 0;
	mpg123_init_string(&purl);
	mpg123_init_string(&host);
	mpg123_init_string(&port);
	mpg123_init_string(&path);
	mpg123_init_string(&request);
	mpg123_init_string(&response);
	mpg123_init_string(&request_url);
	mpg123_init_string(&httpauth1);

	/* Get initial info for proxy server. Once. */
	if(hd->proxystate == PROXY_UNKNOWN && !proxy_init(hd)) goto exit;

	if(!translate_url(url, &purl)){ oom=1; goto exit; }

	/* Don't confuse the different auth strings... */
	if(!split_url(&purl, &httpauth1, NULL, NULL, NULL) ){ oom=1; goto exit; }

	/* "GET http://"		11
	 * " HTTP/1.0\r\nUser-Agent: <PACKAGE_NAME>/<PACKAGE_VERSION>\r\n"
	 * 				26 + PACKAGE_NAME + PACKAGE_VERSION
	 * accept header            + accept_length()
	 * "Authorization: Basic \r\n"	23
	 * "\r\n"			 2
	 * ... plus the other predefined header lines
	 */
	/* Just use this estimate as first guess to reduce malloc calls in string library. */
	{
		size_t length_estimate = 62 + strlen(PACKAGE_NAME) + strlen(PACKAGE_VERSION) 
		                       + accept_length() + strlen(CONN_HEAD) + strlen(icy_yes) + purl.fill;
		if(    !mpg123_grow_string(&request, length_estimate)
		    || !mpg123_grow_string(&response,4096) )
		{
			oom=1; goto exit;
		}
	}

	do
	{
		/* Storing the request url, with http:// prepended if needed. */
		/* used to be url here... seemed wrong to me (when loop advanced...) */
		if(strncasecmp(purl.p, "http://", 7) != 0) mpg123_set_string(&request_url, "http://");
		else mpg123_set_string(&request_url, "");

		mpg123_add_string(&request_url, purl.p);

		if (hd->proxystate >= PROXY_HOST)
		{
			/* We will connect to proxy, full URL goes into the request. */
			if(    !mpg123_copy_string(&hd->proxyhost, &host)
			    || !mpg123_copy_string(&hd->proxyport, &port)
			    || !mpg123_set_string(&request, "GET ")
			    || !mpg123_add_string(&request, request_url.p) )
			{
				oom=1; goto exit;
			}
		}
		else
		{
			/* We will connect to the host from the URL and only the path goes into the request. */
			if(!split_url(&purl, NULL, &host, &port, &path)){ oom=1; goto exit; }
			if(    !mpg123_set_string(&request, "GET ")
			    || !mpg123_add_string(&request, path.p) )
			{
				oom=1; goto exit;
			}
		}

		if(!fill_request(&request, &host, &port, &httpauth1, &try_without_port)){ oom=1; goto exit; }

		httpauth1.fill = 0; /* We use the auth data from the URL only once. */
		debug2("attempting to open_connection to %s:%s", host.p, port.p);
		win32_net_open_connection(&host, &port);
		if(ws.local_socket == SOCKET_ERROR)
		{
			error1("Unable to establish connection to %s", host.fill ? host.p : "");
			goto exit;
		}
		debug("win32_net_open_connection succeed");
#define http_failure win32_net_close(ws.local_socket); ws.local_socket=SOCKET_ERROR; goto exit;
		
		if(param.verbose > 2) fprintf(stderr, "HTTP request:\n%s\n",request.p);
		if(!win32_net_writestring(ws.local_socket, &request)){ http_failure; }
		debug("Skipping fdopen for WSA sockets");
		relocate = FALSE;
		/* Arbitrary length limit here... */
#define safe_readstring \
		win32_net_readstring(&response, SIZE_MAX/16, NULL); \
		if(response.fill > SIZE_MAX/16) /* > because of appended zero. */ \
		{ \
			error("HTTP response line exceeds max. length"); \
			http_failure; \
		} \
		else if(response.fill == 0) \
		{ \
			error("readstring failed"); \
			http_failure; \
		} \
		if(param.verbose > 2) fprintf(stderr, "HTTP in: %s", response.p);
		safe_readstring;

		{
			char *sptr;
			if((sptr = strchr(response.p, ' ')))
			{
				if(response.fill > sptr-response.p+2)
				switch (sptr[1])
				{
					case '3':
						relocate = TRUE;
					case '2':
						break;
					default:
						fprintf (stderr, "HTTP request failed: %s", sptr+1); /* '\n' is included */
						http_failure;
				}
				else{ error("Too short response,"); http_failure; }
			}
		}

		/* If we are relocated, we need to look out for a Location header. */
		got_location = FALSE;

		do
		{
			safe_readstring; /* Think about that: Should we really error out when we get nothing? Could be that the server forgot the trailing empty line... */
			if (!strncasecmp(response.p, "Location: ", 10))
			{ /* It is a redirection! */
				if(!win32_net_resolve_redirect(&response, &request_url, &purl)){ oom=1, http_failure; }

				if(!strcmp(purl.p, request_url.p))
				{
					warning("relocated to very same place! trying request again without host port");
					try_without_port = 1;
				}
				got_location = TRUE;
			}
			else
			{ /* We got a header line (or the closing empty line). */
				char *tmp;
				debug1("searching for header values... %s", response.p);
				/* Not sure if I want to bail out on error here. */
				/* Also: What text encoding are these strings in? Doesn't need to be plain ASCII... */
				get_header_string(&response, "content-type", &hd->content_type);
				get_header_string(&response, "icy-name",     &hd->icy_name);
				get_header_string(&response, "icy-url",      &hd->icy_url);

				/* watch out for icy-metaint */
				if((tmp = get_header_val("icy-metaint", &response)))
				{
					hd->icy_interval = (off_t) atol(tmp); /* atoll ? */
					debug1("got icy-metaint %li", (long int)hd->icy_interval);
				}
			}
		} while(response.p[0] != '\r' && response.p[0] != '\n');
	} while(relocate && got_location && purl.fill && numrelocs++ < HTTP_MAX_RELOCATIONS);
	if(relocate)
	{
		if(!got_location)
		error("Server meant to redirect but failed to provide a location!");
		else
		error1("Too many HTTP relocations (%i).", numrelocs);

		http_failure;
	}

exit: /* The end as well as the exception handling point... */
	if(oom) error("Apparently, I ran out of memory or had some bad input data...");

	mpg123_free_string(&purl);
	mpg123_free_string(&host);
	mpg123_free_string(&port);
	mpg123_free_string(&path);
	mpg123_free_string(&request);
	mpg123_free_string(&response);
	mpg123_free_string(&request_url);
	mpg123_free_string(&httpauth1);
	if (ws.local_socket == SOCKET_ERROR || oom)
	return -1;
	else
	return 1;
}
예제 #5
0
파일: mpg123.c 프로젝트: flatmax/mpg123
/* 1 on success, 0 on failure */
int open_track(char *fname)
{
	filept=-1;
	httpdata_reset(&htd);
	if(MPG123_OK != mpg123_param(mh, MPG123_ICY_INTERVAL, 0, 0))
	error1("Cannot (re)set ICY interval: %s", mpg123_strerror(mh));
	if(!strcmp(fname, "-"))
	{
		filept = STDIN_FILENO;
#ifdef WIN32
		_setmode(STDIN_FILENO, _O_BINARY);
#endif
		return open_track_fd();
	}
	else if (!strncmp(fname, "http://", 7)) /* http stream */
	{
#if defined (WANT_WIN32_SOCKETS)
	if(param.streamdump != NULL)
	{
		fprintf(stderr, "\nWarning: win32 networking conflicts with stream dumping. Aborting the dump.\n");
		dump_close();
	}
	/*Use recv instead of stdio functions */
	win32_net_replace(mh);
	filept = win32_net_http_open(fname, &htd);
#else
	filept = http_open(fname, &htd);
#endif
	network_sockets_used = 1;
/* utf-8 encoded URLs might not work under Win32 */
		
		/* now check if we got sth. and if we got sth. good */
		if(    (filept >= 0) && (htd.content_type.p != NULL)
			  && !APPFLAG(MPG123APP_IGNORE_MIME) && !(debunk_mime(htd.content_type.p) & IS_FILE) )
		{
			error1("Unknown mpeg MIME type %s - is it perhaps a playlist (use -@)?", htd.content_type.p == NULL ? "<nil>" : htd.content_type.p);
			error("If you know the stream is mpeg1/2 audio, then please report this as "PACKAGE_NAME" bug");
			return 0;
		}
		if(filept < 0)
		{
			error1("Access to http resource %s failed.", fname);
			return 0;
		}
		if(MPG123_OK != mpg123_param(mh, MPG123_ICY_INTERVAL, htd.icy_interval, 0))
		error1("Cannot set ICY interval: %s", mpg123_strerror(mh));
		if(param.verbose > 1) fprintf(stderr, "Info: ICY interval %li\n", (long)htd.icy_interval);
	}

	if(param.icy_interval > 0)
	{
		if(MPG123_OK != mpg123_param(mh, MPG123_ICY_INTERVAL, param.icy_interval, 0))
		error1("Cannot set ICY interval: %s", mpg123_strerror(mh));
		if(param.verbose > 1) fprintf(stderr, "Info: Forced ICY interval %li\n", param.icy_interval);
	}

	debug("OK... going to finally open.");
	/* Now hook up the decoder on the opened stream or the file. */
	if(network_sockets_used) 
	{
		return open_track_fd();
	}
	else if(mpg123_open(mh, fname) != MPG123_OK)
	{
		error2("Cannot open %s: %s", fname, mpg123_strerror(mh));
		return 0;
	}
	debug("Track successfully opened.");

	fresh = TRUE;
	return 1;
}
예제 #6
0
/* This uses the currently opened audio device, queries its caps.
   In case of buffered playback, this works _once_ by querying the buffer for the caps before entering the main loop. */
void audio_capabilities(audio_output_t *ao, mpg123_handle *mh)
{
    int force_fmt = 0;
    int fmts;
    size_t ri;
    /* Pitching introduces a difference between decoder rate and playback rate. */
    long rate, decode_rate;
    int channels;
    const long *rates;
    size_t      num_rates, rlimit;
    debug("audio_capabilities");
    mpg123_rates(&rates, &num_rates);
    mpg123_format_none(mh); /* Start with nothing. */
    if(param.force_encoding != NULL)
    {
        int i;
        if(!param.quiet) fprintf(stderr, "Note: forcing output encoding %s\n", param.force_encoding);

        for(i=0; i<KNOWN_ENCS; ++i)
            if(!strncasecmp(encdesc[i].name, param.force_encoding, encdesc[i].nlen))
            {
                force_fmt = encdesc[i].code;
                break;
            }

        if(i==KNOWN_ENCS)
        {
            error1("Failed to find an encoding to match requested \"%s\"!\n", param.force_encoding);
            return; /* No capabilities at all... */
        }
        else if(param.verbose > 2) fprintf(stderr, "Note: forcing encoding code 0x%x\n", force_fmt);
    }
    rlimit = param.force_rate > 0 ? num_rates+1 : num_rates;
    for(channels=1; channels<=2; channels++)
        for(ri = 0; ri<rlimit; ri++)
        {
            decode_rate = ri < num_rates ? rates[ri] : param.force_rate;
            rate = pitch_rate(decode_rate);
            if(param.verbose > 2) fprintf(stderr, "Note: checking support for %liHz/%ich.\n", rate, channels);
#ifndef NOXFERMEM
            if(param.usebuffer)
            {   /* Ask the buffer process. It is waiting for this. */
                buffermem->rate     = rate;
                buffermem->channels = channels;
                buffermem->format   = 0; /* Just have it initialized safely. */
                debug2("asking for formats for %liHz/%ich", rate, channels);
                xfermem_putcmd(buffermem->fd[XF_WRITER], XF_CMD_AUDIOCAP);
                xfermem_getcmd(buffermem->fd[XF_WRITER], TRUE);
                fmts = buffermem->format;
            }
            else
#endif
            {   /* Check myself. */
                ao->rate     = rate;
                ao->channels = channels;
                fmts = ao->get_formats(ao);
            }
            if(param.verbose > 2) fprintf(stderr, "Note: result 0x%x\n", fmts);
            if(force_fmt)
            {   /* Filter for forced encoding. */
                if((fmts & force_fmt) == force_fmt) fmts = force_fmt;
                else fmts = 0; /* Nothing else! */

                if(param.verbose > 2) fprintf(stderr, "Note: after forcing 0x%x\n", fmts);
            }

            if(fmts < 0) continue;
            else mpg123_format(mh, decode_rate, channels, fmts);
        }

#ifndef NOXFERMEM
    /* Buffer loop shall start normal operation now. */
    if(param.usebuffer)
    {
        xfermem_putcmd(buffermem->fd[XF_WRITER], XF_CMD_WAKEUP);
        xfermem_getcmd(buffermem->fd[XF_WRITER], TRUE);
    }
#endif

    if(param.verbose > 1) print_capabilities(ao, mh);
}
예제 #7
0
파일: rb2rgb.c 프로젝트: jbmulligan/quip
static int install_white(SINGLE_QSP_ARG_DECL)
{
	int j,k;
	float wc[3];	/* white chromaticity */
	float uv[3];	/* unit vector */
	float *ptr;

	if( init_matrices(SINGLE_QSP_ARG) < 0 ) return(-1);

	/* we assume we already have the white point */
	if( ! know_white )
		error1("install_white:  white point not defined!?");


	for(j=0;j<3;j++) wc[j] = _white[j];
showvec(wc);
	rgb2rb(wc);	/* now we have the chromaticity of the white point */
advise("white transformed to opponent space");
showvec(wc);

	for(j=0;j<3;j++) uv[j] = wc[j];
	uv[0]+= 0.1;	/* take a step in the red cone direction */
	rb2rgb(uv);
	for(j=0;j<3;j++) uv[j] -= _white[j];

	/* now have an rgb vector for an red cone step */
	/* normalize this relative to the white point */
	/* this is to guarantee that amp. of +-1 won't overflow */
advise("red cone vector");
showvec(wc);

	wnorm(uv);

	/* now set the entries of the o2p matrix */
	for(j=0;j<3;j++) o2p_mat[j][0] = uv[j];

	for(j=0;j<3;j++) uv[j] = wc[j];
	uv[1]+= 0.1;	/* take a step in the blue cone  direction */
	rb2rgb(uv);
	for(j=0;j<3;j++) uv[j] -= _white[j];

	/* now have an rgb vector for a blue cone step */

	wnorm(uv);

	for(j=0;j<3;j++) o2p_mat[j][1] = uv[j];

	for(j=0;j<3;j++) uv[j] = _white[j];
	wnorm(uv);
	for(j=0;j<3;j++) o2p_mat[j][2] = uv[j];

	ptr = (float *)OBJ_DATA_PTR(o2p_dp);
	for(j=0;j<3;j++)
		for(k=0;k<3;k++)
			*ptr++ = o2p_mat[j][k];
	dp_copy(p2o_dp,o2p_dp);
	dt_invert(p2o_dp);
	ptr = (float *)OBJ_DATA_PTR(p2o_dp);
	for(j=0;j<3;j++)
		for(k=0;k<3;k++)
			p2o_mat[j][k] = *ptr++;

	return(0);
}
예제 #8
0
파일: readers.c 프로젝트: 4johndoe/Podax
/* stream based operation  with icy meta data*/
static ssize_t icy_fullread(mpg123_handle *fr, unsigned char *buf, ssize_t count)
{
	ssize_t ret,cnt;
	cnt = 0;
	if(fr->rdat.flags & READER_SEEKABLE)
	{
		if(NOQUIET) error("mpg123 programmer error: I don't do ICY on seekable streams.");
		return -1;
	}
	/*
		There used to be a check for expected file end here (length value or ID3 flag).
		This is not needed:
		1. EOF is indicated by fdread returning zero bytes anyway.
		2. We get false positives of EOF for either files that grew or
		3. ... files that have ID3v1 tags in between (stream with intro).
	*/

	while(cnt < count)
	{
		/* all icy code is inside this if block, everything else is the plain fullread we know */
		/* debug1("read: %li left", (long) count-cnt); */
		if(fr->icy.next < count-cnt)
		{
			unsigned char temp_buff;
			size_t meta_size;
			ssize_t cut_pos;

			/* we are near icy-metaint boundary, read up to the boundary */
			if(fr->icy.next > 0)
			{
				cut_pos = fr->icy.next;
				ret = fr->rdat.fdread(fr,buf+cnt,cut_pos);
				if(ret < 1)
				{
					if(ret == 0) break; /* Just EOF. */
					if(NOQUIET) error("icy boundary read");

					return READER_ERROR;
				}

				if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret;
				cnt += ret;
				fr->icy.next -= ret;
				if(fr->icy.next > 0)
				{
					debug1("another try... still %li left", (long)fr->icy.next);
					continue;
				}
			}
			/* now off to read icy data */

			/* one byte icy-meta size (must be multiplied by 16 to get icy-meta length) */
			
			ret = fr->rdat.fdread(fr,&temp_buff,1); /* Getting one single byte hast to suceed. */
			if(ret < 0){ if(NOQUIET) error("reading icy size"); return READER_ERROR; }
			if(ret == 0) break;

			debug2("got meta-size byte: %u, at filepos %li", temp_buff, (long)fr->rdat.filepos );
			if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret; /* 1... */

			if((meta_size = ((size_t) temp_buff) * 16))
			{
				/* we have got some metadata */
				char *meta_buff;
				/* TODO: Get rid of this malloc ... perhaps hooking into the reader buffer pool? */
				meta_buff = malloc(meta_size+1);
				if(meta_buff != NULL)
				{
					ssize_t left = meta_size;
					while(left > 0)
					{
						ret = fr->rdat.fdread(fr,meta_buff+meta_size-left,left);
						/* 0 is error here, too... there _must_ be the ICY data, the server promised! */
						if(ret < 1){ if(NOQUIET) error("reading icy-meta"); return READER_ERROR; }
						left -= ret;
					}
					meta_buff[meta_size] = 0; /* string paranoia */
					if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret;

					if(fr->icy.data) free(fr->icy.data);
					fr->icy.data = meta_buff;
					fr->metaflags |= MPG123_NEW_ICY;
					debug2("icy-meta: %s size: %d bytes", fr->icy.data, (int)meta_size);
				}
				else
				{
					if(NOQUIET) error1("cannot allocate memory for meta_buff (%lu bytes) ... trying to skip the metadata!", (unsigned long)meta_size);
					fr->rd->skip_bytes(fr, meta_size);
				}
			}
			fr->icy.next = fr->icy.interval;
		}
		else
		{
			ret = plain_fullread(fr, buf+cnt, count-cnt);
			if(ret < 0){ if(NOQUIET) error1("reading the rest of %li", (long)(count-cnt)); return READER_ERROR; }
			if(ret == 0) break;

			cnt += ret;
			fr->icy.next -= ret;
		}
	}
	/* debug1("done reading, got %li", (long)cnt); */
	return cnt;
}
예제 #9
0
/* Open an audio output module, trying modules in list (comma-separated). */
audio_output_t* open_output_module( const char* names )
{
    mpg123_module_t *module = NULL;
    audio_output_t *ao = NULL;
    int result = 0;
    char *curname, *modnames;

    if(param.usebuffer || names==NULL) return NULL;

    /* Use internal code. */
    if(param.outmode != DECODE_AUDIO) return open_fake_module();

    modnames = strdup(names);
    if(modnames == NULL)
    {
        error("Error allocating memory for module names.");
        return NULL;
    }
    /* Now loop over the list of possible modules to find one that works. */
    curname = strtok(modnames, ",");
    while(curname != NULL)
    {
        char* name = curname;
        curname = strtok(NULL, ",");
        if(param.verbose > 1) fprintf(stderr, "Trying output module %s.\n", name);
        /* Open the module, initial check for availability+libraries. */
        module = open_module( "output", name );
        if(module == NULL) continue;
        /* Check if module supports output */
        if(module->init_output == NULL)
        {
            error1("Module '%s' does not support audio output.", name);
            close_module(module);
            continue; /* Try next one. */
        }
        /* Allocation+initialization of memory for audio output type. */
        ao = alloc_audio_output();
        if(ao==NULL)
        {
            error("Failed to allocate audio output structure.");
            close_module(module);
            break; /* This is fatal. */
        }

        /* Call the init function */
        ao->device = param.output_device;
        ao->flags  = param.output_flags;
        /* Should I do funny stuff with stderr file descriptor instead? */
        if(curname == NULL)
        {
            if(param.verbose > 1)
                fprintf(stderr, "Note: %s is the last output option... showing you any error messages now.\n", name);
        }
        else ao->auxflags |= MPG123_OUT_QUIET; /* Probing, so don't spill stderr with errors. */
        ao->is_open = FALSE;
        ao->module = module; /* Need that to close module later. */
        result = module->init_output(ao);
        if(result == 0)
        {   /* Try to open the device. I'm only interested in actually working modules. */
            result = open_output(ao);
            close_output(ao);
        }
        else error2("Module '%s' init failed: %i", name, result);

        if(result!=0)
        {   /* Try next one... */
            close_module(module);
            free(ao);
            ao = NULL;
        }
        else
        {   /* All good, leave the loop. */
            if(param.verbose > 1) fprintf(stderr, "Output module '%s' chosen.\n", name);

            ao->auxflags &= ~MPG123_OUT_QUIET;
            break;
        }
    }

    free(modnames);
    if(ao==NULL) error1("Unable to find a working output module in this list: %s", names);

    return ao;
}
예제 #10
0
파일: Printer.cpp 프로젝트: alekstorm/tala
int Printer_print (void (*draw) (void *boss, Graphics g), void *boss) {
	#if defined (UNIX)
		structMelderFile tempFile = { 0 };
		char tempPath_utf8 [] = "/tmp/picXXXXXX";
		close (mkstemp (tempPath_utf8));
		Melder_pathToFile (Melder_peekUtf8ToWcs (tempPath_utf8), & tempFile);
		thePrinter. graphics = Graphics_create_postscriptjob (& tempFile, thePrinter. resolution,
			thePrinter. spots, thePrinter. paperSize, thePrinter. orientation, thePrinter. magnification);
		if (! thePrinter. graphics) return Melder_error1 (L"Cannot create temporary PostScript file for printing.");
		draw (boss, thePrinter. graphics);
		forget (thePrinter. graphics);
		char command [500];
		sprintf (command, Melder_peekWcsToUtf8 (Site_getPrintCommand ()), tempPath_utf8);
		system (command);
		MelderFile_delete (& tempFile);
	#elif defined (_WIN32)
		int postScriptCode = POSTSCRIPT_PASSTHROUGH;
		DOCINFO docInfo;
		DEVMODE *devMode;
		initPrinter ();
		if (! theWinPrint. hDevMode) {
			memset (& theWinPrint, 0, sizeof (PRINTDLG));
			theWinPrint. lStructSize = sizeof (PRINTDLG);
			theWinPrint. Flags = PD_RETURNDEFAULT;
			if (! PrintDlg (& theWinPrint)) return Melder_error1 (L"Cannot initialize printer.");
		}
		if (Melder_backgrounding) {
			theWinPrint. Flags = PD_RETURNDEFAULT | PD_RETURNDC;
			if (! PrintDlg (& theWinPrint) || theWinPrint. hDC == NULL) {
				return Melder_error1 (L"Cannot print from a script on this computer.");
			}
		} else {
			theWinPrint. Flags &= ~ PD_RETURNDEFAULT;
			theWinPrint. Flags |= PD_RETURNDC;
			if (! PrintDlg (& theWinPrint)) return 1;
		}
		theWinDC = theWinPrint. hDC;
		thePrinter. postScript = thePrinter. allowDirectPostScript &&
			Escape (theWinDC, QUERYESCSUPPORT, sizeof (int), (LPSTR) & postScriptCode, NULL);
		/*
		 * The HP colour inkjet printer returns in dmFields:
		 * 0, 1, 8, 9, 10, 11, 12, 13, 14, 15, 23, 24, 25, 26 = DM_ORIENTATION |
		 *    DM_PAPERSIZE | DM_COPIES | DM_DEFAULTSOURCE | DM_PRINTQUALITY |
		 *    DM_COLOR | DM_DUPLEX | DM_YRESOLUTION | DM_TTOPTION | DM_COLLATE |
		 *    DM_ICMMETHOD | DM_ICMINTENT | DM_MEDIATYPE | DM_DITHERTYPE
		 */
		devMode = * (DEVMODE **) theWinPrint. hDevMode;
		thePrinter. resolution = devMode -> dmFields & DM_YRESOLUTION ? devMode -> dmYResolution :
			devMode -> dmFields & DM_PRINTQUALITY ?
			( devMode -> dmPrintQuality > 0 ? devMode -> dmPrintQuality : 300 ) : 300;
		if (devMode -> dmFields & DM_PAPERWIDTH) {
			thePrinter. paperWidth = devMode -> dmPaperWidth * thePrinter. resolution / 254;
			thePrinter. paperHeight = devMode -> dmPaperLength * thePrinter. resolution / 254;
		} else if (devMode -> dmFields & DM_PAPERSIZE) {
			static struct { float width, height; } sizes [] = { { 0, 0 }, { 8.5, 11 }, { 8.5, 11 }, { 11, 17 },
				{ 17, 11 }, { 8.5, 14 }, { 5.5, 8.5 }, { 7.25, 10.5 }, { 297/25.4, 420/25.4 },
				{ 210/25.4, 297/25.4 }, { 210/25.4, 297/25.4 }, { 148.5/25.4, 210/25.4 },
				{ 250/25.4, 354/25.4 }, { 182/25.4, 257/25.4 }, { 8.5, 13 },
				{ 215/25.4, 275/25.4 }, { 10, 14 }, { 11, 17 }, { 8.5, 11 }, { 3.875, 8.875 },
				{ 4.125, 9.5 }, { 4.5, 10.375 } };
			int paperSize = devMode -> dmPaperSize;
			if (paperSize <= 0 || paperSize > 21) paperSize = 1;
			thePrinter. paperWidth = sizes [paperSize]. width * thePrinter. resolution;
			thePrinter. paperHeight = sizes [paperSize]. height * thePrinter. resolution;
			if (devMode -> dmOrientation == DMORIENT_LANDSCAPE) {
				long dummy = thePrinter. paperWidth;
				thePrinter. paperWidth = thePrinter. paperHeight;
				thePrinter. paperHeight = dummy;
			}
		} else {
			thePrinter. paperWidth = 1000;
			thePrinter. paperHeight = 1000;
		}
		EnableWindow ((HWND) XtWindow (theCurrentPraatApplication -> topShell), FALSE);
		SetAbortProc (theWinDC, AbortFunc);
		memset (& docInfo, 0, sizeof (DOCINFO));
		docInfo. cbSize = sizeof (DOCINFO);
		docInfo. lpszDocName = L"Praatjes";
		docInfo. lpszOutput = NULL;
		if (thePrinter. postScript) {
			StartDoc (theWinDC, & docInfo);
			StartPage (theWinDC);
			initPostScriptPage ();
			thePrinter. graphics = Graphics_create_postscriptprinter ();
			if (! thePrinter. graphics) return Melder_error1 (L"Cannot open printer.");
			draw (boss, thePrinter. graphics);
			forget (thePrinter. graphics);
			exitPostScriptPage ();
			EndPage (theWinDC);
			EndDoc (theWinDC);
		} else {
			StartDoc (theWinDC, & docInfo);
			StartPage (theWinDC);
			thePrinter. graphics = Graphics_create_screenPrinter (NULL, (unsigned long) theWinDC);
			if (! thePrinter. graphics) return Melder_error1 (L"Cannot open printer.");
			draw (boss, thePrinter. graphics);
			forget (thePrinter. graphics);
			if (EndPage (theWinDC) < 0) {
				Melder_error1 (L"Cannot print page.");
			} else {
				EndDoc (theWinDC);
			}
		}
		EnableWindow ((HWND) XtWindow (theCurrentPraatApplication -> topShell), TRUE);
		DeleteDC (theWinDC), theWinDC = NULL;
	#elif defined (macintosh)
		Boolean result;
		initPrinter ();
		if (Melder_backgrounding) {
			PMSessionValidatePageFormat (theMacPrintSession, theMacPageFormat, & result);
			PMSessionValidatePrintSettings (theMacPrintSession, theMacPrintSettings, & result);
		} else {
			Boolean accepted;
			PMSessionPrintDialog (theMacPrintSession, theMacPrintSettings, theMacPageFormat, & accepted);
			if (! accepted) return 1;   /* Normal cancelled return. */
		}
		PMSessionValidatePageFormat (theMacPrintSession, theMacPageFormat, & result);
		PMSessionValidatePrintSettings (theMacPrintSession, theMacPrintSettings, & result);
		PMResolution res;
		PMGetResolution (theMacPageFormat, & res);
		thePrinter. resolution = res. hRes;
		PMGetAdjustedPaperRect (theMacPageFormat, & paperSize);
		thePrinter. paperWidth = paperSize. right - paperSize. left;
		thePrinter. paperHeight = paperSize. bottom - paperSize. top;
		Boolean isPostScriptDriver = FALSE;
		//PMSessionIsDocumentFormatSupported (theMacPrintSession,
		//	kPMDocumentFormatPICTPS, & isPostScriptDriver);
		CFArrayRef supportedFormats;
		PMSessionGetDocumentFormatGeneration (theMacPrintSession, & supportedFormats);
		CFIndex numberOfSupportedFormats = CFArrayGetCount (supportedFormats);
		if (Melder_debug == 21) {
			MelderInfo_open ();
			MelderInfo_writeLine1 (L"Supported document formats:");
		}
		for (CFIndex i = 0; i < numberOfSupportedFormats; i ++) {
			CFStringRef supportedFormat = CFArrayGetValueAtIndex (supportedFormats, i);
			if (CFStringCompare (supportedFormat, kPMDocumentFormatPICTPS, 0) == 0) {
				isPostScriptDriver = TRUE;
			}
			if (Melder_debug == 21) {
				MelderInfo_writeLine3 (Melder_integer (i), L": ",
					Melder_peekUtf8ToWcs (CFStringGetCStringPtr (supportedFormat, kCFStringEncodingUTF8)));
			}
		}
		if (Melder_debug == 21) {
			MelderInfo_close ();
		}
		CFRelease (supportedFormats);
		isPostScriptDriver = FALSE;   // OVERRIDE, because from 10.4 on we have something better: we'll be sending PDF
		thePrinter. postScript = thePrinter. allowDirectPostScript && isPostScriptDriver;
		if (thePrinter. postScript) {
			CFStringRef strings [1];
			strings [0] = kPMGraphicsContextQuickdraw;
			CFArrayRef array = CFArrayCreate (kCFAllocatorDefault, (const void **) strings, 1, & kCFTypeArrayCallBacks);
			OSStatus err = PMSessionSetDocumentFormatGeneration (theMacPrintSession, kPMDocumentFormatPICTPS, array, NULL);
			CFRelease (array);
			if (err != 0) {
				return Melder_error2 (L"PMSessionSetDocumentFormatGeneration: error ", Melder_integer (err));
			}
		}
		PMOrientation orientation;
		PMGetOrientation (theMacPageFormat, & orientation);
		thePrinter. orientation = orientation == kPMLandscape ||
			orientation == kPMReverseLandscape ? kGraphicsPostscript_orientation_LANDSCAPE : kGraphicsPostscript_orientation_PORTRAIT;
		PMSessionBeginDocument (theMacPrintSession, theMacPrintSettings, theMacPageFormat);
		PMSessionBeginPage (theMacPrintSession, theMacPageFormat, NULL);
		PMSessionGetGraphicsContext (theMacPrintSession, kPMGraphicsContextQuickdraw, (void **) & theMacPort);
		/*
		 * On PostScript, the point (0, 0) is the bottom left corner of the paper, which is fine.
		 * On the screen, however, the point (0, 0) is the top left corner of the writable page.
		 * Since we want paper-related margins, not writable-page-related margins,
		 * we require that this point gets the coordinates (250, 258) or so,
		 * so that the top left corner of the paper gets coordinates (0, 0).
		 * The "left" and "top" attributes of rPaper are negative values (e.g. -250 and -258),
		 * so multiply them by -1.
		 *
		 * Under Carbon, the port has to be set inside the page.
		 */
		SetPort (theMacPort);
		if (! thePrinter. postScript) SetOrigin (- paperSize. left, - paperSize. top);
		if (thePrinter. postScript) {
			if (! openPostScript ()) error1 (L"Cannot print PostScript.")
			thePrinter. graphics = Graphics_create_postscriptprinter ();
			if (! thePrinter. graphics) goto end;
			draw (boss, thePrinter. graphics);
			forget (thePrinter. graphics);
			closePostScript ();
		} else {
			thePrinter. graphics = Graphics_create_screenPrinter (NULL, (unsigned long) theMacPort);
			draw (boss, thePrinter. graphics);
			forget (thePrinter. graphics);
		}
	end:
		if (theMacPort) {
			PMSessionEndPage (theMacPrintSession);
			PMSessionEndDocument (theMacPrintSession);
			theMacPort = NULL;
		}
	#endif
	iferror return 0;
	return 1;
}
예제 #11
0
파일: module.c 프로젝트: JoeyZheng/deadbeef
/* Open a module in current directory. */
mpg123_module_t* open_module_here(const char* type, const char* name)
{
	lt_dlhandle handle = NULL;
	mpg123_module_t *module = NULL;
	char* module_path = NULL;
	size_t module_path_len = 0;
	char* module_symbol = NULL;
	size_t module_symbol_len = 0;

	/* Initialize libltdl */
	if(lt_dlinit())
	{
		error("Failed to initialise libltdl");
		return NULL;
	}

	/* Work out the path of the module to open */
	/* Note that we need to open ./file, not just file! */
	module_path_len = 2 + strlen(type) + 1 + strlen(name) + strlen(MODULE_FILE_SUFFIX) + 1;
	module_path = malloc( module_path_len );
	if (module_path == NULL) {
		error1( "Failed to allocate memory for module name: %s", strerror(errno) );
		return NULL;
	}
	snprintf( module_path, module_path_len, "./%s_%s%s", type, name, MODULE_FILE_SUFFIX );
	/* Display the path of the module created */
	if(param.verbose > 1) fprintf(stderr, "Module path: %s\n", module_path );

	/* Open the module */
	handle = lt_dlopen( module_path );
	free( module_path );
	if (handle==NULL) {
		error2( "Failed to open module %s: %s", name, lt_dlerror() );
		if(param.verbose > 1)
		fprintf(stderr, "Note: This could be because of braindead path in the .la file...\n");

		return NULL;
	}
	
	/* Work out the symbol name */
	module_symbol_len = strlen( MODULE_SYMBOL_PREFIX ) +
						strlen( type )  +
						strlen( MODULE_SYMBOL_SUFFIX ) + 1;
	module_symbol = malloc(module_symbol_len);
	if (module_symbol == NULL) {
		error1( "Failed to allocate memory for module symbol: %s", strerror(errno) );
		return NULL;
	}
	snprintf( module_symbol, module_symbol_len, "%s%s%s", MODULE_SYMBOL_PREFIX, type, MODULE_SYMBOL_SUFFIX );
	debug1( "Module symbol: %s", module_symbol );
	
	/* Get the information structure from the module */
	module = (mpg123_module_t*)lt_dlsym(handle, module_symbol );
	free( module_symbol );
	if (module==NULL) {
		error1( "Failed to get module symbol: %s", lt_dlerror() );
		return NULL;
	}
	
	/* Check the API version */
	if (MPG123_MODULE_API_VERSION != module->api_version)
	{
		error2( "API version of module does not match (got %i, expected %i).", module->api_version, MPG123_MODULE_API_VERSION);
		lt_dlclose(handle);
		return NULL;
	}

	/* Store handle in the data structure */
	module->handle = handle;
	return module;
}
예제 #12
0
파일: sgi.c 프로젝트: Distrotech/mpg123
static int open_sgi(audio_output_t *ao)
{
	int current_dev;
	ALport port = NULL;
	ALconfig config = alNewConfig();

	ao->userptr = NULL;

	/* Test for correct completion */
	if(config == 0)
	{
		error1("open_sgi: %s", alGetErrorString(oserror()));
		return -1;
	}

	/* Setup output device to specified device name. If there is no device name
	specified in ao structure, use the default for output */
	if((ao->device) != NULL)
	{
		current_dev = alGetResourceByName(AL_SYSTEM, ao->device, AL_OUTPUT_DEVICE_TYPE);

		debug2("Dev: %s %i", ao->device, current_dev);

		if(!current_dev)
		{
			int i, numOut;
			char devname[32];
			ALpv pv[1];
			ALvalue *alvalues;

			error2("Invalid audio resource: %s (%s)", ao->device, alGetErrorString(oserror()));

			if((numOut= alQueryValues(AL_SYSTEM,AL_DEFAULT_OUTPUT,0,0,0,0))>=0)
			fprintf(stderr, "There are %d output devices on this system.\n", numOut);
			else
			{
				fprintf(stderr, "Can't find output devices. alQueryValues failed: %s\n", alGetErrorString(oserror()));
				goto open_sgi_bad;
			}

			alvalues = malloc(sizeof(ALvalue) * numOut);
			i = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, alvalues, numOut, pv, 0);
			if(i == -1)
			error1("alQueryValues: %s", alGetErrorString(oserror()));
			else
			{
				for(i=0; i < numOut; i++)
				{
					pv[0].param = AL_NAME;
					pv[0].value.ptr = devname;
					pv[0].sizeIn = 32;
					alGetParams(alvalues[i].i, pv, 1);

					fprintf(stderr, "%i: %s\n", i, devname);
				}
			}
			free(alvalues);

			goto open_sgi_bad;
		}

		if(alSetDevice(config, current_dev) < 0)
		{
			error1("open: alSetDevice : %s",alGetErrorString(oserror()));
			goto open_sgi_bad;
		}
	} else
	current_dev = AL_DEFAULT_OUTPUT;

	/* Set the device */
	if(alSetDevice(config, current_dev) < 0)
	{
		error1("open_sgi: %s", alGetErrorString(oserror()));
		goto open_sgi_bad;
	}

	/* Set port parameters */

	if(alSetQueueSize(config, 131069) < 0)
	{
		error1("open_sgi: setting audio buffer failed: %s", alGetErrorString(oserror()));
		goto open_sgi_bad;
	}
	
	if(   set_format(ao, config) < 0
	   || set_rate(ao, config) < 0
	   || set_channels(ao, config) < 0 )
	goto open_sgi_bad;
	
	/* Open the audio port */
	port = alOpenPort("mpg123-VSC", "w", config);
	if(port == NULL)
	{
		error1("Unable to open audio channel: %s", alGetErrorString(oserror()));
		goto open_sgi_bad;
	}

	ao->userptr = (void*)port;

	alFreeConfig(config);
	return 1;

open_sgi_bad:
	/* clean up and return error */
	alFreeConfig(config);
	return -1;
}
예제 #13
0
static int open_sgi(audio_output_t *ao)
{
	int dev = AL_DEFAULT_OUTPUT;
	ALconfig config = alNewConfig();
	ALport port = NULL;
	
	/* Test for correct completion */
	if (config == 0) {
		error1("open_sgi: %s",alGetErrorString(oserror()));
		return -1;
	}
	
	/* Set port parameters */
	if(ao->channels == 2)
		alSetChannels(config, AL_STEREO);
	else
		alSetChannels(config, AL_MONO);
	
	alSetWidth(config, AL_SAMPLE_16);
	alSetSampFmt(config,AL_SAMPFMT_TWOSCOMP);
	alSetQueueSize(config, 131069);
	
	/* Setup output device to specified module. If there is no module
	specified in ao structure, use the default four output */
	if ((ao->device) != NULL) {
		char *dev_name;
		
		dev_name=malloc((strlen(ao->device) + strlen(analog_output_res_name) + 1) *
		  sizeof(char));
		
		strcpy(dev_name,ao->device);
		strcat(dev_name,analog_output_res_name);
		
		/* Find the asked device resource */
		dev=alGetResourceByName(AL_SYSTEM,dev_name,AL_DEVICE_TYPE);
		
		/* Free allocated space */
		free(dev_name);
		
		if (!dev) {
			error2("Invalid audio resource: %s (%s)",dev_name, alGetErrorString(oserror()));
			return -1;
		}
	}
	
	/* Set the device */
	if (alSetDevice(config,dev) < 0)
	{
		error1("open_sgi: %s",alGetErrorString(oserror()));
		return -1;
	}
	
	/* Open the audio port */
	port = alOpenPort("mpg123-VSC", "w", config);
	if(port == NULL) {
		error1("Unable to open audio channel: %s", alGetErrorString(oserror()));
		return -1;
	}
	
	ao->handle = (void*)port;
	
	
	set_format(ao, config);
	set_channels(ao, config);
	set_rate(ao, config);
	
	
	alFreeConfig(config);
	
	return 1;
}
예제 #14
0
파일: main.cpp 프로젝트: kokizzu/sdl_test
int main() {
    // more info at: https://wiki.libsdl.org/

    puts( "Initializing SDL.." );
    if(SDL_Init(SDL_INIT_EVERYTHING)) error1("SDL_Init Error");
    SDL_Window *win = SDL_CreateWindow("Pong", 100, 100, W, H, SDL_WINDOW_SHOWN);
    if (!win) error1("SDL_CreateWindow Error");
    SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);
    if (!ren) error1("SDL_CreateRenderer Error");

    SDL_Surface *sur = SDL_LoadBMP("bg.bmp");
    if(!sur) error1("SDL_CreateRGBSurface error");
    SDL_Texture *bg = SDL_CreateTextureFromSurface(ren,sur);
    if(!bg) error1("SDL_CreateTextureFromSurface error");
    SDL_FreeSurface(sur);

    sur = SDL_LoadBMP("fb.bmp");
    if(!sur) error1("SDL_CreateRGBSurface error");
    SDL_Texture *fb = SDL_CreateTextureFromSurface(ren,sur);
    if(!fb) error1("SDL_CreateTextureFromSurface error");
    SDL_FreeSurface(sur);

    Uint32 rate_ms;
    SDL_Event e;
    int speed = 5;
    SDL_Rect pos;
    pos.x = 100;
    pos.y = 100;
    pos.h = 36;
    pos.w = 36;
    int dx = speed, dy = speed;

    bool running = true;
    while(running) { // gamel loop
         rate_ms = SDL_GetTicks();
        // check for input
        while(SDL_PollEvent(&e)) {
            switch(e.type) {
            case SDL_QUIT:
                running = false;
                break;
            case SDL_KEYDOWN:
                switch(e.key.keysym.scancode) {
                    case SDL_SCANCODE_RETURN:
                    case SDL_SCANCODE_RETURN2:
                    case SDL_SCANCODE_KP_ENTER:
                    case SDL_SCANCODE_SPACE:
                        dx = 0;
                        dy = 0;
                    case SDL_SCANCODE_ESCAPE:
                        running = false;
                    break;
                }
                break;
            case SDL_MOUSEBUTTONUP:
                pos.x = e.motion.x;
                pos.y = e.motion.y;
                break;
            }
        }
        // game logic
        pos.x += dx;
        pos.y += dy;
        if(pos.x<=1) dx = speed;
        else if(pos.x>=W-pos.w) dx = -speed;
        if(pos.y<=1) dy = speed;
        else if(pos.y>=H-pos.h) dy = -speed;
        // render
        //SDL_RenderClear(ren);
        SDL_RenderCopy(ren, bg, NULL, NULL);
        SDL_RenderCopy(ren, fb, NULL, &pos);
        SDL_RenderPresent(ren);
        // sleep
        rate_ms = SDL_GetTicks()-rate_ms;
        if (rate_ms<FRAME_RATE) SDL_Delay(FRAME_RATE-rate_ms);
    }

    // free resources
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);
    SDL_Quit();
    return 0;
}