示例#1
0
static int dsound_restore_out (LPDIRECTSOUNDBUFFER dsb)
{
    HRESULT hr;
    int i;

    for (i = 0; i < conf.restore_retries; ++i) {
        hr = IDirectSoundBuffer_Restore (dsb);

        switch (hr) {
        case DS_OK:
            return 0;

        case DSERR_BUFFERLOST:
            continue;

        default:
            dsound_logerr (hr, "Could not restore playback buffer\n");
            return -1;
        }
    }

    dolog ("%d attempts to restore playback buffer failed\n", i);
    return -1;
}
示例#2
0
文件: cs4231a.c 项目: cardoe/qemu
static uint64_t cs_read (void *opaque, hwaddr addr, unsigned size)
{
    CSState *s = opaque;
    uint32_t saddr, iaddr, ret;

    saddr = addr;
    iaddr = ~0U;

    switch (saddr) {
    case Index_Address:
        ret = s->regs[saddr] & ~0x80;
        break;

    case Index_Data:
        if (!(s->dregs[MODE_And_ID] & MODE2))
            iaddr = s->regs[Index_Address] & 0x0f;
        else
            iaddr = s->regs[Index_Address] & 0x1f;

        ret = s->dregs[iaddr];
        if (iaddr == Error_Status_And_Initialization) {
            /* keep SEAL happy */
            if (s->aci_counter) {
                ret |= 1 << 5;
                s->aci_counter -= 1;
            }
        }
        break;

    default:
        ret = s->regs[saddr];
        break;
    }
    dolog ("read %d:%d -> %d\n", saddr, iaddr, ret);
    return ret;
}
示例#3
0
文件: paaudio.c 项目: ESOS-Lab/VSSIM
static pa_sample_format_t audfmt_to_pa (audfmt_e afmt, int endianness)
{
    int format;

    switch (afmt) {
    case AUD_FMT_S8:
    case AUD_FMT_U8:
        format = PA_SAMPLE_U8;
        break;
    case AUD_FMT_S16:
    case AUD_FMT_U16:
        format = endianness ? PA_SAMPLE_S16BE : PA_SAMPLE_S16LE;
        break;
    case AUD_FMT_S32:
    case AUD_FMT_U32:
        format = endianness ? PA_SAMPLE_S32BE : PA_SAMPLE_S32LE;
        break;
    default:
        dolog ("Internal logic error: Bad audio format %d\n", afmt);
        format = PA_SAMPLE_U8;
        break;
    }
    return format;
}
示例#4
0
static void
coreaudio_voice_fini (coreaudioVoice*  core)
{
    OSStatus status;
    int err;

    if (!conf.isAtexit) {
        /* stop playback */
        coreaudio_voice_ctl(core, VOICE_DISABLE);

        /* remove callback */
        status = AudioDeviceRemoveIOProc(core->deviceID, core->ioproc);
        if (status != kAudioHardwareNoError) {
            coreaudio_logerr (status, "Could not remove IOProc\n");
        }
    }
    core->deviceID = kAudioDeviceUnknown;

    /* destroy mutex */
    err = pthread_mutex_destroy(&core->mutex);
    if (err) {
        dolog("Could not destroy mutex\nReason: %s\n", strerror (err));
    }
}
示例#5
0
/*--------------------------------------------------------------------------*
 *	init controller state table entry
 *--------------------------------------------------------------------------*/
static int
init_controller_state(int controller, int ctrl_type, int card_type, int tei,
		      int nbch)
{
        int i;

	if((controller < 0) || (controller >= ncontroller))
	{
		dolog(LL_ERR, "init_controller_state: invalid controller number [%d]!", controller);
		return(ERROR);
	}
	
	/* init controller tab */
		
	switch (ctrl_type) {
	case CTRL_PASSIVE:
		if((card_type > CARD_TYPEP_UNK) &&
		   (card_type <= CARD_TYPEP_MAX))
		{
			isdn_ctrl_tab[controller].ctrl_type = ctrl_type;
			isdn_ctrl_tab[controller].card_type = card_type;
			isdn_ctrl_tab[controller].state = CTRL_UP;
		}
		else
		{
			dolog(LL_ERR, "init_controller_state: unknown card type %d", card_type);
			return(ERROR);
		}
		break;
		
	case CTRL_DAIC:
		isdn_ctrl_tab[controller].ctrl_type = ctrl_type;
		isdn_ctrl_tab[controller].card_type = card_type;
		isdn_ctrl_tab[controller].state = CTRL_DOWN;
		break;

	case CTRL_TINADD:
		isdn_ctrl_tab[controller].ctrl_type = ctrl_type;
		isdn_ctrl_tab[controller].card_type = 0;
		isdn_ctrl_tab[controller].state = CTRL_DOWN;
		break;

	case CTRL_CAPI:
		isdn_ctrl_tab[controller].ctrl_type = ctrl_type;
		isdn_ctrl_tab[controller].card_type = card_type;
		isdn_ctrl_tab[controller].state = CTRL_UP;
		break;

	default:
		dolog(LL_ERR, "init_controller_state: unknown controller type %d", ctrl_type);
		return(ERROR);
	}
	
	isdn_ctrl_tab[controller].nbch = nbch;
	isdn_ctrl_tab[controller].freechans = nbch;
	for (i = 0; i < nbch; i++)
	    isdn_ctrl_tab[controller].stateb[i] = CHAN_IDLE;
		isdn_ctrl_tab[controller].tei = tei;	
		isdn_ctrl_tab[controller].l1stat = LAYER_IDLE;
		isdn_ctrl_tab[controller].l2stat = LAYER_IDLE;

		dolog(LL_DMN, "init_controller_state: controller %d is %s",
		  controller,
		  name_of_controller(isdn_ctrl_tab[controller].ctrl_type,
				     isdn_ctrl_tab[controller].card_type));
		
	return(GOOD);
}	
示例#6
0
static int coreaudio_init_out(HWVoiceOut *hw, struct audsettings *as,
                              void *drv_opaque)
{
    OSStatus status;
    coreaudioVoiceOut *core = (coreaudioVoiceOut *) hw;
    UInt32 propertySize;
    int err;
    const char *typ = "playback";
    AudioValueRange frameRange;
    CoreaudioConf *conf = drv_opaque;

    /* create mutex */
    err = pthread_mutex_init(&core->mutex, NULL);
    if (err) {
        dolog("Could not create mutex\nReason: %s\n", strerror (err));
        return -1;
    }

    audio_pcm_init_info (&hw->info, as);

    /* open default output device */
    propertySize = sizeof(core->outputDeviceID);
    status = AudioHardwareGetProperty(
        kAudioHardwarePropertyDefaultOutputDevice,
        &propertySize,
        &core->outputDeviceID);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get default output Device\n");
        return -1;
    }
    if (core->outputDeviceID == kAudioDeviceUnknown) {
        dolog ("Could not initialize %s - Unknown Audiodevice\n", typ);
        return -1;
    }

    /* get minimum and maximum buffer frame sizes */
    propertySize = sizeof(frameRange);
    status = AudioDeviceGetProperty(
        core->outputDeviceID,
        0,
        0,
        kAudioDevicePropertyBufferFrameSizeRange,
        &propertySize,
        &frameRange);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get device buffer frame range\n");
        return -1;
    }

    if (frameRange.mMinimum > conf->buffer_frames) {
        core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMinimum;
        dolog ("warning: Upsizing Buffer Frames to %f\n", frameRange.mMinimum);
    }
    else if (frameRange.mMaximum < conf->buffer_frames) {
        core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMaximum;
        dolog ("warning: Downsizing Buffer Frames to %f\n", frameRange.mMaximum);
    }
    else {
        core->audioDevicePropertyBufferFrameSize = conf->buffer_frames;
    }

    /* set Buffer Frame Size */
    propertySize = sizeof(core->audioDevicePropertyBufferFrameSize);
    status = AudioDeviceSetProperty(
        core->outputDeviceID,
        NULL,
        0,
        false,
        kAudioDevicePropertyBufferFrameSize,
        propertySize,
        &core->audioDevicePropertyBufferFrameSize);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not set device buffer frame size %" PRIu32 "\n",
                           (uint32_t)core->audioDevicePropertyBufferFrameSize);
        return -1;
    }

    /* get Buffer Frame Size */
    propertySize = sizeof(core->audioDevicePropertyBufferFrameSize);
    status = AudioDeviceGetProperty(
        core->outputDeviceID,
        0,
        false,
        kAudioDevicePropertyBufferFrameSize,
        &propertySize,
        &core->audioDevicePropertyBufferFrameSize);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get device buffer frame size\n");
        return -1;
    }
    hw->samples = conf->nbuffers * core->audioDevicePropertyBufferFrameSize;

    /* get StreamFormat */
    propertySize = sizeof(core->outputStreamBasicDescription);
    status = AudioDeviceGetProperty(
        core->outputDeviceID,
        0,
        false,
        kAudioDevicePropertyStreamFormat,
        &propertySize,
        &core->outputStreamBasicDescription);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get Device Stream properties\n");
        core->outputDeviceID = kAudioDeviceUnknown;
        return -1;
    }

    /* set Samplerate */
    core->outputStreamBasicDescription.mSampleRate = (Float64) as->freq;
    propertySize = sizeof(core->outputStreamBasicDescription);
    status = AudioDeviceSetProperty(
        core->outputDeviceID,
        0,
        0,
        0,
        kAudioDevicePropertyStreamFormat,
        propertySize,
        &core->outputStreamBasicDescription);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ, "Could not set samplerate %d\n",
                           as->freq);
        core->outputDeviceID = kAudioDeviceUnknown;
        return -1;
    }

    /* set Callback */
    status = AudioDeviceAddIOProc(core->outputDeviceID, audioDeviceIOProc, hw);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ, "Could not set IOProc\n");
        core->outputDeviceID = kAudioDeviceUnknown;
        return -1;
    }

    /* start Playback */
    if (!isPlaying(core->outputDeviceID)) {
        status = AudioDeviceStart(core->outputDeviceID, audioDeviceIOProc);
        if (status != kAudioHardwareNoError) {
            coreaudio_logerr2 (status, typ, "Could not start playback\n");
            AudioDeviceRemoveIOProc(core->outputDeviceID, audioDeviceIOProc);
            core->outputDeviceID = kAudioDeviceUnknown;
            return -1;
        }
    }

    return 0;
}
示例#7
0
文件: p910nd.c 项目: Einheri/wl500g
void server(int lpnumber)
{
	struct rlimit resourcelimit;
#ifdef	USE_GETPROTOBYNAME
	struct protoent *proto;
#endif
	int netfd = -1, fd, lp, one = 1;
	int open_sleep = 10;
	socklen_t clientlen;
	struct sockaddr_storage client;
	struct addrinfo hints, *res, *ressave;
	char pidfilename[sizeof(PIDFILE)];
	char service[10];	// 9100 (65535 max)
	FILE *f;
	const int bufsiz = 65536;

#ifndef	TESTING
	if (!log_to_stdout)
	{
		switch (fork()) {
		case -1:
			dolog(LOGOPTS, "fork: %m\n");
			exit(1);
		case 0:		/* child */
			break;
		default:		/* parent */
			exit(0);
		}
		/* Now in child process */
		resourcelimit.rlim_max = 0;
		if (getrlimit(RLIMIT_NOFILE, &resourcelimit) < 0) {
			dolog(LOGOPTS, "getrlimit: %m\n");
			exit(1);
		}
		for (fd = 0; fd < resourcelimit.rlim_max; ++fd)
			(void)close(fd);
		if (setsid() < 0) {
			dolog(LOGOPTS, "setsid: %m\n");
			exit(1);
		}
		(void)chdir("/");
		(void)umask(022);
		fd = open("/dev/null", O_RDWR);	/* stdin */
		(void)dup(fd);		/* stdout */
		(void)dup(fd);		/* stderr */
		(void)snprintf(pidfilename, sizeof(pidfilename), PIDFILE, lpnumber);
		if ((f = fopen(pidfilename, "w")) == NULL) {
			dolog(LOGOPTS, "%s: %m\n", pidfilename);
			exit(1);
		}
		(void)fprintf(f, "%d\n", getpid());
		(void)fclose(f);
	}
	if (get_lock(lpnumber) == 0)
		exit(1);
#endif
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = PF_UNSPEC;
	hints.ai_flags = AI_PASSIVE;
	hints.ai_socktype = SOCK_STREAM;
	(void)snprintf(service, sizeof(service), "%hu", (BASEPORT + lpnumber - '0'));
	if (getaddrinfo(bindaddr, service, &hints, &res) != 0) {
		dolog(LOGOPTS, "getaddr: %m\n");
		exit(1);
	}
	ressave = res;
	while (res) {
#ifdef	USE_GETPROTOBYNAME
		if ((proto = getprotobyname("tcp6")) == NULL) {
			if ((proto = getprotobyname("tcp")) == NULL) {
				dolog(LOGOPTS, "Cannot find protocol for TCP!\n");
				exit(1);
			}
		}
		if ((netfd = socket(res->ai_family, res->ai_socktype, proto->p_proto)) < 0)
#else
		if ((netfd = socket(res->ai_family, res->ai_socktype, IPPROTO_IP)) < 0)
#endif
		{
			dolog(LOGOPTS, "socket: %m\n");
			close(netfd);
			res = res->ai_next;
			continue;
		}
		if (setsockopt(netfd, SOL_SOCKET, SO_RCVBUF, &bufsiz, sizeof(bufsiz)) < 0) {
			dolog(LOGOPTS, "setsocketopt: SO_RCVBUF: %m\n");
			/* not fatal if it fails */
		}
		if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF, &bufsiz, sizeof(bufsiz)) < 0) {
			dolog(LOGOPTS, "setsocketopt: SO_SNDBUF: %m\n");
			/* not fatal if it fails */
		}
		if (setsockopt(netfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) {
			dolog(LOGOPTS, "setsocketopt: SO_REUSEADDR: %m\n");
			close(netfd);
			res = res->ai_next;
			continue;
		}
		if (bind(netfd, res->ai_addr, res->ai_addrlen) < 0) {
			dolog(LOGOPTS, "bind: %m\n");
			close(netfd);
			res = res->ai_next;
			continue;
		}
		if (listen(netfd, 5) < 0) {
			dolog(LOGOPTS, "listen: %m\n");
			close(netfd);
			res = res->ai_next;
			continue;
		}
		break;
	}
	freeaddrinfo(ressave);
	clientlen = sizeof(client);
	memset(&client, 0, sizeof(client));
	while ((fd = accept(netfd, (struct sockaddr *)&client, &clientlen)) >= 0) {
		char host[INET6_ADDRSTRLEN];
#ifdef	USE_LIBWRAP
		if (hosts_ctl("p910nd", STRING_UNKNOWN, get_ip_str((struct sockaddr *)&client, host, sizeof(host)), STRING_UNKNOWN) == 0) {
			dolog(LOGOPTS,
			       "Connection from %s port %hu rejected\n", get_ip_str((struct sockaddr *)&client, host, sizeof(host)), get_port((struct sockaddr *)&client));
			close(fd);
			continue;
		}
#endif
		dolog(LOG_NOTICE, "Connection from %s port %hu accepted\n", get_ip_str((struct sockaddr *)&client, host, sizeof(host)), get_port((struct sockaddr *)&client));
		/*write(fd, "Printing", 8); */

		/* Make sure lp device is open... */
		while ((lp = open_printer(lpnumber)) == -1) {
			sleep(open_sleep);
			if (open_sleep < 320) /* ~5 min interval to avoid spam in syslog */
				open_sleep *= 2;
		}
		open_sleep = 10;

		if (copy_stream(fd, lp) < 0)
			dolog(LOGOPTS, "copy_stream: %m\n");
		(void)close(fd);
		(void)close(lp);
	}
	dolog(LOGOPTS, "accept: %m\n");
	free_lock();
	exit(1);
}
示例#8
0
static int qpa_init_out(HWVoiceOut *hw, struct audsettings *as,
                        void *drv_opaque)
{
    int error;
    pa_sample_spec ss;
    pa_buffer_attr ba;
    struct audsettings obt_as = *as;
    PAVoiceOut *pa = (PAVoiceOut *) hw;
    paaudio *g = pa->g = drv_opaque;
    AudiodevPaOptions *popts = &g->dev->u.pa;
    AudiodevPaPerDirectionOptions *ppdo = popts->out;

    ss.format = audfmt_to_pa (as->fmt, as->endianness);
    ss.channels = as->nchannels;
    ss.rate = as->freq;

    /*
     * qemu audio tick runs at 100 Hz (by default), so processing
     * data chunks worth 10 ms of sound should be a good fit.
     */
    ba.tlength = pa_usec_to_bytes (10 * 1000, &ss);
    ba.minreq = pa_usec_to_bytes (5 * 1000, &ss);
    ba.maxlength = -1;
    ba.prebuf = -1;

    obt_as.fmt = pa_to_audfmt (ss.format, &obt_as.endianness);

    pa->stream = qpa_simple_new (
        g,
        "qemu",
        PA_STREAM_PLAYBACK,
        ppdo->has_name ? ppdo->name : NULL,
        &ss,
        NULL,                   /* channel map */
        &ba,                    /* buffering attributes */
        &error
        );
    if (!pa->stream) {
        qpa_logerr (error, "pa_simple_new for playback failed\n");
        goto fail1;
    }

    audio_pcm_init_info (&hw->info, &obt_as);
    hw->samples = pa->samples = audio_buffer_samples(
        qapi_AudiodevPaPerDirectionOptions_base(ppdo), &obt_as, 46440);
    pa->pcm_buf = audio_calloc(__func__, hw->samples, 1 << hw->info.shift);
    pa->rpos = hw->rpos;
    if (!pa->pcm_buf) {
        dolog ("Could not allocate buffer (%d bytes)\n",
               hw->samples << hw->info.shift);
        goto fail2;
    }

    if (audio_pt_init(&pa->pt, qpa_thread_out, hw, AUDIO_CAP, __func__)) {
        goto fail3;
    }

    return 0;

 fail3:
    g_free (pa->pcm_buf);
    pa->pcm_buf = NULL;
 fail2:
    if (pa->stream) {
        pa_stream_unref (pa->stream);
        pa->stream = NULL;
    }
 fail1:
    return -1;
}
示例#9
0
/*---------------------------------------------------------------------------*
 *	re-open the log/acct files on SIGUSR1
 *---------------------------------------------------------------------------*/
void
reopenfiles(int dummy)
{
        if(useacctfile)
	{
		/* close file */

		if(acctfp)
		{
		        fflush(acctfp);
		        fclose(acctfp);
		}

	        /* if user specified a suffix, rename the old file */

	        if(rotatesuffix[0] != '\0')
	        {
	        	char filename[MAXPATHLEN];

	        	snprintf(filename, sizeof(filename), "%s%s", acctfile, rotatesuffix);

			if((rename(acctfile, filename)) != 0)
			{
				dolog(LL_ERR, "reopenfiles: acct rename failed, cause = %s", strerror(errno));
				error_exit(1, "reopenfiles: acct rename failed, cause = %s", strerror(errno));
			}
		}

		if((acctfp = fopen(acctfile, "a")) == NULL)
		{
			dolog(LL_ERR, "ERROR, can't open acctfile %s for writing, terminating!", acctfile);
			error_exit(1, "ERROR, can't open acctfile %s for writing, terminating!", acctfile);
		}
		setvbuf(acctfp, NULL, _IONBF, 0);
	}

	if(uselogfile)
	{
	        finish_log();

	        /* if user specified a suffix, rename the old file */

	        if(rotatesuffix[0] != '\0')
	        {
	        	char filename[MAXPATHLEN];

	        	snprintf(filename, sizeof(filename), "%s%s", logfile, rotatesuffix);

			if((rename(logfile, filename)) != 0)
			{
				dolog(LL_ERR, "reopenfiles: log rename failed, cause = %s", strerror(errno));
				error_exit(1, "reopenfiles: log rename failed, cause = %s", strerror(errno));
			}
		}

	        if((logfp = fopen(logfile, "a")) == NULL)
		{
			fprintf(stderr, "ERROR, cannot open logfile %s: %s\n",
				logfile, strerror(errno));
			error_exit(1, "reopenfiles: ERROR, cannot open logfile %s: %s\n",
				logfile, strerror(errno));
		}

		/* set unbuffered operation */

		setvbuf(logfp, NULL, _IONBF, 0);
	}
}
示例#10
0
/*---------------------------------------------------------------------------*
 *	main loop
 *---------------------------------------------------------------------------*/
static void
mloop(
#ifdef I4B_EXTERNAL_MONITOR
	int localmonitor
#ifndef I4B_NOTCPIP_MONITOR
	, int remotemonitor
#endif
#endif
)
{
	fd_set set;
	struct timeval timeout;
	int ret;
	int high_selfd;

 	/* go into loop */

	dolog(LL_DMN, "i4b isdn daemon started (pid = %d)", getpid());

	for(;;)
	{
		FD_ZERO(&set);

#ifdef USE_CURSES
		if(do_fullscreen)
			FD_SET(fileno(stdin), &set);
#endif

		FD_SET(isdnfd, &set);

		high_selfd = isdnfd;

#ifdef I4B_EXTERNAL_MONITOR
		if(do_monitor)
		{
			if (localmonitor != -1) {
				/* always watch for new connections */
				FD_SET(localmonitor, &set);
				if(localmonitor > high_selfd)
					high_selfd = localmonitor;
			}
#ifndef I4B_NOTCPIP_MONITOR
			if (remotemonitor != -1) {
				FD_SET(remotemonitor, &set);
				if(remotemonitor > high_selfd)
					high_selfd = remotemonitor;
			}
#endif

			/* if there are client connections, let monitor module
			 * enter them into the fdset */
			if(accepted)
			{
				monitor_prepselect(&set, &high_selfd);
			}
		}
#endif

		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		ret = select(high_selfd + 1, &set, NULL, NULL, &timeout);

		if(ret > 0)
		{
			if(FD_ISSET(isdnfd, &set))
				isdnrdhdl();

#ifdef USE_CURSES
			if(FD_ISSET(fileno(stdin), &set))
				kbdrdhdl();
#endif

#ifdef I4B_EXTERNAL_MONITOR
			if(do_monitor)
			{
				if(localmonitor != -1 && FD_ISSET(localmonitor, &set))
					monitor_handle_connect(localmonitor, 1);

#ifndef I4B_NOTCPIP_MONITOR
				if(remotemonitor != -1 && FD_ISSET(remotemonitor, &set))
					monitor_handle_connect(remotemonitor, 0);
#endif
				if(accepted)
					monitor_handle_input(&set);
			}
#endif
		}
		else if(ret == -1)
		{
			if(errno != EINTR)
			{
				dolog(LL_ERR, "mloop: ERROR, select error on isdn device, errno = %d!", errno);
				error_exit(1, "mloop: ERROR, select error on isdn device, errno = %d!", errno);
			}
		}

		/* handle timeout and recovery */

		handle_recovery();
	}
}
示例#11
0
/* Accept a message from the reservation protocol and take
 * appropriate action.
 */
static void
rsrr_accept(int recvlen)
{
    struct rsrr_header *rsrr;
    struct rsrr_rq *route_query;
    
    if (recvlen < RSRR_HEADER_LEN) {
	dolog(LOG_WARNING, 0,
	    "Received RSRR packet of %d bytes, which is less than min size",
	    recvlen);
	return;
    }
    
    rsrr = (struct rsrr_header *) rsrr_recv_buf;
    
    if (rsrr->version > RSRR_MAX_VERSION) {
	dolog(LOG_WARNING, 0,
	    "Received RSRR packet version %d, which I don't understand",
	    rsrr->version);
	return;
    }
    
    switch (rsrr->version) {
      case 1:
	switch (rsrr->type) {
	  case RSRR_INITIAL_QUERY:
	    /* Send Initial Reply to client */
	    IF_DEBUG(DEBUG_RSRR)
	    dolog(LOG_DEBUG, 0, "Received Initial Query\n");
	    rsrr_accept_iq();
	    break;
	  case RSRR_ROUTE_QUERY:
	    /* Check size */
	    if (recvlen < RSRR_RQ_LEN) {
		dolog(LOG_WARNING, 0,
		    "Received Route Query of %d bytes, which is too small",
		    recvlen);
		break;
	    }
	    /* Get the query */
	    route_query = (struct rsrr_rq *) (rsrr_recv_buf + RSRR_HEADER_LEN);
	    IF_DEBUG(DEBUG_RSRR)
	    dolog(LOG_DEBUG, 0,
		"Received Route Query for src %s grp %s notification %d",
		inet_fmt(route_query->source_addr.s_addr, s1),
		inet_fmt(route_query->dest_addr.s_addr,s2),
		BIT_TST(rsrr->flags,RSRR_NOTIFICATION_BIT));
	    /* Send Route Reply to client */
	    rsrr_accept_rq(route_query,rsrr->flags,NULL);
	    break;
	  default:
	    dolog(LOG_WARNING, 0,
		"Received RSRR packet type %d, which I don't handle",
		rsrr->type);
	    break;
	}
	break;
	
      default:
	dolog(LOG_WARNING, 0,
	    "Received RSRR packet version %d, which I don't understand",
	    rsrr->version);
	break;
    }
}
示例#12
0
void print_stats(void)
{
	s4    i;
	float f;
	s4    sum;


	// DONE
	dolog("Number of JIT compiler calls: %6d", count_jit_calls);
	// DONE
	dolog("Number of compiled methods:   %6d", count_methods);

	// DONE
	dolog("Number of compiled basic blocks:               %6d",
		  count_basic_blocks);
	// DONE
	dolog("Number of max. basic blocks per method:        %6d",
		  count_max_basic_blocks);

	// DONE
	dolog("Number of compiled JavaVM instructions:        %6d",
		  count_javainstr);
	// DONE
	dolog("Number of max. JavaVM instructions per method: %6d",
		  count_max_javainstr);
	// PARTLY DONE
	dolog("Size of compiled JavaVM instructions:          %6d(%d)",
		  count_javacodesize, count_javacodesize - count_methods * 18);

	// DONE
	dolog("Size of compiled Exception Tables:      %d", count_javaexcsize);
	// XXX 4 byte instructions hardcoded oO. I guess this is no longer valid.
	dolog("Number of Machine-Instructions: %d", count_code_len >> 2);
	// DONE
	dolog("Number of Spills (write to memory) <all [i/l/a|flt|dbl]>: %d [%d|%d|%d]",
		count_spills_write_ila + count_spills_write_flt + count_spills_write_dbl,
		count_spills_write_ila, count_spills_write_flt, count_spills_write_dbl);
	// DONE
	dolog("Number of Spills (read from memory) <all [i/l/a|flt|dbl]>: %d [%d|%d|%d]",
		count_spills_read_ila + count_spills_read_flt + count_spills_read_dbl,
		count_spills_read_ila, count_spills_read_flt, count_spills_read_dbl);
	// NOT used?!
	dolog("Number of Activ    Pseudocommands: %6d", count_pcmd_activ);
	// NOT used?!
	dolog("Number of Drop     Pseudocommands: %6d", count_pcmd_drop);
	// DONE
	dolog("Number of Const    Pseudocommands: %6d (zero:%5d)",
		  count_pcmd_load, count_pcmd_zero);
	// NOT used?!
	dolog("Number of ConstAlu Pseudocommands: %6d (cmp: %5d, store:%5d)",
		  count_pcmd_const_alu, count_pcmd_const_bra, count_pcmd_const_store);
	// NOT used?!
	dolog("Number of Move     Pseudocommands: %6d", count_pcmd_move);
	// DONE
	dolog("Number of Load     Pseudocommands: %6d", count_load_instruction);
	// DONE
	// count_pcmd_store_comb NOT used?!
	dolog("Number of Store    Pseudocommands: %6d (combined: %5d)",
		  count_pcmd_store, count_pcmd_store - count_pcmd_store_comb);
	// DONE
	dolog("Number of OP       Pseudocommands: %6d", count_pcmd_op);
	// DONE
	dolog("Number of DUP      Pseudocommands: %6d", count_dup_instruction);
	// DONE
	dolog("Number of Mem      Pseudocommands: %6d", count_pcmd_mem);
	// DONE
	dolog("Number of Method   Pseudocommands: %6d", count_pcmd_met);
	// DONE
	dolog("Number of Branch   Pseudocommands: %6d (rets:%5d, Xrets: %5d)",
		  count_pcmd_bra, count_pcmd_return, count_pcmd_returnx);
	// DONE
	log_println("                resolved branches: %6d", count_branches_resolved);
	// DONE
	log_println("              unresolved branches: %6d", count_branches_unresolved);
	// DONE
	dolog("Number of Table    Pseudocommands: %6d", count_pcmd_table);
	dolog("Number of Useful   Pseudocommands: %6d", count_pcmd_table +
		  count_pcmd_bra + count_pcmd_load + count_pcmd_mem + count_pcmd_op);
	// DONE
	dolog("Number of Null Pointer Checks:     %6d", count_check_null);
	// DONE
	dolog("Number of Array Bound Checks:      %6d", count_check_bound);
	// DONE
	dolog("Number of Try-Blocks: %d", count_tryblocks);

	// DONE
	dolog("Number of branch_emit (total, 8bit/16bit/32bit/64bit offset): %d, %d/%d/%d/%d",
		count_emit_branch,  count_emit_branch_8bit,  count_emit_branch_16bit,
							count_emit_branch_32bit, count_emit_branch_64bit);

	// DONE
	dolog("Maximal count of stack elements:   %d", count_max_new_stack);
	// DONE
	dolog("Upper bound of max stack elements: %d", count_upper_bound_new_stack);
	// DONE
	dolog("Distribution of stack sizes at block boundary");
	dolog("     0     1     2     3     4     5     6     7     8     9  >=10");
	dolog("%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d",
		  count_block_stack[0], count_block_stack[1], count_block_stack[2],
		  count_block_stack[3], count_block_stack[4], count_block_stack[5],
		  count_block_stack[6], count_block_stack[7], count_block_stack[8],
		  count_block_stack[9], count_block_stack[10]);
	// DONE
	dolog("Distribution of store stack depth");
	dolog("     0     1     2     3     4     5     6     7     8     9  >=10");
	dolog("%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d",
		  count_store_depth[0], count_store_depth[1], count_store_depth[2],
		  count_store_depth[3], count_store_depth[4], count_store_depth[5],
		  count_store_depth[6], count_store_depth[7], count_store_depth[8],
		  count_store_depth[9], count_store_depth[10]);
	dolog("Distribution of store creator chains first part");
	dolog("     0     1     2     3     4     5     6     7     8     9");
	// DONE
	dolog("%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d",
		  count_store_length[0], count_store_length[1], count_store_length[2],
		  count_store_length[3], count_store_length[4], count_store_length[5],
		  count_store_length[6], count_store_length[7], count_store_length[8],
		  count_store_length[9]);
	// DONE
	dolog("Distribution of store creator chains second part");
	dolog("    10    11    12    13    14    15    16    17    18    19  >=20");
	dolog("%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d",
		  count_store_length[10], count_store_length[11],
		  count_store_length[12], count_store_length[13],
		  count_store_length[14], count_store_length[15],
		  count_store_length[16], count_store_length[17],
		  count_store_length[18], count_store_length[19],
		  count_store_length[20]);
	// DONE
	dolog("Distribution of analysis iterations");
	dolog("     1     2     3     4   >=5");
	dolog("%6d%6d%6d%6d%6d",
		  count_analyse_iterations[0], count_analyse_iterations[1],
		  count_analyse_iterations[2], count_analyse_iterations[3],
		  count_analyse_iterations[4]);


	/* Distribution of basic blocks per method ********************************/

	// DONE
	log_println("Distribution of basic blocks per method:");
	log_println("   <=5  <=10  <=15  <=20  <=30  <=40  <=50  <=75   >75");

	log_start();
	for (i = 0; i <= 8; i++)
		log_print("%6d", count_method_bb_distribution[i]);
	log_finish();

	/* print ratio */

	f = (float) count_methods;

	log_start();
	for (i = 0; i <= 8; i++)
		log_print("%6.2f", (float) count_method_bb_distribution[i] / f);
	log_finish();

	/* print cumulated ratio */

	log_start();
	for (i = 0, sum = 0; i <= 8; i++) {
		sum += count_method_bb_distribution[i];
		log_print("%6.2f", (float) sum / f);
	}
	log_finish();


	/* Distribution of basic block sizes **************************************/

	// DONE
	log_println("Distribution of basic block sizes:");
	log_println("     0     1     2     3     4     5     6     7     8     9   <13   <15   <17   <19   <21   <26   <31   >30");

	/* print block sizes */

	log_start();
	for (i = 0; i <= 17; i++)
		log_print("%6d", count_block_size_distribution[i]);
	log_finish();

	/* print ratio */

	f = (float) count_basic_blocks;

	log_start();
	for (i = 0; i <= 17; i++)
		log_print("%6.2f", (float) count_block_size_distribution[i] / f);
	log_finish();

	/* print cumulated ratio */

	log_start();
	for (i = 0, sum = 0; i <= 17; i++) {
		sum += count_block_size_distribution[i];
		log_print("%6.2f", (float) sum / f);
	}
	log_finish();

	// DONE
	statistics_print_memory_usage();

	// DONE
	dolog("Number of class loads:    %6d", count_class_loads);
	// DONE
	dolog("Number of class inits:    %6d", count_class_inits);
	// DONE
	dolog("Number of loaded Methods: %6d\n", count_all_methods);

	// DONE
	dolog("Calls of utf_new:                 %6d", count_utf_new);
	// NOT used?!
	dolog("Calls of utf_new (element found): %6d\n", count_utf_new_found);


	/* LSRA statistics ********************************************************/

	// DONE
	dolog("Moves reg -> reg:     %6d", count_mov_reg_reg);
	// DONE
	dolog("Moves mem -> reg:     %6d", count_mov_mem_reg);
	// DONE
	dolog("Moves reg -> mem:     %6d", count_mov_reg_mem);
	// DONE
	dolog("Moves mem -> mem:     %6d", count_mov_mem_mem);

	// DONE
	dolog("Methods allocated by LSRA:         %6d",
		  count_methods_allocated_by_lsra);
	// DONE
	dolog("Conflicts between local Variables: %6d", count_locals_conflicts);
	// DONE
	dolog("Local Variables held in Memory:    %6d", count_locals_spilled);
	// DONE
	dolog("Local Variables held in Registers: %6d", count_locals_register);
	// DONE
	dolog("Stackslots held in Memory:         %6d", count_ss_spilled);
	// DONE
	dolog("Stackslots held in Registers:      %6d", count_ss_register);
	// not used!?
	dolog("Memory moves at BB Boundaries:     %6d", count_mem_move_bb);
	// DONE
	dolog("Number of interface slots:         %6d\n", count_interface_size);
	// DONE
	dolog("Number of Argument stack slots in register:  %6d",
		  count_argument_reg_ss);
	// DONE
	dolog("Number of Argument stack slots in memory:    %6d\n",
		  count_argument_mem_ss);
	// DONE
	dolog("Number of Methods kept in registers:         %6d\n",
		  count_method_in_register);


	/* instruction scheduler statistics ***************************************/

#if defined(USE_SCHEDULER)
	dolog("Instruction scheduler statistics:");
	dolog("Number of basic blocks:       %7d", count_schedule_basic_blocks);
	dolog("Number of nodes:              %7d", count_schedule_nodes);
	dolog("Number of leaders nodes:      %7d", count_schedule_leaders);
	dolog("Number of max. leaders nodes: %7d", count_schedule_max_leaders);
	dolog("Length of critical path:      %7d\n", count_schedule_critical_path);
#endif


	/* call statistics ********************************************************/

	dolog("Function call statistics:");
	// DONE
	dolog("Number of jni->CallXMethod function invokations: %ld",
		  count_jni_callXmethod_calls);
	// DONE
	dolog("Overall number of jni invokations:               %ld",
		  count_jni_calls);

	// DONE
	log_println("java-to-native calls:   %10ld", count_calls_java_to_native);
	// DONE
	log_println("native-to-java calls:   %10ld", count_calls_native_to_java);


	/* now print other statistics ********************************************/

#if defined(ENABLE_INTRP)
	print_dynamic_super_statistics();
#endif
}
int
main(int argc, char * const argv[])
{
	char **vec;
	unsigned int num;
	char *s;
	int state;
	char *sstate;
	char *p;
	char buf[80];
	int type = DEVTYPE_UNKNOWN;
	int ch;
	int debug_fd;
	FILE *pidfile_f;

	while ((ch = getopt(argc, argv, "dfl:p:s:")) != -1) {
		switch (ch) {
		case 'd':
			dflag = 1;
			break;
		case 'f':
			fflag = 1;
			break;
		case 'l':
			log_file = optarg;
			break;
		case 'p':
			pidfile = pidfile;
		case 's':
			vbd_script = optarg;
			break;
		default:
			usage();
		}
	}

	if (vbd_script == NULL)
		vbd_script = VBD_SCRIPT;
	if (pidfile == NULL)
		pidfile = PID_FILE;
	if (log_file == NULL)
		log_file = LOG_FILE;

	openlog("xenbackendd", LOG_PID | LOG_NDELAY, LOG_DAEMON);

	if (fflag == 0) {
		/* open log file */
		debug_fd = open(log_file, O_RDWR | O_CREAT | O_TRUNC, 0644);
		if (debug_fd == -1) {
			dolog(LOG_ERR, "can't open %s: %s",
			    log_file, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	if (fflag == 0) {
		/* daemonize */
		pidfile_f = fopen(pidfile, "w");
		if (pidfile_f == NULL) {
			dolog(LOG_ERR, "can't open %s: %s",
			    pidfile, strerror(errno));
			exit(EXIT_FAILURE);
		}
		if (daemon(0, 0) < 0) {
			dolog(LOG_ERR, "can't daemonize: %s",
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
		fprintf(pidfile_f, "%d\n", (int)getpid());
		fclose(pidfile_f);

		/* redirect stderr to log file */
		if (dup2(debug_fd, STDERR_FILENO) < 0) {
			dolog(LOG_ERR, "can't redirect stderr to %s: %s\n",
			    log_file, strerror(errno));
			exit(EXIT_FAILURE);
		}

		/* also redirect stdout if we're in debug mode */
		if (dflag) {
			if (dup2(debug_fd, STDOUT_FILENO) < 0) {
				dolog(LOG_ERR,
				    "can't redirect stdout to %s: %s\n",
				    log_file, strerror(errno));
				exit(EXIT_FAILURE);
			}
		}

		close(debug_fd);
		debug_fd = -1;
	}

	if (xen_setup() < 0)
		exit(EXIT_FAILURE);

	for (;;) {
		vec = xs_read_watch(xs, &num);
		if (!vec) {
			dolog(LOG_ERR, "xs_read_watch: NULL\n");
			continue;
		}

		if (strlen(vec[XS_WATCH_PATH]) < sizeof("state"))
			goto next1;

		/* find last component of path, check if it's "state" */
		p = &vec[XS_WATCH_PATH][
		    strlen(vec[XS_WATCH_PATH]) - sizeof("state")];
		if (p[0] != '/')
			goto next1;
		p[0] = '\0';
		p++;
		if (strcmp(p, "state") != 0)
			goto next1;

		snprintf(buf, sizeof(buf), "%s/state", vec[XS_WATCH_PATH]);
		sstate = xs_read(xs, XBT_NULL, buf, 0);
		if (sstate == NULL) {
			dolog(LOG_ERR,
			    "Failed to read %s (%s)", buf, strerror(errno));
			goto next1;
		}

		state = atoi(sstate);
		snprintf(buf, sizeof(buf), "%s/hotplug-status",
		    vec[XS_WATCH_PATH]);
		s = xs_read(xs, XBT_NULL, buf, 0);
		if (s != NULL && state != 6 /* XenbusStateClosed */)
			goto next2;

		if (strncmp(vec[XS_WATCH_PATH],
		    DOMAIN_PATH "/backend/vif",
		    strlen(DOMAIN_PATH "/backend/vif")) == 0)
			type = DEVTYPE_VIF;

		if (strncmp(vec[XS_WATCH_PATH],
		    DOMAIN_PATH "/backend/vbd",
		    strlen(DOMAIN_PATH "/backend/vbd")) == 0)
			type = DEVTYPE_VBD;

		switch(type) {
		case DEVTYPE_VIF:
			if (s)
				free(s);
			snprintf(buf, sizeof(buf), "%s/script",
			    vec[XS_WATCH_PATH]);
			s = xs_read(xs, XBT_NULL, buf, 0);
			if (s == NULL) {
				dolog(LOG_ERR,
				    "Failed to read %s (%s)", buf,
				    strerror(errno));
				goto next2;
			}
			doexec(s, vec[XS_WATCH_PATH], sstate);
			break;

		case DEVTYPE_VBD:
			doexec(vbd_script, vec[XS_WATCH_PATH], sstate);
			break;

		default:
			break;
		}

next2:
		if (s)
			free(s);
		free(sstate);

next1:
		free(vec);
	}

	return 0;
}
示例#14
0
static BOOL sigterm_testing(DWORD sig)
{
	D(dolog(LOG_DEBUG, "Ignoring CTRL event\n"));
	return true;
}
示例#15
0
static BOOL sigterm(DWORD sig)
{
	D(dolog(LOG_DEBUG, "Terminating due to CTRL event\n"));
	g_aiccu->running = false;
	return true;
}
示例#16
0
char *plugin_load(char *file) 
{
	void *h;
	char *err;
	int i, *type = 0;
	struct subwin *sb[] = { &sub_proc, &sub_user, &sub_main };
	struct subwin *target;
AGAIN:	
	if(!(h = dlopen(file, RTLD_LAZY))) {
		snprintf(dlerr, sizeof dlerr, "%s", dlerror());
		return dlerr;
	}
	dolog("%s: dlopen returned %x\n", __FUNCTION__, h);
	/* 
	 * Check if the same plugin has been loaded. 
	 * Plugin's name could be the same but code could be different.
	 * If so, then probably it has changed so we have to unload it
	 * twice and load again. Ses dlopen(3) for reasons of doing this.
	 */
	for(i = 0; i < sizeof sb/sizeof(struct subwin *); i++) {
		if(sb[i]->handle == h) {
			dolog("%s: subwin %d has handle %x\n",
				__FUNCTION__, i, sb[i]->handle); 		
			dlclose(h);
			dlclose(sb[i]->handle);
			dolog("%s: plugin already loaded in subwin %d, count %d\n",
				__FUNCTION__, i, i);
			sb[i]->handle = h = 0;
			goto AGAIN;
		break;
		}
	}	
	type = dlsym(h, "plugin_type");
	if((err = dlerror())) goto ERROR;	
	if(*type >= SUBWIN_NR) {
		snprintf(dlerr, sizeof dlerr, "Unknown plugin type [%d]", *type);
		dlclose(h);
		return dlerr;
	}	
	target = sb[*type];
	target->plugin_init = dlsym(h, "plugin_init");
	if((err = dlerror())) goto ERROR;
	target->plugin_draw = dlsym(h, "plugin_draw");
	if((err = dlerror())) goto ERROR;
	target->plugin_clear = dlsym(h, "plugin_clear");
	target->plugin_cleanup = dlsym(h, "plugin_cleanup");
	/* close previous library if it was loaded */
	if(target->handle) {
		int i;
		i = dlclose(target->handle);
		dolog("%s: closing prev library: %d %s\n",
			__FUNCTION__, i, dlerror());
	}
	dolog("%s: plugin loaded\n", __FUNCTION__);
	target->handle = h;
	target->flags = target->plugin_init(on_cursor());
	return 0;
ERROR:
	dolog("%s: plugin not loaded\n", __FUNCTION__);
	snprintf(dlerr, sizeof dlerr, "%s", err);
	dlclose(h);
	return dlerr;
}		
示例#17
0
/*---------------------------------------------------------------------------*
 *	program entry
 *---------------------------------------------------------------------------*/
int
main(int argc, char **argv)
{
	int i;
	msg_vr_req_t mvr;

#ifdef I4B_EXTERNAL_MONITOR
	int sockfd = -1;		/* local monitor socket */
#ifndef I4B_NOTCPIP_MONITOR
	int remotesockfd = -1;		/* tcp/ip monitor socket */
#endif
#endif

	setlocale (LC_ALL, "");

	while ((i = getopt(argc, argv, "mc:d:fFlL:Pr:s:t:u:")) != -1)
	{
		switch (i)
		{
#ifdef I4B_EXTERNAL_MONITOR
			case 'm':
				inhibit_monitor = 1;
				break;
#endif

			case 'c':
				configfile = optarg;
				break;

#ifdef DEBUG
			case 'd':
				if(*optarg == 'n')
					debug_noscreen = 1;
				else if((sscanf(optarg, "%i", &debug_flags)) == 1)
					do_debug = 1;
				else
					usage();
				break;
#endif

			case 'f':
				do_fullscreen = 1;
				do_fork = 0;
#ifndef USE_CURSES
				fprintf(stderr, "Sorry, no fullscreen mode available - daemon compiled without USE_CURSES\n");
				exit(1);
#endif
				break;

			case 'F':
				do_fork = 0;
				break;

			case 'l':
				uselogfile = 1;
				break;

			case 'L':
				strlcpy(logfile, optarg, sizeof(logfile));
				break;

			case 'P':
				do_print = 1;
				break;

			case 'r':
				rdev = optarg;
				do_rdev = 1;
				break;

			case 's':
				if(isdigit(*optarg))
				{
					int facility;
					logfacility = strtoul(optarg, NULL, 10);
					facility = logfacility << 3;

					if((facility < LOG_KERN) ||
					   (facility > LOG_FTP && facility < LOG_LOCAL0) ||
					   (facility > LOG_LOCAL7))
					{
						fprintf(stderr, "Error, option -s has invalid logging facility %d", logfacility);
						usage();
					}
					logfacility = facility;
				}
				else
				{
					fprintf(stderr, "Error: option -s requires a numeric argument!\n");
					usage();
				}
				break;

			case 't':
				ttype = optarg;
				do_ttytype = 1;
				break;

			case 'u':
				if(isdigit(*optarg))
				{
					unit_length = strtoul(optarg, NULL, 10);
					if(unit_length < ULSRC_CMDLMIN)
						unit_length = ULSRC_CMDLMIN;
					else if(unit_length > ULSRC_CMDLMAX)
						unit_length = ULSRC_CMDLMAX;
					got_unitlen = 1;
				}
				else
				{
					fprintf(stderr, "Error: option -T requires a numeric argument!\n");
					usage();
				}
				break;

			case '?':
			default:
				usage();
				break;
		}
	}
#ifdef DEBUG
	if(!do_debug)
		debug_noscreen = 0;
#endif

	if(!do_print)
	{
		umask(UMASK);	/* set our umask ... */

		init_log();	/* initialize the logging subsystem */
	}

	check_pid();	/* check if we are already running */

	if(!do_print)
	{
		if(do_fork || (do_fullscreen && do_rdev)) /* daemon mode ? */
			daemonize();

		write_pid();	/* write our pid to file */

		/* set signal handler(s) */

		signal(SIGCHLD, sigchild_handler); /* process handling	*/
		signal(SIGHUP,  rereadconfig);	/* reread configuration	*/
		signal(SIGUSR1, reopenfiles);	/* reopen acct/log files*/
		signal(SIGPIPE, SIG_IGN);	/* handled manually	*/
		signal(SIGINT,  do_exit);	/* clean up on SIGINT	*/
		signal(SIGTERM, do_exit);	/* clean up on SIGTERM	*/
		signal(SIGQUIT, do_exit);	/* clean up on SIGQUIT	*/
	}

	/* open isdn device */

	if((isdnfd = open(I4BDEVICE, O_RDWR)) < 0)
	{
		dolog(LL_ERR, "main: cannot open %s: %s", I4BDEVICE, strerror(errno));
		exit(1);
	}

	/* check kernel and userland have same version/release numbers */

	if((ioctl(isdnfd, I4B_VR_REQ, &mvr)) < 0)
	{
		dolog(LL_ERR, "main: ioctl I4B_VR_REQ failed: %s", strerror(errno));
		do_exit(1);
	}

	if(mvr.version != VERSION)
	{
		dolog(LL_ERR, "main: version mismatch, kernel %d, daemon %d", mvr.version, VERSION);
		do_exit(1);
	}

	if(mvr.release != REL)
	{
		dolog(LL_ERR, "main: release mismatch, kernel %d, daemon %d", mvr.release, REL);
		do_exit(1);
	}

	if(mvr.step != STEP)
	{
		dolog(LL_ERR, "main: step mismatch, kernel %d, daemon %d", mvr.step, STEP);
		do_exit(1);
	}

	/* init controller state array */

	init_controller();

	/* read runtime configuration file and configure ourselves */

	configure(configfile, 0);

	if(config_error_flag)
	{
		dolog(LL_ERR, "there were %d error(s) in the configuration file, terminating!", config_error_flag);
		exit(1);
	}

	/* set controller ISDN protocol */

	init_controller_protocol();

	/* init active controllers, if any */

	signal(SIGCHLD, SIG_IGN);		/*XXX*/

	init_active_controller();

	signal(SIGCHLD, sigchild_handler);	/*XXX*/

	/* handle the rates stuff */

	if((i = readrates(ratesfile)) == ERROR)
	{
		if(rate_error != NULL)
			dolog(LL_ERR, "%s", rate_error);
		exit(1);
	}

	if(i == GOOD)
	{
		got_rate = 1;	/* flag, ratesfile read and ok */
		DBGL(DL_RCCF, (dolog(LL_DBG, "ratesfile %s read successfully", ratesfile)));
	}
	else
	{
		if(rate_error != NULL)
			dolog(LL_WRN, "%s", rate_error);
	}

	/* if writing accounting info, open file, set unbuffered */

	if(useacctfile)
	{
		if((acctfp = fopen(acctfile, "a")) == NULL)
		{
			dolog(LL_ERR, "ERROR, can't open acctfile %s for writing, terminating!", acctfile);
			exit(1);
		}
		setvbuf(acctfp, NULL, _IONBF, 0);
	}

	/* initialize alias processing */

	if(aliasing)
		init_alias(aliasfile);

	/* init holidays */

	init_holidays(holidayfile);

	/* init remote monitoring */

#ifdef I4B_EXTERNAL_MONITOR
	if(do_monitor)
	{
		monitor_init();
		sockfd = monitor_create_local_socket();
#ifndef I4B_NOTCPIP_MONITOR
		remotesockfd = monitor_create_remote_socket(monitorport);
#endif
	}
#endif

	/* in case fullscreendisplay, initialize */

#ifdef USE_CURSES
	if(do_fullscreen)
	{
		init_screen();
	}
#endif

	/* init realtime priority */

#ifdef USE_RTPRIO
  	if(rt_prio != RTPRIO_NOTUSED)
  	{
  		struct rtprio rtp;

  		rtp.type = RTP_PRIO_REALTIME;
  		rtp.prio = rt_prio;

  		if((rtprio(RTP_SET, getpid(), &rtp)) == -1)
  		{
			dolog(LL_ERR, "rtprio failed: %s", strerror(errno));
			do_exit(1);
		}
	}
#endif

	starttime = time(NULL);	/* get starttime */

	srandom(580403);	/* init random number gen */

	mloop(		/* enter loop of no return .. */
#ifdef I4B_EXTERNAL_MONITOR
		sockfd
#ifndef I4B_NOTCPIP_MONITOR
		, remotesockfd
#endif
#endif
		);
	do_exit(0);
	return(0);
}
示例#18
0
void load_config(const char *config, config_t *pconfig)
{
	char *dummy = strdup(config);

	char *cur_dir_dummy = dirname(dummy);
	char *cur_dir = realpath(cur_dir_dummy, NULL);

        int linenr = 0;
        FILE *fh = fopen(config, "r");
        if (!fh)
                error_exit("error opening configuration file '%s'", config);

	/* set defaults */
	pconfig -> max_number_of_mem_pools = 14;
	pconfig -> max_number_of_disk_pools = 128;
	pconfig -> min_store_on_disk_n = 5;

	pconfig -> bitcount_estimator = BCE_SHANNON;

	pconfig -> listen_adapter    = "0.0.0.0";
	pconfig -> listen_port       = DEFAULT_BROKER_PORT;
	pconfig -> listen_queue_size = 64;
	pconfig -> disable_nagle     = false;
	pconfig -> enable_keepalive  = true;

	pconfig -> reset_counters_interval    = 60;
	pconfig -> statistics_interval        = 300;
	pconfig -> ping_interval              = 601;
	pconfig -> kernelpool_filled_interval = 3600;

	pconfig -> stats_file = NULL;

	pconfig -> communication_timeout              = 15.0;
	pconfig -> communication_session_timeout      = 3600.0; /* 0 for no timeout */
	pconfig -> default_sleep_time_when_pools_full = 10;
	pconfig -> default_sleep_when_pools_empty     = 16;
	pconfig -> default_max_sleep_when_pools_empty = 60;
	pconfig -> when_pools_full_allow_submit_interval = 15;
	pconfig -> max_open_files = 1024;

	pconfig -> default_max_bits_per_interval = 16000000;

	pconfig -> ignore_rngtest_fips140 = false;
	pconfig -> ignore_rngtest_scc = false;
	pconfig -> scc_threshold = 0.2;

	pconfig -> allow_event_entropy_addition = true;
	pconfig -> add_entropy_even_if_all_full = false;
	pconfig -> allow_prng = false;

	pconfig -> user_map = new std::string("usermap.txt");

	pconfig -> pool_size_bytes = DEFAULT_POOL_SIZE_BITS / 8;

	pconfig -> prng_seed_file = NULL;

	pconfig -> max_get_put_size = 1249;

	pconfig -> ht = H_SHA512;
	pconfig -> st = S_BLOWFISH;

	pconfig -> rs = RS_CRYPTOPP;

	pconfig -> stream_cipher = "blowfish";
	pconfig -> mac_hasher = "md5";
	pconfig -> hash_hasher = "sha512";

	pconfig -> webserver_interface = "0.0.0.0";
	pconfig -> webserver_port = -1;

	pconfig -> graph_font = strdup(FONT);

	pconfig -> default_max_get_bps = 4096;

        for(;;)
        {
		double parvald;
		int parval;
                char read_buffer[4096], *lf, *par;
                char *cmd = fgets(read_buffer, sizeof read_buffer, fh), *is;
                if (!cmd)
                        break;
                linenr++;

                if (read_buffer[0] == '#' || read_buffer[0] == ';')
                        continue;

		while(*cmd == ' ') cmd++;

                lf = strchr(read_buffer, '\n');
                if (lf) *lf = 0x00;

		if (strlen(cmd) == 0)
			continue;

                is = strchr(read_buffer, '=');
                if (!is)
                        error_exit("invalid line at line %d: '=' missing", linenr);

                *is = 0x00;
                par = is + 1;
		while(*par == ' ') par++;
		parval = atoi(par);
		parvald = atof(par);

		is--;
		while(*is == ' ') { *is = 0x00 ; is--; }

		if (strcmp(cmd, "max_number_of_mem_pools") == 0)
			pconfig -> max_number_of_mem_pools = parval;
		else if (strcmp(cmd, "max_number_of_disk_pools") == 0)
			pconfig -> max_number_of_disk_pools = parval;
		else if (strcmp(cmd, "min_store_on_disk_n") == 0)
			pconfig -> min_store_on_disk_n = parval;
		else if (strcmp(cmd, "listen_adapter") == 0)
			pconfig -> listen_adapter = strdup(par);
		else if (strcmp(cmd, "graph_font") == 0)
			pconfig -> graph_font = strdup(par);
		else if (strcmp(cmd, "users") == 0)
		{
			char *p_file = static_cast<char *>(malloc(strlen(cur_dir) + strlen(par) + 1 + 1));
			if (par[0] == '/')
				strcpy(p_file, par);
			else
				sprintf(p_file, "%s/%s", cur_dir, par);
			dolog(LOG_INFO, "Load users from %s", p_file);
			delete pconfig -> user_map;
			pconfig -> user_map = new std::string(p_file);
			free(p_file);
		}
		else if (strcmp(cmd, "bitcount_estimator") == 0)
		{
			if (strcmp(par, "shannon") == 0)
				pconfig -> bitcount_estimator = BCE_SHANNON;
			else if (strcmp(par, "compression") == 0)
				pconfig -> bitcount_estimator = BCE_COMPRESSION;
			else
				error_exit("bitcount_estimator of type '%s' is not known", par);
		}
		else if (strcmp(cmd, "random_source") == 0)
		{
			if (strcmp(par, "cryptopp") == 0)
				pconfig -> rs = RS_CRYPTOPP;
			else if (strcmp(par, "dev_random") == 0)
				pconfig -> rs = RS_DEV_RANDOM;
			else if (strcmp(par, "dev_urandom") == 0)
				pconfig -> rs = RS_DEV_URANDOM;
			else
				error_exit("random_source of type '%s' is not known", par);
		}
		else if (strcmp(cmd, "listen_port") == 0)
			pconfig -> listen_port = parval;
		else if (strcmp(cmd, "listen_queue_size") == 0)
			pconfig -> listen_queue_size = parval;
		else if (strcmp(cmd, "default_max_get_bps") == 0)
			pconfig -> default_max_get_bps = parval;
		else if (strcmp(cmd, "max_open_files") == 0)
			pconfig -> max_open_files = parval;
		else if (strcmp(cmd, "webserver_interface") == 0)
			pconfig -> webserver_interface = par;
		else if (strcmp(cmd, "webserver_port") == 0)
			pconfig -> webserver_port = parval;
		else if (strcmp(cmd, "disable_nagle") == 0)
			pconfig -> disable_nagle = config_yes_no(par);
		else if (strcmp(cmd, "enable_keepalive") == 0)
			pconfig -> enable_keepalive = config_yes_no(par);
		else if (strcmp(cmd, "reset_counters_interval") == 0)
			pconfig -> reset_counters_interval = parval;
		else if (strcmp(cmd, "statistics_interval") == 0)
			pconfig -> statistics_interval = parval;
		else if (strcmp(cmd, "ping_interval") == 0)
			pconfig -> ping_interval = parval;
		else if (strcmp(cmd, "pool_size_in_bytes") == 0)
			pconfig -> pool_size_bytes = parval;
		else if (strcmp(cmd, "max_get_put_size") == 0)
			pconfig -> max_get_put_size = parval;
		else if (strcmp(cmd, "kernelpool_filled_interval") == 0)
			pconfig -> kernelpool_filled_interval = parval;
		else if (strcmp(cmd, "stats_file") == 0)
			pconfig -> stats_file = strdup(par);
		else if (strcmp(cmd, "stream_cipher") == 0)
			pconfig -> stream_cipher = par;
		else if (strcmp(cmd, "mac_hasher") == 0)
			pconfig -> mac_hasher = par;
		else if (strcmp(cmd, "hash_hasher") == 0)
			pconfig -> hash_hasher = par;
		else if (strcmp(cmd, "prng_seed_file") == 0)
		{
			char *p_file = static_cast<char *>(malloc(strlen(VAR_DIR) + strlen(par) + 1 + 1));
			if (par[0] == '/')
				strcpy(p_file, par);
			else
				sprintf(p_file, VAR_DIR "/%s", par);
			dolog(LOG_INFO, "Will load PRNG seed from %s", p_file);
			pconfig -> prng_seed_file = p_file;
		}
		else if (strcmp(cmd, "communication_timeout") == 0)
			pconfig -> communication_timeout = parvald;
		else if (strcmp(cmd, "communication_session_timeout") == 0)
			pconfig -> communication_session_timeout = parvald;
		else if (strcmp(cmd, "default_sleep_time_when_pools_full") == 0)
			pconfig -> default_sleep_time_when_pools_full = parval;
		else if (strcmp(cmd, "default_sleep_when_pools_empty") == 0)
			pconfig -> default_sleep_when_pools_empty = parval;
		else if (strcmp(cmd, "default_max_sleep_when_pools_empty") == 0)
			pconfig -> default_max_sleep_when_pools_empty = parval;
		else if (strcmp(cmd, "default_max_bits_per_interval") == 0)
			pconfig -> default_max_bits_per_interval = parval;
		else if (strcmp(cmd, "ignore_rngtest_fips140") == 0)
			pconfig -> ignore_rngtest_fips140 = config_yes_no(par);
		else if (strcmp(cmd, "ignore_rngtest_scc") == 0)
			pconfig -> ignore_rngtest_scc = config_yes_no(par);
		else if (strcmp(cmd, "allow_event_entropy_addition") == 0)
			pconfig -> allow_event_entropy_addition = config_yes_no(par);
		else if (strcmp(cmd, "add_entropy_even_if_all_full") == 0)
			pconfig -> add_entropy_even_if_all_full = config_yes_no(par);
		else if (strcmp(cmd, "allow_prng") == 0)
			pconfig -> allow_prng = config_yes_no(par);
		else if (strcmp(cmd, "scc_threshold") == 0)
			pconfig -> scc_threshold = parvald;
		else if (strcmp(cmd, "when_pools_full_allow_submit_interval") == 0)
			pconfig -> when_pools_full_allow_submit_interval = parval;
		else if (strcmp(cmd, "hash_type") == 0)
		{
			if (strcmp(par, "sha512") == 0)
				pconfig -> ht = H_SHA512;
			else if (strcmp(par, "md5") == 0)
				pconfig -> ht = H_MD5;
			else if (strcmp(par, "ripemd160") == 0)
				pconfig -> ht = H_RIPEMD160;
			else if (strcmp(par, "whirlpool") == 0)
				pconfig -> ht = H_WHIRLPOOL;
			else
				error_exit("Hash type '%s' not understood", par);
		}
		else if (strcmp(cmd, "stirrer_type") == 0)
		{
			if (strcmp(par, "blowfish") == 0)
				pconfig -> st = S_BLOWFISH;
			else if (strcmp(par, "aes") == 0)
				pconfig -> st = S_AES;
			else if (strcmp(par, "3des") == 0)
				pconfig -> st = S_3DES;
			else if (strcmp(par, "camellia") == 0)
				pconfig -> st = S_CAMELLIA;
			else
				error_exit("Stirrer type '%s' not understood", par);
		}
		else
			error_exit("%s=%s not understood", cmd, par);
	}

	dolog(LOG_DEBUG, "read %d configuration file lines", linenr);

	fclose(fh);

	free(dummy);
	free(cur_dir);
}
示例#19
0
/*---------------------------------------------------------------------------*
 *	data from /dev/isdn available, read and process them
 *---------------------------------------------------------------------------*/
static void
isdnrdhdl(void)
{
	static unsigned char msg_rd_buf[MSG_BUF_SIZ];
	msg_hdr_t *hp = (msg_hdr_t *)&msg_rd_buf[0];

	int len;

	if((len = read(isdnfd, msg_rd_buf, MSG_BUF_SIZ)) > 0)
	{
		switch(hp->type)
		{
			case MSG_CONNECT_IND:
				msg_connect_ind((msg_connect_ind_t *)msg_rd_buf);
				break;

			case MSG_CONNECT_ACTIVE_IND:
				msg_connect_active_ind((msg_connect_active_ind_t *)msg_rd_buf);
				break;

			case MSG_DISCONNECT_IND:
				msg_disconnect_ind((msg_disconnect_ind_t *)msg_rd_buf);
				break;

			case MSG_DIALOUT_IND:
				msg_dialout((msg_dialout_ind_t *)msg_rd_buf);
				break;

			case MSG_ACCT_IND:
				msg_accounting((msg_accounting_ind_t *)msg_rd_buf);
				break;

			case MSG_IDLE_TIMEOUT_IND:
				msg_idle_timeout_ind((msg_idle_timeout_ind_t *)msg_rd_buf);
				break;

			case MSG_CHARGING_IND:
				msg_charging_ind((msg_charging_ind_t *)msg_rd_buf);
				break;

			case MSG_PROCEEDING_IND:
				msg_proceeding_ind((msg_proceeding_ind_t *)msg_rd_buf);
				break;

			case MSG_ALERT_IND:
				msg_alert_ind((msg_alert_ind_t *)msg_rd_buf);
				break;

			case MSG_DRVRDISC_REQ:
				msg_drvrdisc_req((msg_drvrdisc_req_t *)msg_rd_buf);
				break;

			case MSG_L12STAT_IND:
				msg_l12stat_ind((msg_l12stat_ind_t *)msg_rd_buf);
				break;

			case MSG_TEIASG_IND:
				msg_teiasg_ind((msg_teiasg_ind_t *)msg_rd_buf);
				break;

			case MSG_PDEACT_IND:
				msg_pdeact_ind((msg_pdeact_ind_t *)msg_rd_buf);
				break;

			case MSG_NEGCOMP_IND:
				msg_negcomplete_ind((msg_negcomplete_ind_t *)msg_rd_buf);
				break;

			case MSG_IFSTATE_CHANGED_IND:
				msg_ifstatechg_ind((msg_ifstatechg_ind_t *)msg_rd_buf);
				break;

			case MSG_DIALOUTNUMBER_IND:
				msg_dialoutnumber((msg_dialoutnumber_ind_t *)msg_rd_buf);
				break;

			case MSG_PACKET_IND:
				msg_packet_ind((msg_packet_ind_t *)msg_rd_buf);
				break;

			case MSG_KEYPAD_IND:
				msg_keypad((msg_keypad_ind_t *)msg_rd_buf);
				break;

			default:
				dolog(LL_WRN, "ERROR, unknown message received from %sisdn (0x%x)", _PATH_DEV, msg_rd_buf[0]);
				break;
		}
	}
	else
	{
		dolog(LL_WRN, "ERROR, read error on isdn device, errno = %d, length = %d", errno, len);
	}
}
示例#20
0
文件: cs4231a.c 项目: ft-/ox820-qemu
static void cs_write (void *opaque, target_phys_addr_t addr,
                      uint64_t val64, unsigned size)
{
    CSState *s = opaque;
    uint32_t saddr, iaddr, val;

    saddr = addr;
    val = val64;

    switch (saddr) {
    case Index_Address:
        if (!(s->regs[Index_Address] & MCE) && (val & MCE)
            && (s->dregs[Interface_Configuration] & (3 << 3)))
            s->aci_counter = conf.aci_counter;

        s->regs[Index_Address] = val & ~(1 << 7);
        break;

    case Index_Data:
        if (!(s->dregs[MODE_And_ID] & MODE2))
            iaddr = s->regs[Index_Address] & 0x0f;
        else
            iaddr = s->regs[Index_Address] & 0x1f;

        switch (iaddr) {
        case RESERVED:
        case RESERVED_2:
        case RESERVED_3:
            lwarn ("attempt to write %#x to reserved indirect register %d\n",
                   val, iaddr);
            break;

        case FS_And_Playback_Data_Format:
            if (s->regs[Index_Address] & MCE) {
                cs_reset_voices (s, val);
            }
            else {
                if (s->dregs[Alternate_Feature_Status] & PMCE) {
                    val = (val & ~0x0f) | (s->dregs[iaddr] & 0x0f);
                    cs_reset_voices (s, val);
                }
                else {
                    lwarn ("[P]MCE(%#x, %#x) is not set, val=%#x\n",
                           s->regs[Index_Address],
                           s->dregs[Alternate_Feature_Status],
                           val);
                    break;
                }
            }
            s->dregs[iaddr] = val;
            break;

        case Interface_Configuration:
            val &= ~(1 << 5);   /* D5 is reserved */
            s->dregs[iaddr] = val;
            if (val & PPIO) {
                lwarn ("PIO is not supported (%#x)\n", val);
                break;
            }
            if (val & PEN) {
                if (!s->dma_running) {
                    cs_reset_voices (s, s->dregs[FS_And_Playback_Data_Format]);
                }
            }
            else {
                if (s->dma_running) {
                    DMA_release_DREQ (s->dma);
                    AUD_set_active_out (s->voice, 0);
                    s->dma_running = 0;
                }
            }
            break;

        case Error_Status_And_Initialization:
            lwarn ("attempt to write to read only register %d\n", iaddr);
            break;

        case MODE_And_ID:
            dolog ("val=%#x\n", val);
            if (val & MODE2)
                s->dregs[iaddr] |= MODE2;
            else
                s->dregs[iaddr] &= ~MODE2;
            break;

        case Alternate_Feature_Enable_I:
            if (val & TE)
                lerr ("timer is not yet supported\n");
            s->dregs[iaddr] = val;
            break;

        case Alternate_Feature_Status:
            if ((s->dregs[iaddr] & PI) && !(val & PI)) {
                /* XXX: TI CI */
                qemu_irq_lower (s->pic);
                s->regs[Status] &= ~INT;
            }
            s->dregs[iaddr] = val;
            break;

        case Version_Chip_ID:
            lwarn ("write to Version_Chip_ID register %#x\n", val);
            s->dregs[iaddr] = val;
            break;

        default:
            s->dregs[iaddr] = val;
            break;
        }
        dolog ("written value %#x to indirect register %d\n", val, iaddr);
        break;

    case Status:
        if (s->regs[Status] & INT) {
            qemu_irq_lower (s->pic);
        }
        s->regs[Status] &= ~INT;
        s->dregs[Alternate_Feature_Status] &= ~(PI | CI | TI);
        break;

    case PIO_Data:
        lwarn ("attempt to write value %#x to PIO register\n", val);
        break;
    }
}
示例#21
0
/*---------------------------------------------------------------------------*
 *	select the first remote number to dial according to the
 *	dial strategy
 *---------------------------------------------------------------------------*/
void
select_first_dialno(cfg_entry_t *cep)
{
	int i, j;

	if(cep->keypad[0] != '\0')
		return;

	if(cep->remote_numbers_count < 1)
	{
		dolog(LL_ERR, "select_first_dialno: remote_numbers_count < 1!");
		return;
	}

	if(cep->remote_numbers_count == 1)
	{
		strcpy(cep->remote_phone_dialout, cep->remote_numbers[0].number);
		DBGL(DL_DIAL, (dolog(LL_DBG, "select_first_dialno: only one no, no = %s", cep->remote_phone_dialout)));
		cep->last_remote_number = 0;
		return;
	}

	if(cep->remote_numbers_handling == RNH_FIRST)
	{
		strcpy(cep->remote_phone_dialout, cep->remote_numbers[0].number);
		DBGL(DL_DIAL, (dolog(LL_DBG, "select_first_dialno: use first, no = %s", cep->remote_phone_dialout)));
		cep->last_remote_number = 0;
		return;
	}

	i = cep->last_remote_number;
	   
	for(j = cep->remote_numbers_count; j > 0; j--)
	{
		if(cep->remote_numbers[i].flag == RNF_SUCC)
		{
			if(cep->remote_numbers_handling == RNH_LAST)
			{
				strcpy(cep->remote_phone_dialout, cep->remote_numbers[i].number);
				DBGL(DL_DIAL, (dolog(LL_DBG, "select_first_dialno: use last, no = %s", cep->remote_phone_dialout)));
				cep->last_remote_number = i;
				return;
			}
			else
			{
				if(++i >= cep->remote_numbers_count)
					i = 0;

				strcpy(cep->remote_phone_dialout, cep->remote_numbers[i].number);
				DBGL(DL_DIAL, (dolog(LL_DBG, "select_first_dialno: use next, no = %s", cep->remote_phone_dialout)));
				cep->last_remote_number = i;
				return;
			}
		}

		if(++i >= cep->remote_numbers_count)
			i = 0;
	}
	strcpy(cep->remote_phone_dialout, cep->remote_numbers[0].number);
	DBGL(DL_DIAL, (dolog(LL_DBG, "select_first_dialno: no last found (use 0), no = %s", cep->remote_phone_dialout)));
	cep->last_remote_number = 0;	
}									
示例#22
0
static int coreaudio_init_out(HWVoiceOut *hw, struct audsettings *as,
                              void *drv_opaque)
{
    OSStatus status;
    coreaudioVoiceOut *core = (coreaudioVoiceOut *) hw;
    int err;
    const char *typ = "playback";
    AudioValueRange frameRange;
    Audiodev *dev = drv_opaque;
    AudiodevCoreaudioPerDirectionOptions *cpdo = dev->u.coreaudio.out;
    int frames;

    /* create mutex */
    err = pthread_mutex_init(&core->mutex, NULL);
    if (err) {
        dolog("Could not create mutex\nReason: %s\n", strerror (err));
        return -1;
    }

    audio_pcm_init_info (&hw->info, as);

    status = coreaudio_get_voice(&core->outputDeviceID);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get default output Device\n");
        return -1;
    }
    if (core->outputDeviceID == kAudioDeviceUnknown) {
        dolog ("Could not initialize %s - Unknown Audiodevice\n", typ);
        return -1;
    }

    /* get minimum and maximum buffer frame sizes */
    status = coreaudio_get_framesizerange(core->outputDeviceID,
                                          &frameRange);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get device buffer frame range\n");
        return -1;
    }

    frames = audio_buffer_frames(
        qapi_AudiodevCoreaudioPerDirectionOptions_base(cpdo), as, 11610);
    if (frameRange.mMinimum > frames) {
        core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMinimum;
        dolog ("warning: Upsizing Buffer Frames to %f\n", frameRange.mMinimum);
    } else if (frameRange.mMaximum < frames) {
        core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMaximum;
        dolog ("warning: Downsizing Buffer Frames to %f\n", frameRange.mMaximum);
    }
    else {
        core->audioDevicePropertyBufferFrameSize = frames;
    }

    /* set Buffer Frame Size */
    status = coreaudio_set_framesize(core->outputDeviceID,
                                     &core->audioDevicePropertyBufferFrameSize);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not set device buffer frame size %" PRIu32 "\n",
                           (uint32_t)core->audioDevicePropertyBufferFrameSize);
        return -1;
    }

    /* get Buffer Frame Size */
    status = coreaudio_get_framesize(core->outputDeviceID,
                                     &core->audioDevicePropertyBufferFrameSize);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get device buffer frame size\n");
        return -1;
    }
    hw->samples = (cpdo->has_buffer_count ? cpdo->buffer_count : 4) *
        core->audioDevicePropertyBufferFrameSize;

    /* get StreamFormat */
    status = coreaudio_get_streamformat(core->outputDeviceID,
                                        &core->outputStreamBasicDescription);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get Device Stream properties\n");
        core->outputDeviceID = kAudioDeviceUnknown;
        return -1;
    }

    /* set Samplerate */
    core->outputStreamBasicDescription.mSampleRate = (Float64) as->freq;
    status = coreaudio_set_streamformat(core->outputDeviceID,
                                        &core->outputStreamBasicDescription);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ, "Could not set samplerate %d\n",
                           as->freq);
        core->outputDeviceID = kAudioDeviceUnknown;
        return -1;
    }

    /* set Callback */
    core->ioprocid = NULL;
    status = AudioDeviceCreateIOProcID(core->outputDeviceID,
                                       audioDeviceIOProc,
                                       hw,
                                       &core->ioprocid);
    if (status != kAudioHardwareNoError || core->ioprocid == NULL) {
        coreaudio_logerr2 (status, typ, "Could not set IOProc\n");
        core->outputDeviceID = kAudioDeviceUnknown;
        return -1;
    }

    /* start Playback */
    if (!isPlaying(core->outputDeviceID)) {
        status = AudioDeviceStart(core->outputDeviceID, core->ioprocid);
        if (status != kAudioHardwareNoError) {
            coreaudio_logerr2 (status, typ, "Could not start playback\n");
            AudioDeviceDestroyIOProcID(core->outputDeviceID, core->ioprocid);
            core->outputDeviceID = kAudioDeviceUnknown;
            return -1;
        }
    }

    return 0;
}
示例#23
0
文件: p910nd.c 项目: Einheri/wl500g
/* If bidir, also copy data from printer (lp) to network (fd). */
int copy_stream(int fd, int lp)
{
	int result;
	Buffer_t networkToPrinterBuffer;
	initBuffer(&networkToPrinterBuffer, fd, lp, 1);

	if (bidir) {
		struct timeval now;
		struct timeval then;
		struct timeval timeout;
		struct timeval lastnetactivity;
		int timer = 0;
		Buffer_t printerToNetworkBuffer;
		initBuffer(&printerToNetworkBuffer, lp, fd, 0);
		fd_set readfds;
		fd_set writefds;

		if (timeoutparam > 0)
			gettimeofday(&lastnetactivity, 0);
		/* Finish when network sent EOF. */
		/* Although the printer to network stream may not be finished (does this matter?) */
		while (!networkToPrinterBuffer.eof_sent && !networkToPrinterBuffer.err) {
			FD_ZERO(&readfds);
			FD_ZERO(&writefds);
			prepBuffer(&networkToPrinterBuffer, &readfds, &writefds);
			prepBuffer(&printerToNetworkBuffer, &readfds, &writefds);

			int maxfd = lp > fd ? lp : fd;
			if (timer) {
				/* Delay after reading from the printer, so the */
				/* return stream cannot dominate. */
				/* Don't read from the printer until the timer expires. */
				gettimeofday(&now, 0);
				if ((now.tv_sec > then.tv_sec) || (now.tv_sec == then.tv_sec && now.tv_usec > then.tv_usec))
					timer = 0;
				else
					FD_CLR(lp, &readfds);
			}
			timeout.tv_sec = 0;
			timeout.tv_usec = 100000;
			result = select(maxfd + 1, &readfds, &writefds, 0, &timeout);
			if (result < 0)
				return (result);
			if (FD_ISSET(fd, &readfds)) {
				/* Read network data. */
				result = readBuffer(&networkToPrinterBuffer);
				if (result > 0)
					dolog(LOG_DEBUG,"read %d bytes from network\n",result);
				if (timeoutparam > 0)
					gettimeofday(&lastnetactivity, 0);
			}
			if (FD_ISSET(lp, &readfds)) {
				/* Read printer data, but pace it more slowly. */
				result = readBuffer(&printerToNetworkBuffer);
				if (result > 0) {
					dolog(LOG_DEBUG,"read %d bytes from printer\n",result);
					gettimeofday(&then, 0);
					// wait 100 msec before reading again.
					then.tv_usec += 100000;
					if (then.tv_usec > 1000000) {
						then.tv_usec -= 1000000;
						then.tv_sec++;
					}
					timer = 1;
				}
			}
			if (FD_ISSET(lp, &writefds)) {
				/* Write data to printer. */
				result = writeBuffer(&networkToPrinterBuffer);
				if (result > 0)
					dolog(LOG_DEBUG,"wrote %d bytes to printer\n",result);
			}
			if (FD_ISSET(fd, &writefds) || printerToNetworkBuffer.outfd == -1) {
				/* Write data to network. */
				result = writeBuffer(&printerToNetworkBuffer);
				/* If socket write error, discard further data from printer */
				if (result < 0) {
					printerToNetworkBuffer.outfd = -1;
					printerToNetworkBuffer.err = 0;
					result = 0;
					dolog(LOG_DEBUG,"network write error, discarding further printer data\n",result);
					if (timeoutparam > 0)
						gettimeofday(&lastnetactivity, 0);
				}
				else if (result > 0) {
					if (printerToNetworkBuffer.outfd == -1)
						dolog(LOG_DEBUG,"discarded %d bytes from printer\n",result);				
					else
						dolog(LOG_DEBUG,"wrote %d bytes to network\n",result);
				}
			}
			if (timeoutparam > 0) {
				gettimeofday(&now, 0);
				if ((now.tv_sec - lastnetactivity.tv_sec) >= timeoutparam) {
					networkToPrinterBuffer.eof_sent = 1;
					printerToNetworkBuffer.err = 1;
				}
			}
		}
		dolog(LOG_NOTICE,
		       "Finished job: %d/%d bytes sent to printer, %d/%d bytes sent to network\n",
		       networkToPrinterBuffer.totalout,networkToPrinterBuffer.totalin, printerToNetworkBuffer.totalout, printerToNetworkBuffer.totalin);
	} else {
		/* Unidirectional: simply read from network, and write to printer. */
		while (!networkToPrinterBuffer.eof_sent && !networkToPrinterBuffer.err) {
			result = readBuffer(&networkToPrinterBuffer);
			if (result > 0)
				dolog(LOG_DEBUG,"read %d bytes from network\n",result);
			result = writeBuffer(&networkToPrinterBuffer);
			if (result > 0)
				dolog(LOG_DEBUG,"wrote %d bytes to printer\n",result);
		}
		dolog(LOG_NOTICE, "Finished job: %d/%d bytes sent to printer\n", networkToPrinterBuffer.totalout, networkToPrinterBuffer.totalin);
	}
	return (networkToPrinterBuffer.err?-1:0);
}
示例#24
0
文件: test1.cpp 项目: sjneph/hmm
int main()
{
  // Observed sequence 
  typedef float T;
  std::vector<T> observed, initial, tmp;
  std::vector< std::vector<T> > transition, emission, results;
  std::string obs = "010000000010000100001000000000";
  make_vector(observed, obs);
  std::copy(observed.begin(), observed.end(), std::ostream_iterator<T>(std::cout, " "));
  std::cout << std::endl << "Length = " << observed.size() << std::endl;

  // Initial state probabilities
  initial.push_back(0.5), initial.push_back(0.5);

  // Transitional probabilities
  tmp.clear();
  tmp.push_back(0.9), tmp.push_back(0.1);
  transition.push_back(tmp);

  tmp.clear();
  tmp.push_back(0.5), tmp.push_back(0.5);
  transition.push_back(tmp);

  // Emission probabilities
  tmp.clear();
  tmp.push_back(0.2), tmp.push_back(0.3), tmp.push_back(0.5);
  emission.push_back(tmp);

  tmp.clear();
  tmp.push_back(0.5), tmp.push_back(0.2), tmp.push_back(0.3);
  emission.push_back(tmp);

  dolog(initial, transition, emission);

  // Test full forward
  std::cout << "Full Forward" << std::endl;
  std::size_t index = observed.size();
  results.resize(initial.size());
  for ( std::size_t i = 0; i < results.size(); ++i )
    results[i].resize(index);

  ci::hmm::forward_full(observed, initial, transition, emission, index, results);
  for ( std::size_t i = 0; i < results.size(); ++i ) {
    for ( std::size_t j = 0; j < results[i].size(); ++j )
      std::cout << results[i][j] << "\t";
    std::cout << std::endl;
  } // for

  // Test indexed forward
  std::cout << "Indexed Forward" << std::endl;
  std::vector<T> ok(initial.size(), 0);
  ci::hmm::forward_index(observed, initial, transition, emission, 1, ok);
  std::copy(ok.begin(), ok.end(), std::ostream_iterator<T>(std::cout, "\t"));
  std::cout << std::endl;

  // Test next forward
  ok.clear();
  ok.resize(initial.size(), 0);
  for ( std::size_t i = 1; i <= observed.size(); ++i ) {
    std::cout << "Next Forward (" << i << ")" << std::endl;
    ci::hmm::forward_next(observed, initial, transition, emission, i, ok);
    std::copy(ok.begin(), ok.end(), std::ostream_iterator<T>(std::cout, "\t"));
    std::cout << std::endl;
  }

  // Test backward
  std::cout << "Full Backward" << std::endl;
  results.clear();
  results.resize(initial.size());
  for ( std::size_t i = 0; i < results.size(); ++i )
    results[i].resize(observed.size(), 0);
  index = 1;

  ci::hmm::backward_full(observed, initial, transition, emission, index, results);
  for ( std::size_t i = 0; i < results.size(); ++i ) {
    for ( std::size_t j = 0; j < results[i].size(); ++j )
      std::cout << results[i][j] << "\t";
    std::cout << std::endl;
  } // for

  // Test indexed backward
  std::cout << "Indexed Backward" << std::endl;
  ok.clear();
  ok.resize(initial.size());
  ci::hmm::backward_index(observed, initial, transition, emission, index, ok);
  std::copy(ok.begin(), ok.end(), std::ostream_iterator<T>(std::cout, "\t"));
  std::cout << std::endl;

  // Test next backward
  ok.clear();
  ok.resize(initial.size(), 0);
  for ( std::size_t i = observed.size(); i > 0; --i ) {
    std::cout << "Next Backward (" << i << ")" << std::endl;
    ci::hmm::backward_next(observed, initial, transition, emission, i, ok);
    std::copy(ok.begin(), ok.end(), std::ostream_iterator<T>(std::cout, "\t"));
    std::cout << std::endl;
  }

  typedef std::vector<T> FOO;
  FOO const* foo;
  ci::hmm::details::BackCache< FOO, FOO, std::vector<FOO>, std::vector<FOO>, T > backcheaterA(observed, initial, transition, emission);
  for ( std::size_t i = 0; i < observed.size(); ++i ) {
    std::cout << "Cheat Backward->Forward (" << i << ")" << std::endl;
    foo = backcheaterA.Next();
    std::copy(foo->begin(), foo->end(), std::ostream_iterator<T>(std::cout, "\t"));
    std::cout << std::endl;
  }

  // Test extended next backward
  std::vector< std::vector<T> > dummy(initial.size());
  for ( std::size_t i = 0; i < dummy.size(); ++i )
    dummy[i] = std::vector<T>(initial.size(), 0);

  for ( std::size_t i = observed.size(); i > 0; --i ) {
    std::cout << "(Ext) Next Backward (" << i << ")" << std::endl;
    ci::hmm::backward_enext(observed, initial, transition, emission, i, dummy);
    for ( std::size_t j = 0; j < dummy.size(); ++j ) {
      for ( std::size_t k = 0; k < dummy[j].size(); ++k )
        std::cout << dummy[k][j] << "\t";
     std::cout << std::endl;
    } // for
    std::cout << std::endl;
  } // for


  // Problem 1
  float ans1 = ci::hmm::evalp(observed, initial, transition, emission);
  std::cout << "Answer to problem 1: " << ans1 << std::endl;

  // Problem 2
  // Test viterbi
  std::cout << "Viterbi answer to problem 2" << std::endl;
  std::ostream_iterator<T> os(std::cout, "\t");
  ci::hmm::viterbi(observed, initial, transition, emission, os);
  std::cout << std::endl;

  // Test gamma
  std::cout << "Testing Gamma" << std::endl;
  results.clear();
  results.resize(initial.size());
  for ( std::size_t i = 0; i < results.size(); ++i )
    results[i].resize(observed.size(), 0);
  ci::hmm::gamma_m_full(observed, initial, transition, emission, results);
  for ( std::size_t i = 0; i < results.size(); ++i ) {
    for ( std::size_t j = 0; j < results[i].size(); ++j )
      std::cout << results[i][j] << "\t";
    std::cout << std::endl;
  } // for

  std::cout << "New Gamma" << std::endl;
  std::vector<T> alpha(initial.size(), 0), beta(alpha.size(), 0), gam(alpha.size(), 0);
  ci::hmm::details::BackCache< FOO, FOO, std::vector<FOO>, std::vector<FOO>, T > backcheaterB(observed, initial, transition, emission);
  for ( std::size_t i = 1; i <= observed.size(); ++i ) {
    std::vector<T> const* foo = backcheaterB.Next();
    ci::hmm::gamma(observed, initial, transition, emission, i, *foo, alpha, gam);
    delete foo;
    std::copy(gam.begin(), gam.end(), std::ostream_iterator<T>(std::cout, "\t"));
    std::cout << std::endl;
  } // for

  // Test xi
  std::cout << "Testing xi" << std::endl;

  std::vector< std::vector< std::vector<T> > > v(initial.size());
  for ( std::size_t i = 0; i < v.size(); ++i ) {
    v[i].resize(initial.size());
    for ( std::size_t j = 0; j < v[i].size(); ++j )
      v[i][j].resize(observed.size(), 0); // should be observed.size()-1, but need to compare to old outputs
  }
  ci::hmm::xi_full(observed, initial, transition, emission, v);
  for ( std::size_t i = 0; i < v.size(); ++i ) {
    for ( std::size_t j = 0; j < v[i].size(); ++j ) {
      for ( std::size_t k = 0; k < v[i][j].size(); ++k )
        std::cout << v[i][j][k] << "\t";
      std::cout << std::endl;
    }
    std::cout << std::endl;
  } // for

  std::cout << "YO NEW-XI" << std::endl;
  std::vector< std::vector<T> > v2(initial.size());
  for ( std::size_t i = 0; i < v2.size(); ++i ) {
    v2[i].resize(initial.size());
  }

  ci::hmm::details::BackCache< std::vector<T>, std::vector<T>, std::vector< std::vector<T> >, std::vector< std::vector<T> >, T > backcheater(observed, initial, transition, emission);
  alpha.resize(alpha.size(), 0), beta.resize(beta.size(), 0);
  foo = backcheater.Next(); // must move up one spot in backward->forward direction
  for ( std::size_t s = 1; s < observed.size(); ++s ) {
    std::vector<T> const* foo = backcheater.Next();
    ci::hmm::xi(observed, initial, transition, emission, s, *foo, alpha, v2);
    delete foo;
    for ( std::size_t i = 0; i < v2.size(); ++i ) {
      for ( std::size_t j = 0; j < v2[i].size(); ++j )
        std::cout << v2[i][j] << "\t";
      std::cout << std::endl;
    } // for
  } // for
  std::cout << std::endl;

  // Problem 3
  // Test training
  std::cout << "Problem 3" << std::endl;
  std::cout << "Start Initial" << std::endl;
  for ( std::size_t i = 0; i < initial.size(); ++i )
    std::cout << initial[i] << std::endl;

  std::vector<T> keepobserved(observed), keepinitial(initial);
  std::vector< std::vector<T> > keeptransition(transition), keepemission(emission);

  std::size_t numiter = 2;
  for ( std::size_t i = 0; i < numiter; ++i ) {
    ci::hmm::train_full(observed, initial, transition, emission);
//    dolog(initial, transition, emission);

    std::cout << "Iteration: " << (i+1) << std::endl;

    std::cout << "New Initial" << std::endl;
    for ( std::size_t i = 0; i < initial.size(); ++i )
      std::cout << initial[i] << std::endl;

    std::cout << "New Transition" << std::endl;
    for ( std::size_t i = 0; i < transition.size(); ++i ) {
      for ( std::size_t j = 0; j < transition[i].size(); ++j )
        std::cout << transition[i][j] << "\t";
      std::cout << std::endl;
    } // for

    std::cout << "New Emission" << std::endl;
    for ( std::size_t i = 0; i < emission.size(); ++i ) {
      for ( std::size_t j = 0; j < emission[i].size(); ++j ) {
        if ( emission[i][j] == ci::inf<T>() )
          emission[i][j] = 0;
        std::cout << emission[i][j] << "\t";
      } // for
      std::cout << std::endl;
    } // for
  } // for


  std::cout << "Finale: *********************" << std::endl;

  observed = keepobserved;
  initial = keepinitial;
  transition = keeptransition;
  emission = keepemission;

  std::cout << "New Training" << std::endl;
  for ( std::size_t i = 0; i < numiter; ++i ) {
    ci::hmm::train(observed, initial, transition, emission);

    std::cout << "Iteration " << (i+1) << std::endl;

    std::cout << "New Initial" << std::endl;
    std::cout << initial.size() << std::endl;
    std::cout.flush();
    for ( std::size_t i = 0; i < initial.size(); ++i )
      std::cout << initial[i] << std::endl;
    std::cout.flush();

    std::cout << "New Transition" << std::endl;
    for ( std::size_t i = 0; i < transition.size(); ++i ) {
      for ( std::size_t j = 0; j < transition[i].size(); ++j )
        std::cout << transition[i][j] << "\t";
      std::cout << std::endl;
    } // for

    std::cout << "New Emission" << std::endl;
    for ( std::size_t i = 0; i < emission.size(); ++i ) {
      for ( std::size_t j = 0; j < emission[i].size(); ++j ) {
        if ( emission[i][j] == ci::inf<T>() )
          emission[i][j] = 0;
        std::cout << emission[i][j] << "\t";
      } // for
      std::cout << std::endl;
    } // for
  } // for

  return(0);
}
示例#25
0
static void dma_cmd (SB16State *s, uint8_t cmd, uint8_t d0, int dma_len)
{
    s->use_hdma = cmd < 0xc0;
    s->fifo = (cmd >> 1) & 1;
    s->dma_auto = (cmd >> 2) & 1;
    s->fmt_signed = (d0 >> 4) & 1;
    s->fmt_stereo = (d0 >> 5) & 1;

    switch (cmd >> 4) {
    case 11:
        s->fmt_bits = 16;
        break;

    case 12:
        s->fmt_bits = 8;
        break;
    }

    if (-1 != s->time_const) {
#if 1
        int tmp = 256 - s->time_const;
        s->freq = (1000000 + (tmp / 2)) / tmp;
#else
        /* s->freq = 1000000 / ((255 - s->time_const) << s->fmt_stereo); */
        s->freq = 1000000 / ((255 - s->time_const));
#endif
        s->time_const = -1;
    }

    s->block_size = dma_len + 1;
    s->block_size <<= (s->fmt_bits == 16);
    if (!s->dma_auto) {
        /* It is clear that for DOOM and auto-init this value
           shouldn't take stereo into account, while Miles Sound Systems
           setsound.exe with single transfer mode wouldn't work without it
           wonders of SB16 yet again */
        s->block_size <<= s->fmt_stereo;
    }

    ldebug ("freq %d, stereo %d, sign %d, bits %d, "
            "dma %d, auto %d, fifo %d, high %d\n",
            s->freq, s->fmt_stereo, s->fmt_signed, s->fmt_bits,
            s->block_size, s->dma_auto, s->fifo, s->highspeed);

    if (16 == s->fmt_bits) {
        if (s->fmt_signed) {
            s->fmt = AUD_FMT_S16;
        }
        else {
            s->fmt = AUD_FMT_U16;
        }
    }
    else {
        if (s->fmt_signed) {
            s->fmt = AUD_FMT_S8;
        }
        else {
            s->fmt = AUD_FMT_U8;
        }
    }

    s->left_till_irq = s->block_size;

    s->bytes_per_second = (s->freq << s->fmt_stereo) << (s->fmt_bits == 16);
    s->highspeed = 0;
    s->align = (1 << (s->fmt_stereo + (s->fmt_bits == 16))) - 1;
    if (s->block_size & s->align) {
        dolog ("warning: misaligned block size %d, alignment %d\n",
               s->block_size, s->align + 1);
    }

    if (s->freq) {
        struct audsettings as;

        s->audio_free = 0;

        as.freq = s->freq;
        as.nchannels = 1 << s->fmt_stereo;
        as.fmt = s->fmt;
        as.endianness = 0;

        s->voice = AUD_open_out (
            &s->card,
            s->voice,
            "sb16",
            s,
            SB_audio_callback,
            &as
            );
    }

    control (s, 1);
    speaker (s, 1);
}
示例#26
0
void cleanpid(int i)
{
	dolog(LOG_INFO, "Exiting...\n");
	unlink(PIDFILE);
	exit(0);
}
示例#27
0
文件: coreaudio.c 项目: 0-14N/NDroid
static int
coreaudio_voice_init (coreaudioVoice*    core,
                      struct audsettings*  as,
                      int                frameSize,
                      AudioDeviceIOProc  ioproc,
                      void*              hw,
                      int                input)
{
    OSStatus  status;
    UInt32    propertySize;
    int       err;
    int       bits = 8;
    AudioValueRange frameRange;
    const char*  typ = input ? "input" : "playback";

    core->isInput = input ? true : false;

    /* create mutex */
    err = pthread_mutex_init(&core->mutex, NULL);
    if (err) {
        dolog("Could not create mutex\nReason: %s\n", strerror (err));
        return -1;
    }

    if (as->fmt == AUD_FMT_S16 || as->fmt == AUD_FMT_U16) {
        bits = 16;
    }

    // TODO: audio_pcm_init_info (&hw->info, as);
    /* open default output device */
   /* note: we use DefaultSystemOutputDevice because DefaultOutputDevice seems to
    * always link to the internal speakers, and not the ones selected through system properties
    * go figure...
    */
    propertySize = sizeof(core->deviceID);
    status = AudioHardwareGetProperty(
        input ? kAudioHardwarePropertyDefaultInputDevice :
                kAudioHardwarePropertyDefaultSystemOutputDevice,
        &propertySize,
        &core->deviceID);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get default %s device\n", typ);
        return -1;
    }
    if (core->deviceID == kAudioDeviceUnknown) {
        dolog ("Could not initialize %s - Unknown Audiodevice\n", typ);
        return -1;
    }

    /* get minimum and maximum buffer frame sizes */
    propertySize = sizeof(frameRange);
    status = AudioDeviceGetProperty(
        core->deviceID,
        0,
        core->isInput,
        kAudioDevicePropertyBufferFrameSizeRange,
        &propertySize,
        &frameRange);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get device buffer frame range\n");
        return -1;
    }

    if (frameRange.mMinimum > frameSize) {
        core->bufferFrameSize = (UInt32) frameRange.mMinimum;
        dolog ("warning: Upsizing Output Buffer Frames to %f\n", frameRange.mMinimum);
    }
    else if (frameRange.mMaximum < frameSize) {
        core->bufferFrameSize = (UInt32) frameRange.mMaximum;
        dolog ("warning: Downsizing Output Buffer Frames to %f\n", frameRange.mMaximum);
    }
    else {
        core->bufferFrameSize = frameSize;
    }

    /* set Buffer Frame Size */
    propertySize = sizeof(core->bufferFrameSize);
    status = AudioDeviceSetProperty(
        core->deviceID,
        NULL,
        0,
        core->isInput,
        kAudioDevicePropertyBufferFrameSize,
        propertySize,
        &core->bufferFrameSize);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not set device buffer frame size %ld\n",
                           core->bufferFrameSize);
        return -1;
    }

    /* get Buffer Frame Size */
    propertySize = sizeof(core->bufferFrameSize);
    status = AudioDeviceGetProperty(
        core->deviceID,
        0,
        core->isInput,
        kAudioDevicePropertyBufferFrameSize,
        &propertySize,
        &core->bufferFrameSize);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get device buffer frame size\n");
        return -1;
    }
    // TODO: hw->samples = *pNBuffers * core->bufferFrameSize;

    /* get StreamFormat */
    propertySize = sizeof(core->streamBasicDescription);
    status = AudioDeviceGetProperty(
        core->deviceID,
        0,
        core->isInput,
        kAudioDevicePropertyStreamFormat,
        &propertySize,
        &core->streamBasicDescription);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ,
                           "Could not get Device Stream properties\n");
        core->deviceID = kAudioDeviceUnknown;
        return -1;
    }

    /* set Samplerate */
    core->streamBasicDescription.mSampleRate = (Float64) as->freq;
    propertySize = sizeof(core->streamBasicDescription);
    status = AudioDeviceSetProperty(
        core->deviceID,
        0,
        0,
        core->isInput,
        kAudioDevicePropertyStreamFormat,
        propertySize,
        &core->streamBasicDescription);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ, "Could not set samplerate %d\n",
                           as->freq);
        core->deviceID = kAudioDeviceUnknown;
        return -1;
    }

    /* set Callback */
    core->ioproc = ioproc;
    status = AudioDeviceAddIOProc(core->deviceID, ioproc, hw);
    if (status != kAudioHardwareNoError) {
        coreaudio_logerr2 (status, typ, "Could not set IOProc\n");
        core->deviceID = kAudioDeviceUnknown;
        return -1;
    }

    /* start Playback */
    if (!input && !coreaudio_voice_isPlaying(core)) {
        status = AudioDeviceStart(core->deviceID, core->ioproc);
        if (status != kAudioHardwareNoError) {
            coreaudio_logerr2 (status, typ, "Could not start playback\n");
            AudioDeviceRemoveIOProc(core->deviceID, core->ioproc);
            core->deviceID = kAudioDeviceUnknown;
            return -1;
        }
    }

    return 0;
}
示例#28
0
void main_loop(std::vector<std::string> * hosts, char *bytes_file, char show_bps, std::string username, std::string password, const char *cdevice)
{
	int n_to_do, bits_out=0, loop;
	char *dummy;
	static short psl=0, psr=0; /* previous samples */
	static char a=1; /* alternater */
	unsigned char byte_out=0;
	int input_buffer_size;
	char *input_buffer;
	snd_pcm_t *chandle;
	snd_pcm_format_t format;
	int err;
	unsigned char bytes[4096]; // 4096 * 8: 9992, must be less then 9999
	int bytes_out = 0;

	char server_type[128];
	snprintf(server_type, sizeof server_type, "eb_server_audio v" VERSION " %s", cdevice);

	protocol *p = NULL;
	if (!hosts -> empty())
		p = new protocol(hosts, username, password, true, server_type, DEFAULT_COMM_TO);

	lock_mem(bytes, sizeof bytes);

	recover_sound_dev(&chandle, false, cdevice, &format);

	init_showbps();
	set_showbps_start_ts();
	for(;!do_exit;)
	{
		char got_any = 0;

		input_buffer_size = snd_pcm_frames_to_bytes(chandle, DEFAULT_SAMPLE_RATE * 2);

		input_buffer = reinterpret_cast<char *>(malloc_locked(input_buffer_size));
		if (!input_buffer)
			error_exit("problem allocating %d bytes of memory", input_buffer_size);

		/* Discard the first data read */
		/* it often contains weird looking data - probably a click from */
		/* driver loading / card initialisation */
		snd_pcm_sframes_t garbage_frames_read = snd_pcm_readi(chandle, input_buffer, DEFAULT_SAMPLE_RATE);
		/* Make sure we aren't hitting a disconnect/suspend case */
		if (garbage_frames_read < 0)
		{
			dolog(LOG_INFO, "snd_pcm_readi: failed retrieving audio", snd_strerror(garbage_frames_read)); // FIXME

			if ((err = snd_pcm_recover(chandle, garbage_frames_read, 0)) < 0)
			{
				dolog(LOG_INFO, "snd_pcm_recover fail : %s", snd_strerror(err));

				dolog(LOG_INFO, "Failure retrieving sound from soundcard, re-opening device");

				recover_sound_dev(&chandle, true, cdevice, &format);
			}
		}

		/* Read a buffer of audio */
		n_to_do = DEFAULT_SAMPLE_RATE * 2;
		dummy = input_buffer;
		while (n_to_do > 0 && !do_exit)
		{
			snd_pcm_sframes_t frames_read = snd_pcm_readi(chandle, dummy, n_to_do);
			/* Make	sure we	aren't hitting a disconnect/suspend case */
			if (frames_read < 0)
				frames_read = snd_pcm_recover(chandle, frames_read, 0);
			/* Nope, something else is wrong. Bail.	*/
			if (frames_read == -1) 
			{
				if ((err = snd_pcm_recover(chandle, frames_read, 0)) < 0)
				{
					dolog(LOG_INFO, "snd_pcm_recover fail : %s", snd_strerror(err));

					dolog(LOG_INFO, "Failure retrieving sound from soundcard, re-opening device");

					recover_sound_dev(&chandle, true, cdevice, &format);
				}
			}
			else
			{
				n_to_do -= frames_read;
				dummy += frames_read;	
			}
		}

		/* de-biase the data */
		for(loop=0; loop<(DEFAULT_SAMPLE_RATE * 2/*16bits*/ * 2/*stereo*/ * 2) && !do_exit; loop+=8)
		{
			int w1, w2, w3, w4, o1, o2;

			if (format == SND_PCM_FORMAT_S16_BE)
			{
				w1 = (input_buffer[loop+0]<<8) + input_buffer[loop+1];
				w2 = (input_buffer[loop+2]<<8) + input_buffer[loop+3];
				w3 = (input_buffer[loop+4]<<8) + input_buffer[loop+5];
				w4 = (input_buffer[loop+6]<<8) + input_buffer[loop+7];
			}
			else
			{
				w1 = (input_buffer[loop+1]<<8) + input_buffer[loop+0];
				w2 = (input_buffer[loop+3]<<8) + input_buffer[loop+2];
				w3 = (input_buffer[loop+5]<<8) + input_buffer[loop+4];
				w4 = (input_buffer[loop+7]<<8) + input_buffer[loop+6];
			}

			/* Determine order of channels for each sample, subtract previous sample
			 * to compensate for unbalanced audio devices */
			o1 = order(w1-psl, w2-psr);
			o2 = order(w3-psl, w4-psr);
			if (a > 0)
			{
				psl = w3;
				psr = w4;
			}
			else
			{
				psl = w1;
				psr = w2;
			}

			/* If both samples have the same order, there is bias in the samples, so we
			 * discard them; if both channels are equal on either sample, we discard
			 * them too; additionally, alternate the sample we'll use next (even more
			 * bias removal) */
			if (o1 == o2 || o1 < 0 || o2 < 0)
			{
				a = -a;
			}
			else
			{
				/* We've got a random bit; the bit is either the order from the first or
				 * the second sample, determined by the alternator 'a' */
				char bit = (a > 0) ? o1 : o2;

				byte_out <<= 1;
				byte_out += bit;

				bits_out++;

				got_any = 1;

				if (bits_out>=8)
				{
					bytes[bytes_out++] = byte_out;

					if (bytes_out == sizeof bytes)
					{
						if (show_bps)
							update_showbps(sizeof bytes);

						if (bytes_file)
							emit_buffer_to_file(bytes_file, bytes, bytes_out);

						if (p && p -> message_transmit_entropy_data(bytes, bytes_out) == -1)
						{
							dolog(LOG_INFO, "connection closed");
							p -> drop();
						}

						set_showbps_start_ts();

						bytes_out = 0;
					}

					bits_out = 0;
				}
			}
		}

		if (!got_any)
			dolog(LOG_WARNING, "no bits in audio-stream, please make sure the recording channel is not muted");

		free_locked(input_buffer, input_buffer_size);
	}

	unlock_mem(bytes, sizeof bytes);

	if (!do_exit)
		snd_pcm_close(chandle);

	delete p;
}
示例#29
0
/*--------------------------------------------------------------------------*
 *	init active or capi controller
 *--------------------------------------------------------------------------*/
void
init_active_controller(void)
{
	int ret;
	int unit = 0;
	int controller;
	char cmdbuf[MAXPATHLEN+128];

	for(controller = 0; controller < ncontroller; controller++)
	{
		if(isdn_ctrl_tab[controller].ctrl_type == CTRL_TINADD)
		{
			DBGL(DL_RCCF, (dolog(LL_DBG, "init_active_controller, tina-dd %d: executing [%s %d]", unit, tinainitprog, unit)));
			
			snprintf(cmdbuf, sizeof(cmdbuf), "%s %d", tinainitprog, unit);

			if((ret = system(cmdbuf)) != 0)
			{
				dolog(LL_ERR, "init_active_controller, tina-dd %d: %s returned %d!", unit, tinainitprog, ret);
				do_exit(1);
			}
		}

		/*
		 *  Generic microcode loading. If a controller has
		 *  defined a microcode file, load it using the
		 *  I4B_CTRL_DOWNLOAD ioctl.
		 */
		
		if(isdn_ctrl_tab[controller].firmware != NULL)
		{
		    int fd, ret;
		    struct isdn_dr_prot idp;
		    struct isdn_download_request idr;

		    fd = open(isdn_ctrl_tab[controller].firmware, O_RDONLY);
		    if (fd < 0) {
			dolog(LL_ERR, "init_active_controller %d: open %s: %s!",
			    controller, isdn_ctrl_tab[controller].firmware,
			    strerror(errno));
			do_exit(1);
		    }

		    idp.bytecount = lseek(fd, 0, SEEK_END);
		    idp.microcode = mmap(0, idp.bytecount, PROT_READ,
					 MAP_SHARED, fd, 0);
		    if (idp.microcode == MAP_FAILED) {
			dolog(LL_ERR, "init_active_controller %d: mmap %s: %s!",
			    controller, isdn_ctrl_tab[controller].firmware,
			    strerror(errno));
			do_exit(1);
		    }
		    
		    DBGL(DL_RCCF, (dolog(LL_DBG, "init_active_controller %d: loading firmware from [%s]", controller, isdn_ctrl_tab[controller].firmware)));

		    idr.controller = controller;
		    idr.numprotos = 1;
		    idr.protocols = &idp;
		    
		    ret = ioctl(isdnfd, I4B_CTRL_DOWNLOAD, &idr, sizeof(idr));
		    if (ret) {
			dolog(LL_ERR, "init_active_controller %d: load %s: %s!",
			    controller, isdn_ctrl_tab[controller].firmware,
			    strerror(errno));
			do_exit(1);
		    }

		    munmap(idp.microcode, idp.bytecount);
		    close(fd);
		}
	}
}	
int main(int argc, char *argv[])
{
	unsigned char bytes[4096];
	int c;
	bool do_not_fork = false, log_console = false, log_syslog = false;
	char *log_logfile = NULL;
	char *bytes_file = NULL;
	int verbose = 0;
	char server_type[128];
	bool show_bps = false;
	libusb_context *ctx = NULL;
	libusb_device_handle *handle = NULL;
	std::string username, password;
	std::vector<std::string> hosts;
	int log_level = LOG_INFO;

	fprintf(stderr, "eb_server_Araneus_Alea v" VERSION ", (C) 2009-2015 by [email protected]\n");

	while((c = getopt(argc, argv, "I:hSX:P:o:L:l:snv")) != -1)
	{
		switch(c)
		{
			case 'I':
				hosts.push_back(optarg);
				break;

			case 'S':
				show_bps = true;
				break;

			case 'X':
				get_auth_from_file(optarg, username, password);
				break;

			case 'P':
				pid_file = optarg;
				break;

			case 'v':
				verbose++;
				break;

			case 'o':
				bytes_file = optarg;
				break;

			case 's':
				log_syslog = true;
				break;

			case 'L':
				log_level = atoi(optarg);
				break;

			case 'l':
				log_logfile = optarg;
				break;

			case 'n':
				do_not_fork = true;
				log_console = true;
				break;

			case 'h':
				help();
				return 0;

			default:
				help();
				return 1;
		}
	}

	if (!hosts.empty() && (username.length() == 0 || password.length() == 0))
		error_exit("please select a file with authentication parameters (username + password) using the -X switch");

	if (hosts.empty() && !bytes_file)
		error_exit("no host to connect to or file to write to given");

	(void)umask(0177);
	no_core();

	lock_mem(bytes, sizeof bytes);

	set_logging_parameters(log_console, log_logfile, log_syslog, log_level);

	if(libusb_init(&ctx) < 0)
		error_exit("Error initialising Araneus Alea");

	libusb_set_debug(ctx, 3);

	handle = libusb_open_device_with_vid_pid(ctx,USB_VENDOR_ARANEUS,USB_ARANEUS_PRODUCT_ALEA);

	if (!handle)
		error_exit("No Alea device found");

	if(libusb_claim_interface(handle, 0) < 0){
        	error_exit("Cannot Claim Interface");
	}

	snprintf(server_type, sizeof server_type, "eb_server_Araneus_Alea v" VERSION);

	if (!do_not_fork)
	{
		if (daemon(0, 0) == -1)
			error_exit("fork failed");
	}

	write_pid(pid_file);

	protocol *p = NULL;
	if (!hosts.empty())
		p = new protocol(&hosts, username, password, true, server_type, DEFAULT_COMM_TO);

	signal(SIGPIPE, SIG_IGN);
	signal(SIGTERM, sig_handler);
	signal(SIGINT , sig_handler);
	signal(SIGQUIT, sig_handler);

	init_showbps();
	set_showbps_start_ts();

	for(;!do_exit;)
	{
        	if (libusb_bulk_transfer(handle, (1 | LIBUSB_ENDPOINT_IN), (unsigned char *)bytes, sizeof bytes, &c, TIMEOUT) < 0)
			error_exit("Failed to retrieve random bytes from device %x", c);

		////////

		if (show_bps)
			update_showbps(sizeof bytes);

		if (bytes_file)
			emit_buffer_to_file(bytes_file, bytes, sizeof bytes);

		if (!hosts.empty() && p -> message_transmit_entropy_data(bytes, sizeof bytes, &do_exit) == -1)
		{
			dolog(LOG_INFO, "connection closed");

			p -> drop();
		}

		set_showbps_start_ts();
	}

	delete p;

	memset(bytes, 0x00, sizeof bytes);

	unlink(pid_file);

	return 0;
}