Example #1
0
int DAUDIO_Start(void* id, int isSource)
{
    DS_Info* info = (DS_Info*) id;
    HRESULT res = DS_OK;
    DWORD status;

    //TRACE0("> DAUDIO_Start\n");

    if (info->isSource)
    {
        res = info->playBuffer->GetStatus(&status);
        if (res == DS_OK)
        {
            if (status & DSBSTATUS_LOOPING)
            {
                ERROR0("DAUDIO_Start: ERROR: Already started!");
                return true;
            }

            /* only start buffer if already something written to it */
            if (info->writePos >= 0)
            {
                res = DS_StartBufferHelper::StartBuffer(info);
                if (res == DSERR_BUFFERLOST)
                {
                    res = info->playBuffer->Restore();
                    if (res == DS_OK)
                    {
                        DS_clearBuffer(info, false /* entire buffer */);
                        /* write() will trigger actual device start */
                    }
                }
                else
                {
                    /* make sure that we will have silence after
                    the currently valid audio data */
                    DS_clearBuffer(info, true /* from write position */);
                }
            }
        }
    }
    else
    {
        if (info->captureBuffer->GetStatus(&status) == DS_OK)
        {
            if (status & DSCBSTATUS_LOOPING)
            {
                ERROR0("DAUDIO_Start: ERROR: Already started!");
                return true;
            }
        }
        res = DS_StartBufferHelper::StartBuffer(info);
    }
    if (FAILED(res))
    {
        ERROR1("DAUDIO_Start: ERROR: Failed to start: %s", TranslateDSError(res));
        return false;
    }
    info->started = true;
    return true;
}
// for each ALSA device, call iterator. userData is passed to the iterator
// returns total number of iterations
static int iterateRawmidiDevices(snd_rawmidi_stream_t direction,
                                 DeviceIteratorPtr iterator,
                                 void* userData) {
    int count = 0;
    int subdeviceCount;
    int card, dev, subDev;
    char devname[16];
    int err;
    snd_ctl_t *handle;
    snd_rawmidi_t *rawmidi;
    snd_rawmidi_info_t *rawmidi_info;
    snd_ctl_card_info_t *card_info, *defcardinfo = NULL;
    UINT32 deviceID;
    int doContinue = TRUE;

    snd_rawmidi_info_malloc(&rawmidi_info);
    snd_ctl_card_info_malloc(&card_info);

    // 1st try "default" device
    if (direction == SND_RAWMIDI_STREAM_INPUT) {
        err = snd_rawmidi_open(&rawmidi, NULL, ALSA_DEFAULT_DEVICE_NAME,
                               SND_RAWMIDI_NONBLOCK);
    } else if (direction == SND_RAWMIDI_STREAM_OUTPUT) {
        err = snd_rawmidi_open(NULL, &rawmidi, ALSA_DEFAULT_DEVICE_NAME,
                               SND_RAWMIDI_NONBLOCK);
    } else {
        ERROR0("ERROR: iterateRawmidiDevices(): direction is neither"
               " SND_RAWMIDI_STREAM_INPUT nor SND_RAWMIDI_STREAM_OUTPUT\n");
        err = MIDI_INVALID_ARGUMENT;
    }
    if (err < 0) {
        ERROR1("ERROR: snd_rawmidi_open (\"default\"): %s\n",
               snd_strerror(err));
    } else {
        err = snd_rawmidi_info(rawmidi, rawmidi_info);

        snd_rawmidi_close(rawmidi);
        if (err < 0) {
            ERROR1("ERROR: snd_rawmidi_info (\"default\"): %s\n",
                    snd_strerror(err));
        } else {
            // try to get card info
            card = snd_rawmidi_info_get_card(rawmidi_info);
            if (card >= 0) {
                sprintf(devname, ALSA_HARDWARE_CARD, card);
                if (snd_ctl_open(&handle, devname, SND_CTL_NONBLOCK) >= 0) {
                    if (snd_ctl_card_info(handle, card_info) >= 0) {
                        defcardinfo = card_info;
                    }
                    snd_ctl_close(handle);
                }
            }
            // call calback function for the device
            if (iterator != NULL) {
                doContinue = (*iterator)(ALSA_DEFAULT_DEVICE_ID, rawmidi_info,
                                         defcardinfo, userData);
            }
            count++;
        }
    }

    // iterate cards
    card = -1;
    TRACE0("testing for cards...\n");
    if (snd_card_next(&card) >= 0) {
        TRACE1("Found card %d\n", card);
        while (doContinue && (card >= 0)) {
            sprintf(devname, ALSA_HARDWARE_CARD, card);
            TRACE1("Opening control for alsa rawmidi device \"%s\"...\n", devname);
            err = snd_ctl_open(&handle, devname, SND_CTL_NONBLOCK);
            if (err < 0) {
                ERROR2("ERROR: snd_ctl_open, card=%d: %s\n", card, snd_strerror(err));
            } else {
                TRACE0("snd_ctl_open() SUCCESS\n");
                err = snd_ctl_card_info(handle, card_info);
                if (err < 0) {
                    ERROR2("ERROR: snd_ctl_card_info, card=%d: %s\n", card, snd_strerror(err));
                } else {
                    TRACE0("snd_ctl_card_info() SUCCESS\n");
                    dev = -1;
                    while (doContinue) {
                        if (snd_ctl_rawmidi_next_device(handle, &dev) < 0) {
                            ERROR0("snd_ctl_rawmidi_next_device\n");
                        }
                        TRACE0("snd_ctl_rawmidi_next_device() SUCCESS\n");
                        if (dev < 0) {
                            break;
                        }
                        snd_rawmidi_info_set_device(rawmidi_info, dev);
                        snd_rawmidi_info_set_subdevice(rawmidi_info, 0);
                        snd_rawmidi_info_set_stream(rawmidi_info, direction);
                        err = snd_ctl_rawmidi_info(handle, rawmidi_info);
                        TRACE0("after snd_ctl_rawmidi_info()\n");
                        if (err < 0) {
                            if (err != -ENOENT) {
                                ERROR2("ERROR: snd_ctl_rawmidi_info, card=%d: %s", card, snd_strerror(err));
                            }
                        } else {
                            TRACE0("snd_ctl_rawmidi_info() SUCCESS\n");
                            subdeviceCount = needEnumerateSubdevices(ALSA_RAWMIDI)
                                ? snd_rawmidi_info_get_subdevices_count(rawmidi_info)
                                : 1;
                            if (iterator!=NULL) {
                                for (subDev = 0; subDev < subdeviceCount; subDev++) {
                                    TRACE3("  Iterating %d,%d,%d\n", card, dev, subDev);
                                    deviceID = encodeDeviceID(card, dev, subDev);
                                    doContinue = (*iterator)(deviceID, rawmidi_info,
                                                             card_info, userData);
                                    count++;
                                    TRACE0("returned from iterator\n");
                                    if (!doContinue) {
                                        break;
                                    }
                                }
                            } else {
                                count += subdeviceCount;
                            }
                        }
                    } // of while(doContinue)
                }
                snd_ctl_close(handle);
            }
            if (snd_card_next(&card) < 0) {
                break;
            }
        }
    } else {
        ERROR0("No cards found!\n");
    }
    snd_ctl_card_info_free(card_info);
    snd_rawmidi_info_free(rawmidi_info);
    return count;
}
Example #3
0
int format_vorbis_get_buffer(format_plugin_t *self, char *data, unsigned long len, refbuf_t **buffer)
{
    char *buf;
    int i, result;
    ogg_packet op;
    char *tag;
    refbuf_t *refbuf;
    vstate_t *state = (vstate_t *)self->_state;
#ifdef USE_YP
    source_t *source;
    time_t current_time;
#endif

    if (data) {
        /* write the data to the buffer */
        buf = ogg_sync_buffer(&state->oy, len);
        memcpy(buf, data, len);
        ogg_sync_wrote(&state->oy, len);
    }

    refbuf = NULL;
    if (ogg_sync_pageout(&state->oy, &state->og) == 1) {
        refbuf = refbuf_new(state->og.header_len + state->og.body_len);
        memcpy(refbuf->data, state->og.header, state->og.header_len);
        memcpy(&refbuf->data[state->og.header_len], state->og.body, state->og.body_len);

        if (state->serialno != ogg_page_serialno(&state->og)) {
            /* this is a new logical bitstream */
            state->header = 0;
            state->packets = 0;

            /* release old headers, stream state, vorbis data */
            for (i = 0; i < MAX_HEADER_PAGES; i++) {
                if (state->headbuf[i]) {
                    refbuf_release(state->headbuf[i]);
                    state->headbuf[i] = NULL;
                }
            }
            /* Clear old stuff. Rarely but occasionally needed. */
            ogg_stream_clear(&state->os);
            vorbis_comment_clear(&state->vc);
            vorbis_info_clear(&state->vi);

            state->serialno = ogg_page_serialno(&state->og);
            ogg_stream_init(&state->os, state->serialno);
            vorbis_info_init(&state->vi);
            vorbis_comment_init(&state->vc);
        }

        if (state->header >= 0) {
            /* FIXME: In some streams (non-vorbis ogg streams), this could get
             * extras pages beyond the header. We need to collect the pages
             * here anyway, but they may have to be discarded later.
             */
            if (ogg_page_granulepos(&state->og) <= 0) {
                state->header++;
            } else {
                /* we're done caching headers */
                state->header = -1;

                /* put known comments in the stats */
                tag = vorbis_comment_query(&state->vc, "TITLE", 0);
                if (tag) stats_event(self->mount, "title", tag);
                else stats_event(self->mount, "title", "unknown");
                tag = vorbis_comment_query(&state->vc, "ARTIST", 0);
                if (tag) stats_event(self->mount, "artist", tag);
                else stats_event(self->mount, "artist", "unknown");

                /* don't need these now */
                ogg_stream_clear(&state->os);
                vorbis_comment_clear(&state->vc);
                vorbis_info_clear(&state->vi);
#ifdef USE_YP
                /* If we get an update on the mountpoint, force a
                   yp touch */
                avl_tree_rlock(global.source_tree);
                source = source_find_mount(self->mount);
                avl_tree_unlock(global.source_tree);

                if (source) {
                    /* If we get an update on the mountpoint, force a
                       yp touch */
                    current_time = time(NULL);
                    for (i=0; i<source->num_yp_directories; i++) {
                        source->ypdata[i]->yp_last_touch = current_time -
                            source->ypdata[i]->yp_touch_interval + 2;
                    }
                }
#endif

            }
        }

        /* cache header pages */
        if (state->header > 0 && state->packets < 3) {
            if(state->header > MAX_HEADER_PAGES) {
                refbuf_release(refbuf);
                ERROR1("Bad vorbis input: header is more than %d pages long", MAX_HEADER_PAGES);

                return -1;
            }
            refbuf_addref(refbuf);
            state->headbuf[state->header - 1] = refbuf;

            if (state->packets >= 0 && state->packets < 3) {
                ogg_stream_pagein(&state->os, &state->og);
                while (state->packets < 3) {
                    result = ogg_stream_packetout(&state->os, &op);
                    if (result == 0) break; /* need more data */
                    if (result < 0) {
                        state->packets = -1;
                        break;
                    }

                    state->packets++;

                    if (vorbis_synthesis_headerin(&state->vi, &state->vc, &op) < 0) {
                        state->packets = -1;
                        break;
                    }
                }
            }
        }
    }

    *buffer = refbuf;
    return 0;
}
CMHandlerAddr CM_FIXEDARGS CMGetOperation(CMType targetType,
																					CMconst_CMGlobalName operationType)
{	
	TOCObjectPtr 	 theObject;
	TOCValuePtr		 theValue;
	ContainerPtr 	 container;
	CM_CHAR	 			 *typeName;
	MetaHandlerPtr metaHandler;
	GetOpComArea 	 getOpComArea;
	
	ExitIfBadType(targetType, NULL);									/* validate targetType							*/

	theObject = (TOCObjectPtr)targetType;
	container = theObject->container;
		
	/* Walk the entire object and look at all the values to find the value for a global		*/
	/* name.  The object can have other properties and values, but there better be only 	*/
	/* one global name.  The object is walked with cmWalkObject().  The "refCon" we pass	*/
	/* is a pointer to a communication area which will hold the count of the global name	*/
	/* values and the pointer to it.  As just mentioned, if the count comes back other 		*/
	/* than 1, we have an error.																													*/
	
	getOpComArea.theValue = NULL;											/* init value ptr to no value yet		*/
	getOpComArea.nbrOfGlobalNames = 0;								/* there are no global names yet too*/
	
	cmWalkObject(container, theObject, &getOpComArea, NULL, NULL, NULL, checkValue);
	
	/* Get the global name for this type. The type must have only one property, one value,*/
	/* and that value must be for a global name.																					*/
		
	if (getOpComArea.nbrOfGlobalNames > 1) {					/* must have exactly 1 global name	*/
		ERROR2(CM_err_AmbiguousType, "CMGetOperation", CONTAINERNAME);
		return (NULL);
	}

	if (getOpComArea.nbrOfGlobalNames == 0) {
		ERROR2(CM_err_TypeNotGlobal, "CMGetOperation", CONTAINERNAME);
		return (NULL);
	}
	
	/* Set the typeName to point at the global name now that we're happy there is one...	*/
	
	theValue = getOpComArea.theValue;
	if (theValue == NULL) return (NULL);							/* safety														*/
	typeName = GetGlobalName(theValue->value.globalName.globalNameSymbol);
	
	/* Use the global name to look up the metahandler in the meta handler symbol table.		*/
	/* A few things can go wrong here, but if we successfully found a metahandler symbol	*/
	/* table entry we use the resulting metahandler proc pointer to get the routine				*/
	/* address for the input operationType.  That's what we return.												*/
	
	if ((metaHandler = cmLookupMetaHandler((CM_UCHAR *)typeName, SESSION)) == NULL) { 
		ERROR1(CM_err_UndefMetaHandler, typeName);
		return (NULL);
	}
	
	if (!SessionSuccess) {														/* if allocation error...						*/
		ERROR1(CM_err_HandlerError, typeName);					/* ...yell													*/
		return (NULL);
	}
	
	return ((CMHandlerAddr)(*metaHandler->metaHandler)(NULL, operationType));
}
Example #5
0
/*
 * w- and r_pipename have to be pre-allocated of atleast FILENAME_MAX size
 */
int erts_run_erl_open_fifo(char *pipename,char *w_pipename,char *r_pipename) {
  int calculated_pipename = 0;
  int highest_pipe_num = 0;
  int fd;

  /*
   * Create FIFOs and open them
   */

  if(*pipename && pipename[strlen(pipename)-1] == '/') {
    /* The user wishes us to find a unique pipe name in the specified */
    /* directory */
    DIR *dirp;
    struct dirent *direntp;

    calculated_pipename = 1;
    dirp = opendir(pipename);
    if(!dirp) {
      ERRNO_ERR1(LOG_ERR,"Can't access pipe directory '%s'.", pipename);
      return 1;
    }

    /* Check the directory for existing pipes */

    while((direntp=readdir(dirp)) != NULL) {
      if(strncmp(direntp->d_name,PIPE_STUBNAME,PIPE_STUBLEN)==0) {
	int num = atoi(direntp->d_name+PIPE_STUBLEN+1);
	if(num > highest_pipe_num)
	  highest_pipe_num = num;
      }
    }
    closedir(dirp);
    strn_catf(pipename, BUFSIZ, "%s.%d",
	      PIPE_STUBNAME, highest_pipe_num+1);
  } /* if */

  for(;;) {
      /* write FIFO - is read FIFO for `to_erl' program */
      strn_cpy(w_pipename, BUFSIZ, pipename);
      strn_cat(w_pipename, BUFSIZ, ".r");
      if (create_fifo(w_pipename, PERM) < 0) {
	  ERRNO_ERR1(LOG_ERR,"Cannot create FIFO %s for writing.",
		     w_pipename);
	  return 1;
      }

      /* read FIFO - is write FIFO for `to_erl' program */
      strn_cpy(r_pipename, BUFSIZ, pipename);
      strn_cat(r_pipename, BUFSIZ, ".w");

      /* Check that nobody is running run_erl already */
      if ((fd = sf_open(r_pipename, O_WRONLY|DONT_BLOCK_PLEASE, 0)) >= 0) {
	  /* Open as client succeeded -- run_erl is already running! */
	  sf_close(fd);
	  if (calculated_pipename) {
	      ++highest_pipe_num;
	      strn_catf(pipename, BUFSIZ, "%s.%d",
			PIPE_STUBNAME, highest_pipe_num+1);
	      continue;
	  }
	  ERROR1(LOG_ERR, "Erlang already running on pipe %s.\n", pipename);
	  unlink(w_pipename);
	  return 1;
      }
      if (create_fifo(r_pipename, PERM) < 0) {
	  unlink(w_pipename);
	  ERRNO_ERR1(LOG_ERR,"Cannot create FIFO %s for reading.",
		     r_pipename);
	  return 1;
      }
      break;
  }
  return 0;
}
Example #6
0
static struct v4l2_buffer *next_frame(QSP_ARG_DECL  int n_devices, Video_Device **vdp_tbl)
{
	fd_set fds;
	struct timeval tv;
	int r;
	//int i;
	int fd_limit;
	Video_Device *ready_vdp;
#ifdef WRITE_SEQUENTIAL
	int where_to_write;
#endif /* WRITE_SEQUENTIAL */

#define CHECK_ALL_DEVICES

	/* We CHECK ALL DEVICES when the cameras are not sychronized, and so we
	 * don't know which one will be ready next
	 */

#ifdef CHECK_ALL_DEVICES
	int i;

	FD_ZERO(&fds);
	fd_limit = vdp_tbl[0]->vd_fd;
	for(i=0;i<n_devices;i++){
		FD_SET(vdp_tbl[i]->vd_fd, &fds);
		if( vdp_tbl[i]->vd_fd > fd_limit )
			fd_limit = vdp_tbl[i]->vd_fd;
	}
	/* what is fd+1 all about??? see select(2) man page... */
	fd_limit++;

	/* Timeout. */
	tv.tv_sec = 2;
	tv.tv_usec = 0;

	r = select(fd_limit, &fds, NULL, NULL, &tv);

	if(r == -1) {
		/* original code repeated if EINTR */
		ERRNO_WARN("select");
		return(NULL);
	}

	if( r == 0 ) {
		sprintf(ERROR_STRING, "select timeout");
		WARN(ERROR_STRING);
		return(NULL);
	}

	/* Something is readable on one of the fd's - but which one??? */
	which_device = (-1);
	for(i=0;i<n_devices;i++){
		if( FD_ISSET(vdp_tbl[i]->vd_fd,&fds) ){
			if( which_device != -1 ) {
				if( verbose )
					advise("more than one device is ready!");
				/* Because we assign which_device every
				 * time we encounter a ready device, this
				 * has the effect of giving a preference
				 * to higher-numbered devices.  We ought
				 * to do something smarter, like noting
				 * how much time has elapsed since the
				 * device was last serviced, to avoid
				 * having a device's ring buffer fill up.
				 * In practice, this doesn't seem to be a
				 * problem, even though the system only
				 * gives each device 6 buffers (200 msec).
				 * With the * new SATA disks, write times
				 * are only 1-2 msec.
				 * Still, we might consider this a BUG.
				 */
			}
			which_device = i;
		}
	}
#ifdef CAUTIOUS
	if( which_device < 0 ){
		sprintf(ERROR_STRING,"CAUTIOUS:  next_frame:  no ready device found!?");
		WARN(ERROR_STRING);
		return(NULL);
	}
#endif /* CAUTIOUS */

#else /* ! CHECK_ALL_DEVICES */

	/* figure out which device we want to read next... */
	which_device = (newest+1) % n_devices;
	FD_ZERO(&fds);
	FD_SET(vdp_tbl[which_device]->vd_fd, &fds);
	fd_limit = vdp_tbl[which_device]->vd_fd;
	fd_limit++;
	/* Timeout. */
	tv.tv_sec = 2;
	tv.tv_usec = 0;

	r = select(fd_limit, &fds, NULL, NULL, &tv);

	if(r == -1) {
		/* original code repeated if EINTR */
		ERRNO_WARN("select");
		return(NULL);
	}

	if( r == 0 ) {
		sprintf(ERROR_STRING, "select timeout");
		WARN(ERROR_STRING);
		return(NULL);
	}

#endif /* ! CHECK_ALL_DEVICES */

	ready_vdp = vdp_tbl[which_device];

	//CLEAR (nf_buf);

	nf_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	nf_buf.memory = V4L2_MEMORY_MMAP;

	/* DQBUF pulls a buffer out and locks it up while we use it... */
	if( xioctl(ready_vdp->vd_fd, VIDIOC_DQBUF, &nf_buf) < 0 ) {
		/* original code had special cases for EAGAIN and EIO */
		ERRNO_WARN ("VIDIOC_DQBUF #1");
		return(NULL);
	}

#ifdef CAUTIOUS
	if( nf_buf.index < 0 || nf_buf.index >= (unsigned int) ready_vdp->vd_n_buffers ){
		sprintf(ERROR_STRING,"CAUTIOUS:  Unexpected buffer number (%d) from VIDIOC_DQBUF, expected 0-%d",
			nf_buf.index,ready_vdp->vd_n_buffers-1);
		WARN(ERROR_STRING);
		return(NULL);
	}
#endif /* CAUTIOUS */

#ifdef RECORD_TIMESTAMPS
	/* Store the timestamp for this buffer */
#ifdef CAUTIOUS
	if( n_stored_times >= ts_array_size ){
		sprintf(ERROR_STRING,"CAUTIOUS:  n_stored_times (%d) should be less than ts_array_size (%d) when storing a new timestamp",n_stored_times,ts_array_size);
		ERROR1(ERROR_STRING);
	}
#endif /* CAUTIOUS */
	ts_array[n_stored_times].grab_time = nf_buf.timestamp;
	ts_array[n_stored_times].which_dev = which_device;
	n_stored_times++;
#endif /* RECORD_TIMESTAMPS */


	/* note that newest & oldest are one thing for the video device,
	 * and another completely different thing for our ring buffer.
	 * Here we update the information for the video dev's private ring buffer...
	 */

	return(&nf_buf);
} /* end next_frame */
Example #7
0
// **** Audio card support
// Aquire and enabled audio card
// return 0 if ok, -1 if failed
int HAE_AquireAudioCard(void *context, UINT32 sampleRate, UINT32 channels, UINT32 bits) {
    int flag;
    short int count;
    INT32 error;
    audio_info_t sunAudioHeader;
    char* pAudioDev = HAE_GetAudioDevPlay(g_currentDeviceID, 0);
	
    flag = 0;
    g_activeDoubleBuffer = FALSE;
    g_shutDownDoubleBuffer = TRUE;

    g_audioFramesToGenerate = HAE_GetMaxSamplePerSlice();	// get number of frames per sample rate slice

    // we're going to build this many buffers at a time
    g_synthFramesPerBlock = HAE_SOLARIS_FRAMES_PER_BLOCK;
    g_audioPeriodSleepTime = HAE_SOLARIS_SOUND_PERIOD;
    g_bitSize = bits;
    g_channels = channels;
    if (bits == 8) {
	g_audioByteBufferSize = ((INT32)sizeof(char) * g_audioFramesToGenerate);
    } else {
	g_audioByteBufferSize = ((INT32)sizeof(short int) * g_audioFramesToGenerate);
    }
    g_audioByteBufferSize *= channels;

    flag = 1;
    // allocate buffer blocks
    g_audioBufferBlock = HAE_Allocate(g_audioByteBufferSize * HAE_SOLARIS_FRAMES_PER_BLOCK);
    if (g_audioBufferBlock) {
	// try to open wave device
	// $$kk: 12.17.97: need O_NONBLOCK flag to be compatible with windows
#ifdef __linux__
            g_waveDevice = open(pAudioDev,O_WRONLY);
#else
            g_waveDevice = open(pAudioDev,O_WRONLY|O_NONBLOCK);
#endif

	if (g_waveDevice > 0) {

	    /* set to multiple open */
	    if (ioctl(g_waveDevice, AUDIO_MIXER_MULTIPLE_OPEN, NULL) >= 0) {
		TRACE1("HAE_AquireAudioCard: %s set to multiple open\n", pAudioDev);
	    } else {
		ERROR1("HAE_AquireAudioCard: ioctl AUDIO_MIXER_MULTIPLE_OPEN failed on %s!\n", pAudioDev);
	    }

	    AUDIO_INITINFO(&sunAudioHeader);
	    // $$kk: 12.17.97: need AUDIO_GETINFO ioctl to get this to work on solaris x86 
	    // add next 1 line
	    error = ioctl(g_waveDevice, AUDIO_GETINFO, &sunAudioHeader);

	    // $$kk: 03.16.98: not valid to call AUDIO_SETINFO ioctl with all the fields from AUDIO_GETINFO,
	    // so let's try init'ing again....
	    AUDIO_INITINFO(&sunAudioHeader);

	    // Set rendering format of the sun device.
	    sunAudioHeader.play.sample_rate = sampleRate;
	    sunAudioHeader.play.precision = bits;
	    sunAudioHeader.play.channels = channels;
	    sunAudioHeader.play.encoding = AUDIO_ENCODING_LINEAR;
		
	    error = ioctl(g_waveDevice, AUDIO_SETINFO, &sunAudioHeader);

	    if (error == 0) {
		g_shutDownDoubleBuffer = FALSE;
		g_activeDoubleBuffer = TRUE;	// must enable process, before thread begins


				/* Spin threads for device service and possibly
				 * stream service.
				 */
				// create thread to manage and render audio frames
		error = HAE_CreateFrameThread(context, PV_AudioWaveOutFrameThread);

		if (error == 0) {	// ok
		    flag = 0;
#ifdef USE_RAWDATA_CHECK
		    { 
			char* fname = "javasound_debug_output.pcm";
			debugrawfile = HAE_FileOpenForWrite(fname);
		    }
#endif

		} else {
		    flag = 1;
		    g_activeDoubleBuffer = FALSE;
		}
	    }
	}
    }

    if (flag) {	// something failed
	HAE_ReleaseAudioCard(context);
    }
    return flag;
}
// for each ALSA device, call iterator. userData is passed to the iterator
// returns total number of iterations
int iteratePCMDevices(DeviceIteratorPtr iterator, void* userData) {
    int count = 0;
    int subdeviceCount;
    int card, dev, subDev;
    char devname[16];
    int err;
    snd_ctl_t *handle;
    snd_pcm_t *pcm;
    snd_pcm_info_t* pcminfo;
    snd_ctl_card_info_t *cardinfo, *defcardinfo = NULL;
    UINT32 deviceID;
    int doContinue = TRUE;

    snd_pcm_info_malloc(&pcminfo);
    snd_ctl_card_info_malloc(&cardinfo);

    // 1st try "default" device
    err = snd_pcm_open(&pcm, ALSA_DEFAULT_DEVICE_NAME,
                       SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
    if (err < 0) {
        // try with the other direction
        err = snd_pcm_open(&pcm, ALSA_DEFAULT_DEVICE_NAME,
                           SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK);
    }
    if (err < 0) {
        ERROR1("ERROR: snd_pcm_open (\"default\"): %s\n", snd_strerror(err));
    } else {
        err = snd_pcm_info(pcm, pcminfo);
        snd_pcm_close(pcm);
        if (err < 0) {
            ERROR1("ERROR: snd_pcm_info (\"default\"): %s\n",
                    snd_strerror(err));
        } else {
            // try to get card info
            card = snd_pcm_info_get_card(pcminfo);
            if (card >= 0) {
                sprintf(devname, ALSA_HARDWARE_CARD, card);
                if (snd_ctl_open(&handle, devname, SND_CTL_NONBLOCK) >= 0) {
                    if (snd_ctl_card_info(handle, cardinfo) >= 0) {
                        defcardinfo = cardinfo;
                    }
                    snd_ctl_close(handle);
                }
            }
            // call callback function for the device
            if (iterator != NULL) {
                doContinue = (*iterator)(ALSA_DEFAULT_DEVICE_ID, pcminfo,
                                         defcardinfo, userData);
            }
            count++;
        }
    }

    // iterate cards
    card = -1;
    while (doContinue) {
        if (snd_card_next(&card) < 0) {
            break;
        }
        if (card < 0) {
            break;
        }
        sprintf(devname, ALSA_HARDWARE_CARD, card);
        TRACE1("Opening alsa device \"%s\"...\n", devname);
        err = snd_ctl_open(&handle, devname, SND_CTL_NONBLOCK);
        if (err < 0) {
            ERROR2("ERROR: snd_ctl_open, card=%d: %s\n",
                    card, snd_strerror(err));
        } else {
            err = snd_ctl_card_info(handle, cardinfo);
            if (err < 0) {
                ERROR2("ERROR: snd_ctl_card_info, card=%d: %s\n",
                        card, snd_strerror(err));
            } else {
                dev = -1;
                while (doContinue) {
                    if (snd_ctl_pcm_next_device(handle, &dev) < 0) {
                        ERROR0("snd_ctl_pcm_next_device\n");
                    }
                    if (dev < 0) {
                        break;
                    }
                    snd_pcm_info_set_device(pcminfo, dev);
                    snd_pcm_info_set_subdevice(pcminfo, 0);
                    snd_pcm_info_set_stream(pcminfo, SND_PCM_STREAM_PLAYBACK);
                    err = snd_ctl_pcm_info(handle, pcminfo);
                    if (err == -ENOENT) {
                        // try with the other direction
                        snd_pcm_info_set_stream(pcminfo, SND_PCM_STREAM_CAPTURE);
                        err = snd_ctl_pcm_info(handle, pcminfo);
                    }
                    if (err < 0) {
                        if (err != -ENOENT) {
                            ERROR2("ERROR: snd_ctl_pcm_info, card=%d: %s",
                                    card, snd_strerror(err));
                        }
                    } else {
                        subdeviceCount = needEnumerateSubdevices(ALSA_PCM) ?
                            snd_pcm_info_get_subdevices_count(pcminfo) : 1;
                        if (iterator!=NULL) {
                            for (subDev = 0; subDev < subdeviceCount; subDev++) {
                                deviceID = encodeDeviceID(card, dev, subDev);
                                doContinue = (*iterator)(deviceID, pcminfo,
                                                         cardinfo, userData);
                                count++;
                                if (!doContinue) {
                                    break;
                                }
                            }
                        } else {
                            count += subdeviceCount;
                        }
                    }
                } // of while(doContinue)
            }
            snd_ctl_close(handle);
        }
    }
    snd_ctl_card_info_free(cardinfo);
    snd_pcm_info_free(pcminfo);
    return count;
}
Example #9
0
File: tfits.c Project: epowers/mpfr
static void
check_intmax (void)
{
#ifdef _MPFR_H_HAVE_INTMAX_T
  mpfr_t x, y;
  int i, r;

  mpfr_init2 (x, sizeof (uintmax_t) * CHAR_BIT);
  mpfr_init2 (y, 8);

  RND_LOOP (r)
    {
      /* Check NAN */
      mpfr_set_nan (x);
      if (mpfr_fits_uintmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (52);
      if (mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (53);

      /* Check INF */
      mpfr_set_inf (x, 1);
      if (mpfr_fits_uintmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (54);
      if (mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (55);

      /* Check Zero */
      MPFR_SET_ZERO (x);
      if (!mpfr_fits_uintmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (56);
      if (!mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (57);

      /* Check positive small op */
      mpfr_set_str1 (x, "1@-1");
      if (!mpfr_fits_uintmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (58);
      if (!mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (59);

      /* Check 17 */
      mpfr_set_ui (x, 17, MPFR_RNDN);
      if (!mpfr_fits_uintmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (60);
      if (!mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (61);

      /* Check hugest */
      mpfr_set_ui_2exp (x, 42, sizeof (uintmax_t) * 32, MPFR_RNDN);
      if (mpfr_fits_uintmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (62);
      if (mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (63);

      /* Check all other values */
      mpfr_set_uj (x, MPFR_UINTMAX_MAX, MPFR_RNDN);
      mpfr_add_ui (x, x, 1, MPFR_RNDN);
      if (mpfr_fits_uintmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (64);
      mpfr_set_uj (x, MPFR_UINTMAX_MAX, MPFR_RNDN);
      if (!mpfr_fits_uintmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (65);
      mpfr_set_sj (x, MPFR_INTMAX_MAX, MPFR_RNDN);
      mpfr_add_ui (x, x, 1, MPFR_RNDN);
      if (mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (66);
      mpfr_set_sj (x, MPFR_INTMAX_MAX, MPFR_RNDN);
      if (!mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (67);
      mpfr_set_sj (x, MPFR_INTMAX_MIN, MPFR_RNDN);
      if (!mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (68);
      mpfr_sub_ui (x, x, 1, MPFR_RNDN);
      if (mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
        ERROR1 (69);

      /* Check negative op */
      for (i = 1; i <= 4; i++)
        {
          int inv;

          mpfr_set_si_2exp (x, -i, -2, MPFR_RNDN);
          mpfr_rint (y, x, (mpfr_rnd_t) r);
          inv = MPFR_NOTZERO (y);
          if (!mpfr_fits_uintmax_p (x, (mpfr_rnd_t) r) ^ inv)
            ERROR1 (70);
          if (!mpfr_fits_intmax_p (x, (mpfr_rnd_t) r))
            ERROR1 (71);
        }
    }

  mpfr_clear (x);
  mpfr_clear (y);
#endif
}
void PORT_GetControls(void* id, INT32 portIndex, PortControlCreator* creator) {
    PortMixer *mixer = (PortMixer *)id;

    TRACE1(">>PORT_GetControls (portIndex = %d)\n", portIndex);

    if (portIndex < 0 || portIndex >= mixer->portCount) {
        ERROR1("<<PORT_GetControls: line (portIndex = %d) not found\n", portIndex);
        return;
    }

    PortLine *port = &(mixer->ports[portIndex]);

    if (mixer->deviceControlCount < 0) {    // not initialized
        OSStatus err;
        UInt32 size;
        // deviceControlCount is overestimated
        // because we don't actually filter by if the owned objects are controls
        err = GetAudioObjectPropertySize(mixer->deviceID, kAudioObjectPropertyScopeGlobal,
            kAudioObjectPropertyOwnedObjects, &size);

        if (err) {
            OS_ERROR1(err, "PORT_GetControls (portIndex = %d) get OwnedObject size", portIndex);
        } else {
            mixer->deviceControlCount = size / sizeof(AudioObjectID);
            TRACE1("  PORT_GetControls: detected %d owned objects\n", mixer->deviceControlCount);

            AudioObjectID controlIDs[mixer->deviceControlCount];

            err = GetAudioObjectProperty(mixer->deviceID, kAudioObjectPropertyScopeGlobal,
                kAudioObjectPropertyOwnedObjects, sizeof(controlIDs), controlIDs, 1);

            if (err) {
                OS_ERROR1(err, "PORT_GetControls (portIndex = %d) get OwnedObject values", portIndex);
            } else {
                mixer->deviceControls = (AudioControl *)calloc(mixer->deviceControlCount, sizeof(AudioControl));

                for (int i = 0; i < mixer->deviceControlCount; i++) {
                    AudioControl *control = &mixer->deviceControls[i];

                    control->controlID = controlIDs[i];

                    OSStatus err1 = GetAudioObjectProperty(control->controlID, kAudioObjectPropertyScopeGlobal,
                        kAudioObjectPropertyClass, sizeof(control->classID), &control->classID, 1);
                    OSStatus err2 = GetAudioObjectProperty(control->controlID, kAudioObjectPropertyScopeGlobal,
                        kAudioControlPropertyScope, sizeof(control->scope), &control->scope, 1);
                    OSStatus err3 = GetAudioObjectProperty(control->controlID, kAudioObjectPropertyScopeGlobal,
                        kAudioControlPropertyElement, sizeof(control->channel), &control->channel, 1);
                    if (err1 || err2 || err3) { // not a control or other error
                        control->classID = 0;
                        continue;
                    }

                    TRACE4("- control 0x%x, class='%s', scope='%s', channel=%d\n",
                        control->controlID, FourCC2Str(control->classID), FourCC2Str(control->scope), control->channel);
                }
            }
        }
    }

    if (mixer->deviceControlCount <= 0) {
        TRACE1("<<PORT_GetControls (portIndex = %d): no owned AudioControls\n", portIndex);
        return;
    }

    int totalChannels = GetChannelCount(mixer->deviceID, port->scope == kAudioDevicePropertyScopeOutput ? 1 : 0);

    // collect volume and mute controls
    AudioControl* volumeControls[totalChannels+1];  // 0 - for master channel
    memset(&volumeControls, 0, sizeof(AudioControl *) * (totalChannels+1));
    AudioControl* muteControls[totalChannels+1];  // 0 - for master channel
    memset(&muteControls, 0, sizeof(AudioControl *) * (totalChannels+1));

    for (int i=0; i<mixer->deviceControlCount; i++) {
        AudioControl *control = &mixer->deviceControls[i];
        if (control->classID == 0 || control->scope != port->scope || control->channel > (unsigned)totalChannels) {
            continue;
        }
        if (control->classID == kAudioVolumeControlClassID) {
            if (volumeControls[control->channel] == NULL) {
                volumeControls[control->channel] = control;
            } else {
                ERROR4("WARNING: duplicate VOLUME control 0x%x, class='%s', scope='%s', channel=%d\n",
                    control->controlID, FourCC2Str(control->classID), FourCC2Str(control->scope), control->channel);
            }
        } else if (control->classID == kAudioMuteControlClassID) {
            if (muteControls[control->channel] == NULL) {
                muteControls[control->channel] = control;
            } else {
                ERROR4("WARNING: duplicate MUTE control 0x%x, class='%s', scope='%s', channel=%d\n",
                    control->controlID, FourCC2Str(control->classID), FourCC2Str(control->scope), control->channel);
            }
        } else {
#ifdef USE_ERROR
            if (control->classID != 0) {
                ERROR4("WARNING: unhandled control 0x%x, class='%s', scope='%s', channel=%d\n",
                    control->controlID, FourCC2Str(control->classID), FourCC2Str(control->scope), control->channel);
            }
#endif
        }
    }

    ////////////////////////////////////////////////////////
    // create java control hierarchy

    void *masterVolume = NULL, *masterMute = NULL, *masterBalance = NULL;
    // volumeControls[0] and muteControls[0] - master volume/mute
    // volumeControls[n] and muteControls[n] (n=1..totalChannels) - corresponding channel controls
    if (volumeControls[0] != NULL) {    // "master volume" AudioControl
        masterVolume = CreatePortControl(mixer, creator, PortControl::Volume, volumeControls, 0, 1);
    } else {
        if (ValidControlCount(volumeControls, 1, totalChannels) == totalChannels) {
            // every channel has volume control => create virtual master volume
            masterVolume = CreatePortControl(mixer, creator, PortControl::Volume, volumeControls, 1, totalChannels);
        } else {
            TRACE2("  PORT_GetControls (master volume): totalChannels = %d, valid volume controls = %d\n",
                totalChannels, ValidControlCount(volumeControls, 1, totalChannels));
        }
    }

    if (muteControls[0] != NULL) {      // "master mute"
        masterMute = CreatePortControl(mixer, creator, PortControl::Mute, muteControls, 0, 1);
    } else {
        if (ValidControlCount(muteControls, 1, totalChannels) == totalChannels) {
            // every channel has mute control => create virtual master mute control
            masterMute = CreatePortControl(mixer, creator, PortControl::Mute, muteControls, 1, totalChannels);
        } else {
            TRACE2("  PORT_GetControls (master mute): totalChannels = %d, valid volume controls = %d\n",
                totalChannels, ValidControlCount(muteControls, 1, totalChannels));
        }
    }

    // virtual balance
    if (totalChannels == 2) {
        if (ValidControlCount(volumeControls, 1, totalChannels) == totalChannels) {
            masterBalance = CreatePortControl(mixer, creator, PortControl::Balance, volumeControls, 1, totalChannels);
        } else {
            TRACE2("  PORT_GetControls (naster balance): totalChannels = %d, valid volume controls = %d\n",
                totalChannels, ValidControlCount(volumeControls, 1, totalChannels));
        }
    }

    // add "master" controls
    if (masterVolume != NULL) {
        creator->addControl(creator, masterVolume);
    }
    if (masterBalance != NULL) {
        creator->addControl(creator, masterBalance);
    }
    if (masterMute != NULL) {
        creator->addControl(creator, masterMute);
    }

    // don't add per-channel controls for mono & stereo - they are handled by "master" controls
    // TODO: this should be reviewed to handle controls other than mute & volume
    if (totalChannels > 2) {
        // add separate compound control for each channel (containing volume and mute)
        // (ensure that we have controls)
        if (ValidControlCount(volumeControls, 1, totalChannels) > 0 || ValidControlCount(muteControls, 1, totalChannels) > 0) {
            for (int ch=1; ch<=totalChannels; ch++) {
                // get the channel name
                char *channelName;
                CFStringRef cfname = NULL;
                const AudioObjectPropertyAddress address = {kAudioObjectPropertyElementName, port->scope, ch};
                UInt32 size = sizeof(cfname);
                OSStatus err = AudioObjectGetPropertyData(mixer->deviceID, &address, 0, NULL, &size, &cfname);
                if (err == noErr) {
                    CFIndex length = CFStringGetLength(cfname) + 1;
                    channelName = (char *)malloc(length);
                    CFStringGetCString(cfname, channelName, length, kCFStringEncodingUTF8);
                    CFRelease(cfname);
                } else {
                    channelName = (char *)malloc(16);
                    sprintf(channelName, "Ch %d", ch);
                }

                void* jControls[2];
                int controlCount = 0;
                if (volumeControls[ch] != NULL) {
                    jControls[controlCount++] = CreatePortControl(mixer, creator, PortControl::Volume, volumeControls, ch, 1);
                }
                if (muteControls[ch] != NULL) {
                    jControls[controlCount++] = CreatePortControl(mixer, creator, PortControl::Mute, muteControls, ch, 1);
                }
                // TODO: add any extra controls for "other" controls for the channel

                void *compoundControl = creator->newCompoundControl(creator, channelName, jControls, controlCount);
                creator->addControl(creator, compoundControl);

                free(channelName);
            }
        }
    }

    AddChangeListeners(mixer);

    TRACE1("<<PORT_GetControls (portIndex = %d)\n", portIndex);
}
Example #11
0
INT32 UnitListComponent::ExportUnitDefinition(BaseCamelotFilter *pFilter, Unit* pUnit)
{
#ifdef DO_EXPORT
	ERROR2IF(pFilter == NULL,0L,"UnitListComponent::ExportUnitDefinition null pFilter");
	ERROR2IF(pUnit == NULL,0L,"UnitListComponent::ExportUnitDefinition null pUnit");
	ERROR2IF(pDocUnitList == NULL,0L,"UnitListComponent::ExportUnitDefinition called with no doc unit list pointer");

	ERROR2IF(pUnit->IsDefault(),0L,"UnitListComponent::ExportUnitDefinition trying to save default unit definition");

	INT32 RecordNumber = 0L;

	// See if we have saved the unit definition out by checking our table
	// If so then do nothing
	CMapPtrToLong::iterator it = pExpUserUnitMap->find(pUnit);
	if (it!=pExpUserUnitMap->end())
		return it->second;

	// Export the definition for this unit
	// First get all the details
//	UnitType type = pUnit->GetUnitType();
	
	// Set up the prefix/suffix state for this user's unit.
	BOOL Prefix = pUnit->IsPrefix();
	INT32 Tag = 0L;
	INT32 Size = 0L;
	if (Prefix)
	{
		Tag = TAG_DEFINE_PREFIXUSERUNIT;
		Size = TAG_DEFINE_PREFIXUSERUNIT_SIZE;
	}
	else
	{
		Tag = TAG_DEFINE_SUFFIXUSERUNIT;
		Size = TAG_DEFINE_SUFFIXUSERUNIT_SIZE;
	}

	// The main full name of the unit
	String_32 Name = pUnit->GetToken();
	// And the abbreviation
	String_32 Abbrev = pUnit->GetSpecifier();

	// If there are string names, then add it to this size
	// REMEMBER: We save out unicode strings and so we need to double the length of the returned string length
	Size += (Name.Length() + 1) * SIZEOF_XAR_UTF16;
	Size += (Abbrev.Length() + 1) * SIZEOF_XAR_UTF16;

	BOOL ok = TRUE;
	CXaraFileRecord Rec(Tag, Size);
	ok = Rec.Init();

	// Write out the name and abbreviation for this unit
	if (ok) ok = Rec.WriteUnicode(Name);
	if (ok) ok = Rec.WriteUnicode(Abbrev);

	// The size of this unit, 0 if based on
	double UnitSize = pUnit->GetMillipoints();
	if (ok) ok = Rec.WriteDOUBLE(UnitSize);

	// What unit this is based on
	UnitType BaseUnit = pUnit->GetBaseUnitType();
	//INT32 ExportBaseUnit = GetExportUnitType(BaseUnit);
	INT32 ExportBaseUnit = GetWriteUnitReference(BaseUnit, pFilter);
	ERROR2IF(ExportBaseUnit == 0,FALSE,"bad base units reference!");
	if (ok) ok = Rec.WriteINT32(ExportBaseUnit);

	// Write out the multipliers for this unit
	double BaseNumerator = 0.0;
	double BaseDenominator = 0.0;
	BaseNumerator = pUnit->GetBaseNumerator();
	BaseDenominator = pUnit->GetBaseDenominator();
	if (ok) ok = Rec.WriteDOUBLE(BaseNumerator);
	if (ok) ok = Rec.WriteDOUBLE(BaseDenominator);

	// Finally, write the record out to file
	// In the process get the record number that this was written out as
	if (ok) RecordNumber = pFilter->Write(&Rec);	// Get the document comment

	// Add the unit to the user units map so we can remember the references of the
	// exported units and hence whether we have exported this before
	// Reference for this unit is the record number
TRACEUSER( "Neville", _T("Exported user unit reference %d\n"), RecordNumber);
	try
	{
		(*pExpUserUnitMap)[pUnit] = RecordNumber;
	}
	catch (std::bad_alloc&)
	{
		ERROR1(FALSE, _R(IDS_OUT_OF_MEMORY));
	}
	catch (...)
	{
		ERROR1(FALSE, _R(IDS_UNKNOWN_ERROR));
	}

	return RecordNumber;
#else
	return 0L;
#endif
}
/*
** A "local" function of main().  Handles a #messageType# message arrived on
** #sd# accompanied by #dataSize# bytes of data.
*/
static void
ProcessRequest(Socket *sd,
               MessageType messageType,
               size_t dataSize) {

  char *contents;
  DataDescriptor contentsDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
  AutoFetchInfo *expandedAutoFetches;
  unsigned long expiration;
  DataDescriptor expirationDescriptor = SIMPLE_DATA(UNSIGNED_LONG_TYPE, 1);
  int i;
  struct state stateDesc;
  char *stateNames;
  DataDescriptor stateNamesDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);

  switch(messageType) {

  case FETCH_STATE:
    if(!RecvData(*sd,
                 &stateDesc,
                 stateDescriptor,
                 stateDescriptorLength,
                 PktTimeOut(*sd))) {
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: state receive failed\n");
      return;
    }
    contents = (char *)malloc(stateDesc.rec_count * MAX_RECORD_SIZE);
    if(contents == NULL) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      if(ReadState(FileOfState(memoryDir, stateDesc.id),
                   contents,
                   stateDesc.rec_count,
                   stateDesc.rec_count * MAX_RECORD_SIZE,
                   stateDesc.seq_no,
                   &stateDesc.time_out,
                   &stateDesc.seq_no,
                   &stateDesc.rec_count,
                   &stateDesc.rec_size)) {
        if(stateDesc.rec_count > 0) {
          contentsDescriptor.repetitions =
            stateDesc.rec_size * stateDesc.rec_count;
          (void)SendMessageAndDatas(*sd,
                                    STATE_FETCHED,
                                    &stateDesc,
                                    stateDescriptor,
                                    stateDescriptorLength,
                                    contents,
                                    &contentsDescriptor,
                                    1,
                                    PktTimeOut(*sd));
        }
        else {
          (void)SendMessageAndData(*sd,
                                   STATE_FETCHED,
                                   &stateDesc,
                                   stateDescriptor,
                                   stateDescriptorLength,
                                   PktTimeOut(*sd));
        }
      }
      else {
        (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
        if(errno == EMFILE) {
          CheckConnections();
        }
      }
      free(contents);
    }
    break;

  case STORE_STATE:
    if(!RecvData(*sd,
                 &stateDesc,
                 stateDescriptor,
                 stateDescriptorLength,
                 PktTimeOut(*sd))) {
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: state receive failed\n");
      return;
    }
    contentsDescriptor.repetitions = stateDesc.rec_size * stateDesc.rec_count;
    contents = (char *)malloc(contentsDescriptor.repetitions + 1);
    if(contents == NULL) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      contents[contentsDescriptor.repetitions] = '\0';
      if(!RecvData(*sd,
                   contents,
                   &contentsDescriptor,
                   1,
                   PktTimeOut(*sd))) {
        DROP_SOCKET(sd);
        ERROR("ProcessRequest: data receive failed\n");
      }
      else {
        (void)SendMessage(*sd,
                          KeepState(&memLogLocation,
                                    &stateDesc,
                                    contents,
                                    contentsDescriptor.repetitions) ?
                          STATE_STORED : MEMORY_FAILED,
                          PktTimeOut(*sd));
        for(i = 0; i < autoFetchCount; i++) {
          if(strstr(autoFetches[i].stateNames, stateDesc.id) != NULL) {
            if(!SendMessageAndDatas(autoFetches[i].clientSock,
                                    STATE_FETCHED,
                                    &stateDesc,
                                    stateDescriptor,
                                    stateDescriptorLength,
                                    contents,
                                    &contentsDescriptor,
                                    1,
                                    PktTimeOut(autoFetches[i].clientSock))) {
              DROP_SOCKET(&autoFetches[i].clientSock);
              free(autoFetches[i].stateNames);
              autoFetches[i] = autoFetches[--autoFetchCount];
            }
          }
        }
      }
      free(contents);
    }
    break;

  case AUTOFETCH_BEGIN:
    stateNamesDescriptor.repetitions = dataSize;
    stateNames = (char *)malloc(dataSize);
    if(stateNames == NULL) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: out of memory\n");
    }
    else if(!RecvData(*sd,
                      stateNames,
                      &stateNamesDescriptor,
                      1,
                      PktTimeOut(*sd))) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      DROP_SOCKET(sd);
      free(stateNames);
      ERROR("ProcessRequest: data receive failed\n");
    }
    else if(*stateNames == '\0') {
      free(stateNames);
      EndAutoFetch(*sd);
      (void)SendMessage(*sd, AUTOFETCH_ACK, PktTimeOut(*sd));
    }
    else {
      for(i=0; (i < autoFetchCount) && (autoFetches[i].clientSock != *sd); i++)
        ; /* Nothing more to do. */
      if(i == autoFetchCount) {
        expandedAutoFetches =
          REALLOC(autoFetches, (autoFetchCount + 1) * sizeof(AutoFetchInfo));
        if(expandedAutoFetches == NULL) {
          (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
          DROP_SOCKET(sd);
          ERROR("ProcessRequest: out of memory\n");
          break;
        }
        autoFetches = expandedAutoFetches;
        autoFetches[i].clientSock = *sd;
        autoFetchCount++;
      }
      else {
        free(autoFetches[i].stateNames);
      }
      autoFetches[i].stateNames = stateNames;
      (void)SendMessage(*sd, AUTOFETCH_ACK, PktTimeOut(*sd));
    }
    break;

  case MEMORY_CLEAN:
    if(!RecvData(*sd, &expiration, &expirationDescriptor, 1, PktTimeOut(*sd))) {
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: data receive failed\n");
    }
    else {
      (void)SendMessage(*sd, MEMORY_CLEANED, PktTimeOut(*sd));
      (void)DoClean(expiration);
    }
    break;

#ifdef WITH_NETLOGGER	  
  case MEMORY_LOGDEST: /* config message contains log location */
	  if(!RecvData(*sd,
		  &memLogLocation,
		  loglocationDescriptor,
		  loglocationDescriptorLength,
		  PktTimeOut(*sd))) {
		  DROP_SOCKET(sd);
		  ERROR("ProcessRequest: loglocation receive failed\n");
		  return;
	  }else
	  {
		  (void)SendMessage(*sd, MEMORY_LOGDEST_ACK, PktTimeOut(*sd));
	  }
	  LOG2("ProcessRequest: loglocation %d .%s.\n", memLogLocation.loc_type, memLogLocation.path);
 
	  break;
#endif /* WITH_NETLOGGER */	  	

  default:
    DROP_SOCKET(sd);
    ERROR1("ProcessRequest: unknown message %d\n", messageType);

  }

}
/*
** A "local" function of main().  Handles a #messageType# message arrived on
** #sd# accompanied by #dataSize# bytes of data.
*/
static void
ProcessRequest(Socket *sd,
               MessageType messageType,
               size_t dataSize) {

  unsigned long timeOut;
  DataDescriptor timeOutDescriptor = SIMPLE_DATA(UNSIGNED_LONG_TYPE, 1);
  char *matching;
  char *object;
  DataDescriptor objectDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
  char *pattern;
  DataDescriptor patternDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);

  switch(messageType) {

  case NS_REGISTER:
    objectDescriptor.repetitions =
      dataSize - HomogenousDataSize(UNSIGNED_LONG_TYPE, 1, NETWORK_FORMAT);
    object = (char *)malloc(objectDescriptor.repetitions + 1);
    if(object == NULL) {
      (void)SendMessage(*sd, NS_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      if(!RecvData(*sd,
                   object,
                   &objectDescriptor,
                   1,
                   PktTimeOut(*sd)) ||
         !RecvData(*sd,
                   &timeOut,
                   &timeOutDescriptor,
                   1,
                   PktTimeOut(*sd))) {
        DROP_SOCKET(sd);
        ERROR("ProcessRequest: receive failed\n");
      }
      else {
        object[objectDescriptor.repetitions] = '\0';
        (void)SendMessage(*sd, NS_REGISTERED, PktTimeOut(*sd));
        /* Change time-out period to an expiration time. */
        if(timeOut != 0) {
          timeOut += (unsigned long)CurrentTime();
        }
        DoRegister(object, timeOut);
      }
      free(object);
    }
    break;

  case NS_SEARCH:
  case NS_UNREGISTER:
    patternDescriptor.repetitions = dataSize;
    pattern = (char *)malloc(dataSize);
    if(pattern == NULL) {
      (void)SendMessage(*sd, NS_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      if(!RecvData(*sd,
                   pattern,
                   &patternDescriptor,
                   1,
                   PktTimeOut(*sd))) {
        DROP_SOCKET(sd);
        ERROR("ProcessRequest: receive failed\n");
      }
      else if(messageType == NS_SEARCH) {
        matching = DoSearch(pattern);
        if(matching == NULL) {
          (void)SendMessage(*sd, NS_FAILED, PktTimeOut(*sd));
          ERROR("ProcessRequest: out of memory\n");
        }
        else {
          objectDescriptor.repetitions = strlen(matching) + 1;
          (void)SendMessageAndData(*sd,
                                   NS_SEARCHED,
                                   matching,
                                   &objectDescriptor,
                                   1,
                                   PktTimeOut(*sd));
          free(matching);
        }
      }
      else {
        DoUnregister(pattern);
        (void)SendMessage(*sd, NS_UNREGISTERED, PktTimeOut(*sd));
      }
      free(pattern);
    }
    break;

  default:
    ERROR1("ProcessRequest: unknown message %d\n", messageType);

  }

}
Example #14
0
/**
 * @TODO
 */
int
build_ann_index(char *bname)
{
	char docid2path[PATH_MAX], indexfile[PATH_MAX];
	char annpath[PATH_MAX];
	char ndocsfile[PATH_MAX];
	int ret;
	int result = -1;
	FILE *fp;
	
	
	snprintf(annpath, sizeof(annpath), "data/0Announce/%s", bname);
	set_anndocid2path_file(docid2path, bname);
	set_annindex_file(indexfile, bname);

	/* Initialize the DB structure.*/
	ret = db_create(&g_dbp, NULL, 0);
	if (ret != 0) {
		ERROR("create db hanldle failed");
		goto RETURN;
	}

	if (dbopen(g_dbp, docid2path, 1) != 0) {
		ERROR1("open db %s failed", docid2path);
		goto RETURN;		
	}

	g_bucket = new_postinglist_bucket(g_size);
	if (g_bucket == NULL) {
		ERROR1("new_postinglist_bucket size=%u failed", g_size);
		goto CLEAN_DB;
	}

	g_text = malloc(MAX_FILE_SIZE);
	if (g_text == NULL) {
		ERROR("malloc failed");
		goto CLEAN_MEM;
	}

	/* Zero out the DBTs before using them. */
	memset(&g_key, 0, sizeof(DBT));
	memset(&g_data, 0, sizeof(DBT));
	
	g_key.size = sizeof(unsigned int);
	g_key.data = &g_docid;

	/* TODO: cache, ensure the cache directory exists */
	ann_traverse(annpath, index_file);
	write_index_file(g_bucket, g_size, indexfile);
	calc_doc_weight(bname, ANNOUNCE, g_docid - 1);
	set_annndocs_file(ndocsfile, bname);
	fp = fopen(ndocsfile, "w");
	if (fp == NULL) {
		ERROR1("fopen %s failed", ndocsfile);
		goto CLEAN;
	}
	fprintf(fp, "%u", g_docid - 1);
	fclose(fp);

	/* it's ok */
	result = 0;
CLEAN:	
	free(g_text);	
CLEAN_MEM:
	free(g_bucket);
CLEAN_DB:
	if (g_dbp != NULL)
		g_dbp->close(g_dbp, 0);
RETURN:
	return result;
}
Example #15
0
File: admin.c Project: krattai/AEBL
void admin_handle_request(client_t *client, const char *uri)
{
    const char *mount, *command_string;
    int command;

    DEBUG1("Admin request (%s)", uri);
    if (!((strcmp(uri, "/admin.cgi") == 0) ||
         (strncmp("/admin/", uri, 7) == 0))) {
        ERROR0("Internal error: admin request isn't");
        client_send_401(client);
        return;
    }

    if (strcmp(uri, "/admin.cgi") == 0) {
        command_string = uri + 1;
    }
    else {
        command_string = uri + 7;
    }

    DEBUG1("Got command (%s)", command_string);
    command = admin_get_command(command_string);

    if(command < 0) {
        ERROR1("Error parsing command string or unrecognised command: %s",
                command_string);
        client_send_400(client, "Unrecognised command");
        return;
    }

    if (command == COMMAND_SHOUTCAST_METADATA_UPDATE) {

        ice_config_t *config;
        const char *sc_mount;
        const char *pass = httpp_get_query_param (client->parser, "pass");
        listener_t *listener;

        if (pass == NULL)
        {
            client_send_400 (client, "missing pass parameter");
            return;
        }
        config = config_get_config ();
        sc_mount = config->shoutcast_mount;
        listener = config_get_listen_sock (config, client->con);
        if (listener && listener->shoutcast_mount)
            sc_mount = listener->shoutcast_mount;

        httpp_set_query_param (client->parser, "mount", sc_mount);
        httpp_setvar (client->parser, HTTPP_VAR_PROTOCOL, "ICY");
        httpp_setvar (client->parser, HTTPP_VAR_ICYPASSWORD, pass);
        config_release_config ();
    }

    mount = httpp_get_query_param(client->parser, "mount");

    if(mount != NULL) {
        source_t *source;

        /* this request does not require auth but can apply to files on webroot */
        if (command == COMMAND_BUILDM3U)
        {
            command_buildm3u (client, mount);
            return;
        }
        /* This is a mount request, handle it as such */
        if (!connection_check_admin_pass(client->parser))
        {
            if (!connection_check_source_pass(client->parser, mount))
            {
                INFO1("Bad or missing password on mount modification admin "
                        "request (command: %s)", command_string);
                client_send_401(client);
                return;
            }
        }
        
        avl_tree_rlock(global.source_tree);
        source = source_find_mount_raw(mount);

        if (source == NULL)
        {
            WARN2("Admin command %s on non-existent source %s", 
                    command_string, mount);
            avl_tree_unlock(global.source_tree);
            client_send_400(client, "Source does not exist");
        }
        else
        {
            if (source->running == 0 && source->on_demand == 0)
            {
                avl_tree_unlock (global.source_tree);
                INFO2("Received admin command %s on unavailable mount \"%s\"",
                        command_string, mount);
                client_send_400 (client, "Source is not available");
                return;
            }
            if (command == COMMAND_SHOUTCAST_METADATA_UPDATE &&
                    source->shoutcast_compat == 0)
            {
                avl_tree_unlock (global.source_tree);
                ERROR0 ("illegal change of metadata on non-shoutcast "
                        "compatible stream");
                client_send_400 (client, "illegal metadata call");
                return;
            }
            INFO2("Received admin command %s on mount \"%s\"", 
                    command_string, mount);
            admin_handle_mount_request(client, source, command);
            avl_tree_unlock(global.source_tree);
        }
    }
    else {

        if (command == COMMAND_PLAINTEXT_LISTSTREAM) {
        /* this request is used by a slave relay to retrieve
           mounts from the master, so handle this request
           validating against the relay password */
            if(!connection_check_relay_pass(client->parser)) {
                INFO1("Bad or missing password on admin command "
                      "request (command: %s)", command_string);
                client_send_401(client);
                return;
            }
        }
        else {
            if(!connection_check_admin_pass(client->parser)) {
                INFO1("Bad or missing password on admin command "
                      "request (command: %s)", command_string);
                client_send_401(client);
                return;
            }
        }
        
        admin_handle_general_request(client, command);
    }
}
Example #16
0
File: tfits.c Project: epowers/mpfr
int
main (void)
{
  mpfr_t x, y;
  int i, r;

  tests_start_mpfr ();

  mpfr_init2 (x, 256);
  mpfr_init2 (y, 8);

  RND_LOOP (r)
    {

      /* Check NAN */
      mpfr_set_nan (x);
      if (mpfr_fits_ulong_p (x, (mpfr_rnd_t) r))
        ERROR1 (1);
      if (mpfr_fits_slong_p (x, (mpfr_rnd_t) r))
        ERROR1 (2);
      if (mpfr_fits_uint_p (x, (mpfr_rnd_t) r))
        ERROR1 (3);
      if (mpfr_fits_sint_p (x, (mpfr_rnd_t) r))
        ERROR1 (4);
      if (mpfr_fits_ushort_p (x, (mpfr_rnd_t) r))
        ERROR1 (5);
      if (mpfr_fits_sshort_p (x, (mpfr_rnd_t) r))
        ERROR1 (6);

      /* Check INF */
      mpfr_set_inf (x, 1);
      if (mpfr_fits_ulong_p (x, (mpfr_rnd_t) r))
        ERROR1 (7);
      if (mpfr_fits_slong_p (x, (mpfr_rnd_t) r))
        ERROR1 (8);
      if (mpfr_fits_uint_p (x, (mpfr_rnd_t) r))
        ERROR1 (9);
      if (mpfr_fits_sint_p (x, (mpfr_rnd_t) r))
        ERROR1 (10);
      if (mpfr_fits_ushort_p (x, (mpfr_rnd_t) r))
        ERROR1 (11);
      if (mpfr_fits_sshort_p (x, (mpfr_rnd_t) r))
        ERROR1 (12);

      /* Check Zero */
      MPFR_SET_ZERO (x);
      if (!mpfr_fits_ulong_p (x, (mpfr_rnd_t) r))
        ERROR1 (13);
      if (!mpfr_fits_slong_p (x, (mpfr_rnd_t) r))
        ERROR1 (14);
      if (!mpfr_fits_uint_p (x, (mpfr_rnd_t) r))
        ERROR1 (15);
      if (!mpfr_fits_sint_p (x, (mpfr_rnd_t) r))
        ERROR1 (16);
      if (!mpfr_fits_ushort_p (x, (mpfr_rnd_t) r))
        ERROR1 (17);
      if (!mpfr_fits_sshort_p (x, (mpfr_rnd_t) r))
        ERROR1 (18);

      /* Check small positive op */
      mpfr_set_str1 (x, "1@-1");
      if (!mpfr_fits_ulong_p (x, (mpfr_rnd_t) r))
        ERROR1 (19);
      if (!mpfr_fits_slong_p (x, (mpfr_rnd_t) r))
        ERROR1 (20);
      if (!mpfr_fits_uint_p (x, (mpfr_rnd_t) r))
        ERROR1 (21);
      if (!mpfr_fits_sint_p (x, (mpfr_rnd_t) r))
        ERROR1 (22);
      if (!mpfr_fits_ushort_p (x, (mpfr_rnd_t) r))
        ERROR1 (23);
      if (!mpfr_fits_sshort_p (x, (mpfr_rnd_t) r))
        ERROR1 (24);

      /* Check 17 */
      mpfr_set_ui (x, 17, MPFR_RNDN);
      if (!mpfr_fits_ulong_p (x, (mpfr_rnd_t) r))
        ERROR1 (25);
      if (!mpfr_fits_slong_p (x, (mpfr_rnd_t) r))
        ERROR1 (26);
      if (!mpfr_fits_uint_p (x, (mpfr_rnd_t) r))
        ERROR1 (27);
      if (!mpfr_fits_sint_p (x, (mpfr_rnd_t) r))
        ERROR1 (28);
      if (!mpfr_fits_ushort_p (x, (mpfr_rnd_t) r))
        ERROR1 (29);
      if (!mpfr_fits_sshort_p (x, (mpfr_rnd_t) r))
        ERROR1 (30);

      /* Check all other values */
      mpfr_set_ui (x, ULONG_MAX, MPFR_RNDN);
      mpfr_mul_2exp (x, x, 1, MPFR_RNDN);
      if (mpfr_fits_ulong_p (x, (mpfr_rnd_t) r))
        ERROR1 (31);
      if (mpfr_fits_slong_p (x, (mpfr_rnd_t) r))
        ERROR1 (32);
      mpfr_mul_2exp (x, x, 40, MPFR_RNDN);
      if (mpfr_fits_ulong_p (x, (mpfr_rnd_t) r))
        ERROR1 (33);
      if (mpfr_fits_uint_p (x, (mpfr_rnd_t) r))
        ERROR1 (34);
      if (mpfr_fits_sint_p (x, (mpfr_rnd_t) r))
        ERROR1 (35);
      if (mpfr_fits_ushort_p (x, (mpfr_rnd_t) r))
        ERROR1 (36);
      if (mpfr_fits_sshort_p (x, (mpfr_rnd_t) r))
        ERROR1 (37);

      mpfr_set_ui (x, ULONG_MAX, MPFR_RNDN);
      if (!mpfr_fits_ulong_p (x, (mpfr_rnd_t) r))
        ERROR1 (38);
      mpfr_set_ui (x, LONG_MAX, MPFR_RNDN);
      if (!mpfr_fits_slong_p (x, (mpfr_rnd_t) r))
        ERROR1 (39);
      mpfr_set_ui (x, UINT_MAX, MPFR_RNDN);
      if (!mpfr_fits_uint_p (x, (mpfr_rnd_t) r))
        ERROR1 (40);
      mpfr_set_ui (x, INT_MAX, MPFR_RNDN);
      if (!mpfr_fits_sint_p (x, (mpfr_rnd_t) r))
        ERROR1 (41);
      mpfr_set_ui (x, USHRT_MAX, MPFR_RNDN);
      if (!mpfr_fits_ushort_p (x, (mpfr_rnd_t) r))
        ERROR1 (42);
      mpfr_set_ui (x, SHRT_MAX, MPFR_RNDN);
      if (!mpfr_fits_sshort_p (x, (mpfr_rnd_t) r))
        ERROR1 (43);

      mpfr_set_si (x, 1, MPFR_RNDN);
      if (!mpfr_fits_sint_p (x, (mpfr_rnd_t) r))
        ERROR1 (44);
      if (!mpfr_fits_sshort_p (x, (mpfr_rnd_t) r))
        ERROR1 (45);

      /* Check negative op */
      for (i = 1; i <= 4; i++)
        {
          int inv;

          mpfr_set_si_2exp (x, -i, -2, MPFR_RNDN);
          mpfr_rint (y, x, (mpfr_rnd_t) r);
          inv = MPFR_NOTZERO (y);
          if (!mpfr_fits_ulong_p (x, (mpfr_rnd_t) r) ^ inv)
            ERROR1 (46);
          if (!mpfr_fits_slong_p (x, (mpfr_rnd_t) r))
            ERROR1 (47);
          if (!mpfr_fits_uint_p (x, (mpfr_rnd_t) r) ^ inv)
            ERROR1 (48);
          if (!mpfr_fits_sint_p (x, (mpfr_rnd_t) r))
            ERROR1 (49);
          if (!mpfr_fits_ushort_p (x, (mpfr_rnd_t) r) ^ inv)
            ERROR1 (50);
          if (!mpfr_fits_sshort_p (x, (mpfr_rnd_t) r))
            ERROR1 (51);
        }
    }

  mpfr_clear (x);
  mpfr_clear (y);

  check_intmax ();

  tests_end_mpfr ();
  return 0;
}
Example #17
0
Bool
HandleVModDef(VModDef *stmt,unsigned mergeMode,VModInfo *info)
{
register int 	i,bit,nextFree;
ExprResult 	mod;
XkbServerMapPtr	srv;
XkbNamesPtr	names;
Atom		stmtName;
    
    srv= info->xkb->server;
    names= info->xkb->names;
    stmtName= XkbInternAtom(info->xkb->dpy,XkbAtomGetString(NULL,stmt->name),
    									False);
    for (i=0,bit=1,nextFree= -1;i<XkbNumVirtualMods;i++,bit<<=1) {
	if (info->defined&bit) {
	    if (names->vmods[i]==stmtName) {	/* already defined */
		info->available|= bit;
		if (stmt->value==NULL)
		    return True;
		else {
		    char *str1,*str2 = "";
		    if (!ExprResolveModMask(stmt->value,&mod,NULL,NULL)) {
			str1= XkbAtomText(NULL,stmt->name,XkbMessage);
			ACTION1("Declaration of %s ignored\n",str1);
			return False;
		    }
		    if (mod.uval==srv->vmods[i])
			return True;

		    str1= XkbAtomText(NULL,stmt->name,XkbMessage);
		    WARN1("Virtual modifier %s multiply defined\n",str1);
		    str1= XkbModMaskText(srv->vmods[i],XkbCFile);
		    if (mergeMode==MergeOverride) {
			str2= str1;
			str1= XkbModMaskText(mod.uval,XkbCFile);
		    }
		    ACTION2("Using %s, ignoring %s\n",str1,str2);
		    if (mergeMode==MergeOverride)
			srv->vmods[i]= mod.uval;
		    return True;
		}
	    }
	}
	else if (nextFree<0)
	    nextFree= i;
    }
    if (nextFree<0) {
	ERROR1("Too many virtual modifiers defined (maximum %d)\n",
						XkbNumVirtualMods);
	ACTION("Exiting\n");
	return False;
    }
    info->defined|= (1<<nextFree);
    info->newlyDefined|= (1<<nextFree);
    info->available|= (1<<nextFree);
    names->vmods[nextFree]= stmtName;
    if (stmt->value==NULL)
	return True;
    if (ExprResolveModMask(stmt->value,&mod,NULL,NULL)) {
	srv->vmods[nextFree]= mod.uval;
	return True;
    }
    ACTION1("Declaration of %s ignored\n",
    				XkbAtomText(NULL,stmt->name,XkbMessage));
    return False;
}
Example #18
0
/* called when listening thread is not checking for incoming connections */
int connection_setup_sockets (ice_config_t *config)
{
    int count = 0;
    listener_t *listener, **prev;

    free (banned_ip.filename);
    banned_ip.filename = NULL;
    free (allowed_ip.filename);
    allowed_ip.filename = NULL;

    global_lock();
    if (global.serversock)
    {
        for (; count < global.server_sockets; count++)
            sock_close (global.serversock [count]);
        free (global.serversock);
        global.serversock = NULL;
    }
    if (config == NULL)
    {
        global_unlock();
        return 0;
    }

    /* setup the banned/allowed IP filenames from the xml */
    if (config->banfile)
        banned_ip.filename = strdup (config->banfile);

    if (config->allowfile)
        allowed_ip.filename = strdup (config->allowfile);

    count = 0;
    global.serversock = calloc (config->listen_sock_count, sizeof (sock_t));

    listener = config->listen_sock; 
    prev = &config->listen_sock;
    while (listener)
    {
        int successful = 0;

        do
        {
            sock_t sock = sock_get_server_socket (listener->port, listener->bind_address);
            if (sock == SOCK_ERROR)
                break;
            if (sock_listen (sock, ICE_LISTEN_QUEUE) == SOCK_ERROR)
            {
                sock_close (sock);
                break;
            }
            /* some win32 setups do not do TCP win scaling well, so allow an override */
            if (listener->so_sndbuf)
                sock_set_send_buffer (sock, listener->so_sndbuf);
            sock_set_blocking (sock, 0);
            successful = 1;
            global.serversock [count] = sock;
            count++;
        } while(0);
        if (successful == 0)
        {
            if (listener->bind_address)
                ERROR2 ("Could not create listener socket on port %d bind %s",
                        listener->port, listener->bind_address);
            else
                ERROR1 ("Could not create listener socket on port %d", listener->port);
            /* remove failed connection */
            *prev = config_clear_listener (listener);
            listener = *prev;
            continue;
        }
        if (listener->bind_address)
            INFO2 ("listener socket on port %d address %s", listener->port, listener->bind_address);
        else
            INFO1 ("listener socket on port %d", listener->port);
        prev = &listener->next;
        listener = listener->next;
    }
    global.server_sockets = count;
    global_unlock();

    if (count == 0)
        ERROR0 ("No listening sockets established");

    return count;
}
void* PORT_Open(INT32 mixerIndex) {
    char devname[16];
    snd_mixer_t* mixer_handle;
    int err;
    PortMixer* handle;

    TRACE0("> PORT_Open\n");
    sprintf(devname, ALSA_HARDWARE_CARD, (int) mixerIndex);
    if ((err = snd_mixer_open(&mixer_handle, 0)) < 0) {
        ERROR2("Mixer %s open error: %s", devname, snd_strerror(err));
        return NULL;
    }
    if ((err = snd_mixer_attach(mixer_handle, devname)) < 0) {
        ERROR2("Mixer attach %s error: %s", devname, snd_strerror(err));
        snd_mixer_close(mixer_handle);
        return NULL;
    }
    if ((err = snd_mixer_selem_register(mixer_handle, NULL, NULL)) < 0) {
        ERROR1("Mixer register error: %s", snd_strerror(err));
        snd_mixer_close(mixer_handle);
        return NULL;
    }
    err = snd_mixer_load(mixer_handle);
    if (err < 0) {
        ERROR2("Mixer %s load error: %s", devname, snd_strerror(err));
        snd_mixer_close(mixer_handle);
        return NULL;
    }
    handle = (PortMixer*) calloc(1, sizeof(PortMixer));
    if (handle == NULL) {
        ERROR0("malloc() failed.");
        snd_mixer_close(mixer_handle);
        return NULL;
    }
    handle->numElems = 0;
    handle->elems = (snd_mixer_elem_t**) calloc(MAX_ELEMS, sizeof(snd_mixer_elem_t*));
    if (handle->elems == NULL) {
        ERROR0("malloc() failed.");
        snd_mixer_close(mixer_handle);
        free(handle);
        return NULL;
    }
    handle->types = (INT32*) calloc(MAX_ELEMS, sizeof(INT32));
    if (handle->types == NULL) {
        ERROR0("malloc() failed.");
        snd_mixer_close(mixer_handle);
        free(handle->elems);
        free(handle);
        return NULL;
    }
    handle->controls = (PortControl*) calloc(MAX_CONTROLS, sizeof(PortControl));
    if (handle->controls == NULL) {
        ERROR0("malloc() failed.");
        snd_mixer_close(mixer_handle);
        free(handle->elems);
        free(handle->types);
        free(handle);
        return NULL;
    }
    handle->mixer_handle = mixer_handle;
    // necessary to initialize data structures
    PORT_GetPortCount(handle);
    TRACE0("< PORT_Open\n");
    return handle;
}
Example #20
0
File: run_erl.c Project: Bwooce/otp
int main(int argc, char **argv)
{
  int childpid;
  int sfd;
  int fd;
  char *p, *ptyslave=NULL;
  int i = 1;
  int off_argv;

  program_name = argv[0];

  if(argc<4) {
    usage(argv[0]);
    exit(1);
  }

  init_outbuf();

  if (!strcmp(argv[1],"-daemon")) {
      daemon_init();
      ++i;
  }

  off_argv = i;
  strn_cpy(pipename, sizeof(pipename), argv[i++]);
  strn_cpy(log_dir, sizeof(log_dir), argv[i]);
  strn_cpy(statusfile, sizeof(statusfile), log_dir);
  strn_cat(statusfile, sizeof(statusfile), STATUSFILENAME);

#ifdef DEBUG
  status("%s: pid is : %d\n", argv[0], getpid());
#endif

  /* Get values for LOG file handling from the environment */
  if ((p = getenv("RUN_ERL_LOG_ALIVE_MINUTES"))) {
      log_alive_minutes = atoi(p);
      if (!log_alive_minutes) {
	  ERROR1(LOG_ERR,"Minimum value for RUN_ERL_LOG_ALIVE_MINUTES is 1 "
		 "(current value is %s)",p);
      }
      log_activity_minutes = log_alive_minutes / 3;
      if (!log_activity_minutes) {
	  ++log_activity_minutes;
      }
  }
  if ((p = getenv("RUN_ERL_LOG_ACTIVITY_MINUTES"))) {
     log_activity_minutes = atoi(p);
      if (!log_activity_minutes) {
	  ERROR1(LOG_ERR,"Minimum value for RUN_ERL_LOG_ACTIVITY_MINUTES is 1 "
		 "(current value is %s)",p);
      }
  } 
  if ((p = getenv("RUN_ERL_LOG_ALIVE_FORMAT"))) {
      if (strlen(p) > ALIVE_BUFFSIZ) {
	  ERROR1(LOG_ERR, "RUN_ERL_LOG_ALIVE_FORMAT can contain a maximum of "
		 "%d characters", ALIVE_BUFFSIZ);
      }
      strn_cpy(log_alive_format, sizeof(log_alive_format), p);
  } else {
      strn_cpy(log_alive_format, sizeof(log_alive_format), DEFAULT_LOG_ALIVE_FORMAT);
  }
  if ((p = getenv("RUN_ERL_LOG_ALIVE_IN_UTC")) && strcmp(p,"0")) {
      ++log_alive_in_gmt;
  }
  if ((p = getenv("RUN_ERL_LOG_GENERATIONS"))) {
    log_generations = atoi(p);
    if (log_generations < LOG_MIN_GENERATIONS)
      ERROR1(LOG_ERR,"Minimum RUN_ERL_LOG_GENERATIONS is %d", LOG_MIN_GENERATIONS);
    if (log_generations > LOG_MAX_GENERATIONS)
      ERROR1(LOG_ERR,"Maximum RUN_ERL_LOG_GENERATIONS is %d", LOG_MAX_GENERATIONS);
  }

  if ((p = getenv("RUN_ERL_LOG_MAXSIZE"))) {
    log_maxsize = atoi(p);
    if (log_maxsize < LOG_MIN_MAXSIZE)
      ERROR1(LOG_ERR,"Minimum RUN_ERL_LOG_MAXSIZE is %d", LOG_MIN_MAXSIZE);
  }

  /*
   * Create FIFOs and open them 
   */

  if(*pipename && pipename[strlen(pipename)-1] == '/') {
    /* The user wishes us to find a unique pipe name in the specified */
    /* directory */
    int highest_pipe_num = 0;
    DIR *dirp;
    struct dirent *direntp;

    dirp = opendir(pipename);
    if(!dirp) {
      ERRNO_ERR1(LOG_ERR,"Can't access pipe directory '%s'.", pipename);
      exit(1);
    }

    /* Check the directory for existing pipes */
    
    while((direntp=readdir(dirp)) != NULL) {
      if(strncmp(direntp->d_name,PIPE_STUBNAME,PIPE_STUBLEN)==0) {
	int num = atoi(direntp->d_name+PIPE_STUBLEN+1);
	if(num > highest_pipe_num)
	  highest_pipe_num = num;
      }
    }	
    closedir(dirp);
    strn_catf(pipename, sizeof(pipename), "%s.%d",
	      PIPE_STUBNAME, highest_pipe_num+1);
  } /* if */

  /* write FIFO - is read FIFO for `to_erl' program */
  strn_cpy(fifo1, sizeof(fifo1), pipename);
  strn_cat(fifo1, sizeof(fifo1), ".r");
  if (create_fifo(fifo1, PERM) < 0) {
    ERRNO_ERR1(LOG_ERR,"Cannot create FIFO %s for writing.", fifo1);
    exit(1);
  }

  /* read FIFO - is write FIFO for `to_erl' program */
  strn_cpy(fifo2, sizeof(fifo2), pipename);
  strn_cat(fifo2, sizeof(fifo2), ".w");

  /* Check that nobody is running run_erl already */
  if ((fd = open (fifo2, O_WRONLY|DONT_BLOCK_PLEASE, 0)) >= 0) {
    /* Open as client succeeded -- run_erl is already running! */
    fprintf(stderr, "Erlang already running on pipe %s.\n", pipename);
    close(fd);
    exit(1);
  }
  if (create_fifo(fifo2, PERM) < 0) { 
    ERRNO_ERR1(LOG_ERR,"Cannot create FIFO %s for reading.", fifo2);
    exit(1);
  }

  /*
   * Open master pseudo-terminal
   */

  if ((mfd = open_pty_master(&ptyslave)) < 0) {
    ERRNO_ERR0(LOG_ERR,"Could not open pty master");
    exit(1);
  }

  /* 
   * Now create a child process
   */

  if ((childpid = fork()) < 0) {
    ERRNO_ERR0(LOG_ERR,"Cannot fork");
    exit(1);
  }
  if (childpid == 0) {
    /* Child */
    close(mfd);
    /* disassociate from control terminal */
#ifdef USE_SETPGRP_NOARGS       /* SysV */
    setpgrp();
#elif defined(USE_SETPGRP)       /* BSD */
    setpgrp(0,getpid());
#else                           /* POSIX */
    setsid();
#endif
    /* Open the slave pty */
    if ((sfd = open_pty_slave(ptyslave)) < 0) {
      ERRNO_ERR1(LOG_ERR,"Could not open pty slave '%s'", ptyslave);
      exit(1);
    }
    /* But sfd may be one of the stdio fd's now, and we should be unmodern and not use dup2... */
    /* easiest to dup it up... */
    while (sfd < 3) {
	sfd = dup(sfd);
    }

#ifndef NO_SYSLOG
    /* Before fiddling with file descriptors we make sure syslog is turned off
       or "closed". In the single case where we might want it again, 
       we will open it again instead. Would not want syslog to
       go to some other fd... */
    if (run_daemon) {
	closelog();
    }
#endif

    /* Close stdio */
    close(0);
    close(1);
    close(2);

    if (dup(sfd) != 0 || dup(sfd) != 1 || dup(sfd) != 2) {
      status("Cannot dup\n");
    }
    close(sfd);
    exec_shell(argv+off_argv); /* exec_shell expects argv[2] to be */
                        /* the command name, so we have to */
                        /* adjust. */
  } else {
    /* Parent */
    /* Ignore the SIGPIPE signal, write() will return errno=EPIPE */
    struct sigaction sig_act;
    sigemptyset(&sig_act.sa_mask);
    sig_act.sa_flags = 0;
    sig_act.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &sig_act, (struct sigaction *)NULL);

    sigemptyset(&sig_act.sa_mask);
    sig_act.sa_flags = SA_NOCLDSTOP;
    sig_act.sa_handler = catch_sigchild;
    sigaction(SIGCHLD, &sig_act, (struct sigaction *)NULL);

    /*
     * read and write: enter the workloop
     */

    pass_on(childpid);
  }
  return 0;
} /* main() */
Example #21
0
// Aquire and enabled audio card
// return 0 if ok, -1 if failed
int HAE_AquireAudioCapture(void *context, UINT32 encoding, UINT32 sampleRate, UINT32 channels, UINT32 bits,
			   UINT32 audioFramesPerBuffer, UINT_PTR *pCaptureHandle) {
    audio_info_t sunAudioHeader;
    INT32 error = -1;
	
    char* pAudioDev = HAE_GetAudioDevRec(g_soundDeviceIndex, 0);
    INT32 minFramesPerBuffer;

    //fprintf(stderr, "Entering HAE_AquireAudioCapture(encoding=%d, samplerate=%d, channels=%d, bits=%d, framesPerBuffer=%d)\n", 
    //	encoding, sampleRate, channels, bits, audioFramesPerBuffer);

    g_encoding = encoding;
    g_bitSize = bits;
    g_channels = channels;
    g_sampleRate = sampleRate;	

    if( audioFramesPerBuffer == 0 ) {
	audioFramesPerBuffer = sampleRate * HAE_SOLARIS_DEFAULT_BUFFERSIZE_IN_MS / 1000;
    }

    g_audioFramesToRead = audioFramesPerBuffer / g_audioCaptureBufferSizeDivisor;

    if (pCaptureHandle) {
	*pCaptureHandle = 0L;
    }

    // try to open wave device for recording
    // $$kk: 12.17.97: need O_NONBLOCK flag to be compatible with windows

    // $$kk: 10.13.98: we want O_NONBLOCK so that we return failure immediately if the
    // device is busy (or absent or whatever) rather than blocking.  however, i think that
    // this same O_NONBLOCK flag dictates whether the read() calls should block.  even 
    // without the O_NONBLOCK flag set, read() does *not* block for me, so i'm keeping 
    // the flag for now....
	
    g_captureSound = open(pAudioDev,O_RDONLY|O_NONBLOCK);

    if (g_captureSound > 0) {

	/* set to multiple open */
	if (ioctl(g_captureSound, AUDIO_MIXER_MULTIPLE_OPEN, NULL) >= 0) {
	    TRACE1("HAE_AquireAudioCapture: %s set to multiple open\n", pAudioDev);
	} else {
	    ERROR1("HAE_AquireAudioCapture: ioctl AUDIO_MIXER_MULTIPLE_OPEN failed on %s!\n", pAudioDev);
	}

	AUDIO_INITINFO(&sunAudioHeader);
		
	// Set capture format of the sun device.
	sunAudioHeader.record.sample_rate = sampleRate;
	sunAudioHeader.record.precision = bits;
	sunAudioHeader.record.channels = channels;
	sunAudioHeader.record.buffer_size = g_audioFramesToRead * channels * bits / 8;
		
	sunAudioHeader.record.encoding = AUDIO_ENCODING_LINEAR;
	if (g_encoding == ULAW) {
	    sunAudioHeader.record.encoding = AUDIO_ENCODING_ULAW;			
	} 
	else if (g_encoding == ALAW) {
	    sunAudioHeader.record.encoding = AUDIO_ENCODING_ALAW;			
	} 



	// start out paused so we don't overflow the device driver buffers
	sunAudioHeader.record.pause = 1;
	error = ioctl(g_captureSound, AUDIO_SETINFO, &sunAudioHeader);

	if (error != -1) {
	    // flush anything we might have accumulated in the capture queue before pausing
	    error = ioctl(g_captureSound, I_FLUSH, FLUSHR);

	    error = ioctl(g_captureSound, AUDIO_GETINFO, &sunAudioHeader);
	    g_audioFramesToRead = sunAudioHeader.record.buffer_size / (channels * bits / 8);


	    if (error != -1) {
		if (pCaptureHandle) {
		    *pCaptureHandle = (UINT_PTR)g_captureSound;
		}
	    } 
	}
    }

    if (error == -1) {	// something failed
	HAE_ReleaseAudioCapture(context);
    }

    //fprintf(stderr, "<< HAE_API_SolarisOS_Capture: HAE_AquireAudioCapture() returning %d\n", error);
    return error;
}
Example #22
0
//-----------------------------------------------------------------------------
int CCBRobot::findDevice( ARangeFinder* &device, std::string devName )
{
  if ( not mFgInitialized ) {
    PRT_WARN0( "Robot is not initialized, call init() first" );
    device = NULL;
    return 0; // error
  }

  if (( devName != CB_DEVICE_LASER ) &&
      ( devName != CB_DEVICE_WALL ) &&
      ( devName != CB_DEVICE_IR ) ) {
    ERROR1( "No such device: %s", devName.c_str() );
    device = NULL;
    return 0; // error
  }

  //************************************
  // Laser

  if ( devName == CB_DEVICE_LASER ) {
    // check if device already exists
    if ( mCBLaser == NULL ) {
      mCBLaser = new CCBLaser( mCBDriver, CB_DEVICE_LASER );
      device = mCBLaser;
      return mCBLaser->init();
    }

    // return already existing device
    device = mCBLaser;
    return 1; // success
  }

  //************************************
  // IR sensor
  if ( devName == CB_DEVICE_IR ) {
    // check if device already exists
    if ( mCBIrSensor == NULL ) {
      mCBIrSensor = new CCBIrSensor( mCBDriver, CB_DEVICE_IR );
      device = mCBIrSensor;
      return mCBIrSensor->init();
    }

    // return already existing device
    device = mCBIrSensor;
    return 1; // success
  }

  //************************************
  // Wall sensor
  if ( devName == CB_DEVICE_WALL ) {
    // check if device already exists
    if ( mCBWallSensor == NULL ) {
      mCBWallSensor = new CCBWallSensor( mCBDriver, CB_DEVICE_WALL );
      device = mCBWallSensor;
      return mCBWallSensor->init();
    }

    // return already existing device
    device = mCBWallSensor;
    return 1; // success
  }

  return 0; // should not be able to reach this, but silences compiler
}
Example #23
0
int erts_run_erl_log_init(int daemon, char* logdir) {
  char *p;

#ifdef __OSE__
  run_erl **re_pp;
  if (!run_erl_pp_key)
     ose_create_ppdata("run_erl_ppdata",&run_erl_pp_key);
  re_pp = (run_erl **)ose_get_ppdata(run_erl_pp_key);
  *re_pp = malloc(sizeof(run_erl));
#endif

  STDSTATUS = NULL;
  LOG_GENERATIONS = DEFAULT_LOG_GENERATIONS;
  LOG_MAXSIZE     = DEFAULT_LOG_MAXSIZE;
  LOG_ACTIVITY_MINUTES = DEFAULT_LOG_ACTIVITY_MINUTES;
  LOG_ALIVE_IN_GMT = 0;
  RUN_DAEMON = 0;
  LOG_ALIVE_MINUTES = DEFAULT_LOG_ALIVE_MINUTES;
  LFD = 0;
  PROTOCOL_VER = RUN_ERL_LO_VER; /* assume lowest to begin with */

  /* Get values for LOG file handling from the environment */
  if ((p = getenv_int("RUN_ERL_LOG_ALIVE_MINUTES"))) {
      LOG_ALIVE_MINUTES = atoi(p);
      if (!LOG_ALIVE_MINUTES) {
	  ERROR1(LOG_ERR,"Minimum value for RUN_ERL_LOG_ALIVE_MINUTES is 1 "
		 "(current value is %s)",p);
      }
      LOG_ACTIVITY_MINUTES = LOG_ALIVE_MINUTES / 3;
      if (!LOG_ACTIVITY_MINUTES) {
	  ++LOG_ACTIVITY_MINUTES;
      }
  }
  if ((p = getenv_int(
		   "RUN_ERL_LOG_ACTIVITY_MINUTES"))) {
     LOG_ACTIVITY_MINUTES = atoi(p);
      if (!LOG_ACTIVITY_MINUTES) {
	  ERROR1(LOG_ERR,"Minimum value for RUN_ERL_LOG_ACTIVITY_MINUTES is 1 "
		 "(current value is %s)",p);
      }
  }
  if ((p = getenv_int("RUN_ERL_LOG_ALIVE_FORMAT"))) {
      if (strlen(p) > ALIVE_BUFFSIZ) {
	  ERROR1(LOG_ERR, "RUN_ERL_LOG_ALIVE_FORMAT can contain a maximum of "
		 "%d characters", ALIVE_BUFFSIZ);
      }
      strn_cpy(LOG_ALIVE_FORMAT, sizeof(LOG_ALIVE_FORMAT), p);
  } else {
      strn_cpy(LOG_ALIVE_FORMAT, sizeof(LOG_ALIVE_FORMAT),
	       DEFAULT_LOG_ALIVE_FORMAT);
  }
  if ((p = getenv_int("RUN_ERL_LOG_ALIVE_IN_UTC"))
      && strcmp(p,"0")) {
      ++LOG_ALIVE_IN_GMT;
  }
  if ((p = getenv_int("RUN_ERL_LOG_GENERATIONS"))) {
    LOG_GENERATIONS = atoi(p);
    if (LOG_GENERATIONS < LOG_MIN_GENERATIONS)
      ERROR1(LOG_ERR,"Minimum RUN_ERL_LOG_GENERATIONS is %d",
	     LOG_MIN_GENERATIONS);
    if (LOG_GENERATIONS > LOG_MAX_GENERATIONS)
      ERROR1(LOG_ERR,"Maximum RUN_ERL_LOG_GENERATIONS is %d",
	     LOG_MAX_GENERATIONS);
  }

  if ((p = getenv_int("RUN_ERL_LOG_MAXSIZE"))) {
    LOG_MAXSIZE = atoi(p);
    if (LOG_MAXSIZE < LOG_MIN_MAXSIZE)
      ERROR1(LOG_ERR,"Minimum RUN_ERL_LOG_MAXSIZE is %d", LOG_MIN_MAXSIZE);
  }

  RUN_DAEMON = daemon;

  strn_cpy(LOG_DIR, sizeof(LOG_DIR), logdir);
  strn_cpy(STATUSFILE, sizeof(STATUSFILE), LOG_DIR);
  strn_cat(STATUSFILE, sizeof(STATUSFILE), STATUSFILENAME);

  return 0;
}
Example #24
0
//-----------------------------------------------------------------------------
int CCBRobot::findDevice( ABinarySensorArray* &device, std::string devName )
{
  if ( not mFgInitialized ) {
    PRT_WARN0( "Robot is not initialized, call init() first" );
    device = NULL;
    return 0; // error
  }

  if (( devName !=  CB_DEVICE_BUMPER ) &&
      ( devName !=  CB_DEVICE_VIRTUAL_WALL ) &&
      ( devName !=  CB_DEVICE_CLIFF ) &&
      ( devName !=  CB_DEVICE_OVERCURRENT ) &&
      ( devName !=  CB_DEVICE_BUTTON ) &&
      ( devName !=  CB_DEVICE_WHEEL_DROP ) ) {
    ERROR1( "No such device: %s", devName.c_str() );
    device = NULL;
    return 0; // error
  }

  //************************************
  // Bumper
  if ( devName ==  CB_DEVICE_BUMPER ) {
    // check if device already exists
    if ( mCBBumper == NULL ) {
      mCBBumper = new CCBBumper( mCBDriver,  CB_DEVICE_BUMPER );
      device = mCBBumper;
      return mCBBumper->init();
    }

    // return already existing device
    device = mCBBumper;
    return 1;
  }

  //************************************
  // Virtual wall
  if ( devName ==  CB_DEVICE_VIRTUAL_WALL ) {
    // check if device already exists
    if ( mCBVirtualWall == NULL ) {
      mCBVirtualWall = new CCBVirtualWallSensor( mCBDriver,  CB_DEVICE_VIRTUAL_WALL );
      device = mCBVirtualWall;
      return mCBVirtualWall->init();
    }

    // return already existing device
    device = mCBVirtualWall;
    return 1;
  }

  //************************************
  // Button
  if ( devName ==  CB_DEVICE_BUTTON ) {
    // check if device already exists
    if ( mCBCreateButton == NULL ) {
      mCBCreateButton = new CCBCreateButton( mCBDriver,  CB_DEVICE_BUTTON );
      device = mCBCreateButton;
      return mCBCreateButton->init();
    }

    // return already existing device
    device = mCBCreateButton;
    return 1;
  }

  //************************************
  // Wheel drop sensor
  if ( devName ==  CB_DEVICE_WHEEL_DROP ) {
    // check if device already exists
    if ( mCBWheelDropSensor == NULL ) {
      mCBWheelDropSensor =
        new CCBWheelDropSensor( mCBDriver, CB_DEVICE_WHEEL_DROP );
      device = mCBWheelDropSensor;
      return mCBWheelDropSensor->init();
    }

    // return already existing device
    device = mCBWheelDropSensor;
    return 1;
  }

  //************************************
  // Cliff sensor
  if ( devName ==  CB_DEVICE_CLIFF ) {
    // check if device already exists
    if ( mCBCliffSensor == NULL ) {
      mCBCliffSensor = new CCBCliffSensor( mCBDriver,  CB_DEVICE_CLIFF );
      device = mCBCliffSensor;
      return mCBCliffSensor->init();
    }

    // return already existing device
    device = mCBCliffSensor;
    return 1;
  }

  //************************************
  // Overcurrent sensor
  if ( devName ==  CB_DEVICE_OVERCURRENT ) {
    // check if device already exists
    if ( mCBOverCurrentSensor == NULL ) {
      mCBOverCurrentSensor = new CCBOverCurrentSensor( mCBDriver,  CB_DEVICE_OVERCURRENT );
      device = mCBOverCurrentSensor;
      return mCBOverCurrentSensor->init();
    }

    // return already existing device
    device = mCBOverCurrentSensor;
    return 1;
  }

  return 0; // should never get here
}
/*
  direction has to be either SND_RAWMIDI_STREAM_INPUT or
  SND_RAWMIDI_STREAM_OUTPUT.
  Returns 0 on success. Otherwise, MIDI_OUT_OF_MEMORY, MIDI_INVALID_ARGUMENT
   or a negative ALSA error code is returned.
*/
INT32 openMidiDevice(snd_rawmidi_stream_t direction, INT32 deviceIndex,
                     MidiDeviceHandle** handle) {
    snd_rawmidi_t* native_handle;
    snd_midi_event_t* event_parser = NULL;
    int err;
    UINT32 deviceID;
    char devicename[100];
#ifdef ALSA_MIDI_USE_PLUGHW
    int usePlugHw = 1;
#else
    int usePlugHw = 0;
#endif

    TRACE0("> openMidiDevice()\n");

    (*handle) = (MidiDeviceHandle*) calloc(sizeof(MidiDeviceHandle), 1);
    if (!(*handle)) {
        ERROR0("ERROR: openDevice: out of memory\n");
        return MIDI_OUT_OF_MEMORY;
    }

    // TODO: iterate to get dev ID from index
    err = getMidiDeviceID(direction, deviceIndex, &deviceID);
    TRACE1("  openMidiDevice(): deviceID: %d\n", (int) deviceID);
    getDeviceStringFromDeviceID(devicename, deviceID,
                                usePlugHw, ALSA_RAWMIDI);
    TRACE1("  openMidiDevice(): deviceString: %s\n", devicename);

    // finally open the device
    if (direction == SND_RAWMIDI_STREAM_INPUT) {
        err = snd_rawmidi_open(&native_handle, NULL, devicename,
                               SND_RAWMIDI_NONBLOCK);
    } else if (direction == SND_RAWMIDI_STREAM_OUTPUT) {
        err = snd_rawmidi_open(NULL, &native_handle, devicename,
                               SND_RAWMIDI_NONBLOCK);
    } else {
        ERROR0("  ERROR: openMidiDevice(): direction is neither SND_RAWMIDI_STREAM_INPUT nor SND_RAWMIDI_STREAM_OUTPUT\n");
        err = MIDI_INVALID_ARGUMENT;
    }
    if (err < 0) {
        ERROR1("<  ERROR: openMidiDevice(): snd_rawmidi_open() returned %d\n", err);
        free(*handle);
        (*handle) = NULL;
        return err;
    }
    /* We opened with non-blocking behaviour to not get hung if the device
       is used by a different process. Writing, however, should
       be blocking. So we change it here. */
    if (direction == SND_RAWMIDI_STREAM_OUTPUT) {
        err = snd_rawmidi_nonblock(native_handle, 0);
        if (err < 0) {
            ERROR1("  ERROR: openMidiDevice(): snd_rawmidi_nonblock() returned %d\n", err);
            snd_rawmidi_close(native_handle);
            free(*handle);
            (*handle) = NULL;
            return err;
        }
    }
    if (direction == SND_RAWMIDI_STREAM_INPUT) {
        err = snd_midi_event_new(EVENT_PARSER_BUFSIZE, &event_parser);
        if (err < 0) {
            ERROR1("  ERROR: openMidiDevice(): snd_midi_event_new() returned %d\n", err);
            snd_rawmidi_close(native_handle);
            free(*handle);
            (*handle) = NULL;
            return err;
        }
    }

    (*handle)->deviceHandle = (void*) native_handle;
    (*handle)->startTime = getTimeInMicroseconds();
    (*handle)->platformData = event_parser;
    TRACE0("< openMidiDevice(): succeeded\n");
    return err;
}
Example #26
0
void svf_loop()
{
	int sockfd = 0;
	unsigned int clilen = 0;
	int so_reuseaddr_option = 1;
	struct sockaddr_in svf_addr, cli_addr;
	int retflag = 0;

	// svf server initiliaze
	WORD wVersionRequested;
	WSADATA wsaData;
	wVersionRequested = MAKEWORD( 2, 2 );
	if (WSAStartup(wVersionRequested, &wsaData) != 0)
	{
		WARNING("Failed to Open Winsock \n");
		WARNING("Press any key to exit \n");
		getchar();
		exit(-1);
	}
	
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		ERROR1("error creating socket \n");
		exit(-1);
	}
	/* allow a host address can be use by many sockets*/
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void*)&so_reuseaddr_option, sizeof(int));
	memset((char *) &svf_addr, 0, sizeof(svf_addr));
	svf_addr.sin_family = AF_INET;
	svf_addr.sin_addr.s_addr = INADDR_ANY;
	svf_addr.sin_port = htons(svf_port);
	if (bind(sockfd, (struct sockaddr *) &svf_addr, sizeof(svf_addr)) == -1)
	{
		ERROR1("couldn't bind to socket \n");
		exit(-1);
	}
	printf("svf interface: using port %d \n", svf_port);
	if (listen(sockfd, 5) == -1)
	{
		ERROR1("couldn't listen on socket \n");
		getchar();
		exit(-1);
	}
	clilen = sizeof(cli_addr);

	svfnewsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
	printf("connectioned to port %d \n", svf_port);
	
	while (shutdown_svf)
	{
		if (svfnewsockfd == -1)
		{
			ERROR1("error on accept! \n");
			getchar();
		exit(-1);
		}
		retflag = svf_input();
		if ( retflag != ERROR_OK)
		{
			shutdown_svf = 0;
		}
	
	}
	shutdown_svf = 1;
	close_socket(sockfd);
	close_socket(svfnewsockfd);
	printf("\n");
	return ;
}
Example #27
0
void xslt_transform(xmlDocPtr doc, const char *xslfilename, client_t *client)
{
    xmlDocPtr    res;
    xsltStylesheetPtr cur;
    xmlChar *string;
    int len, problem = 0;
    const char *mediatype = NULL;

    xmlSetGenericErrorFunc ("", log_parse_failure);
    xsltSetGenericErrorFunc ("", log_parse_failure);

    thread_mutex_lock(&xsltlock);
    cur = xslt_get_stylesheet(xslfilename);

    if (cur == NULL)
    {
        thread_mutex_unlock(&xsltlock);
        ERROR1 ("problem reading stylesheet \"%s\"", xslfilename);
        client_send_404 (client, "Could not parse XSLT file");
        return;
    }

    res = xsltApplyStylesheet(cur, doc, NULL);

    if (xsltSaveResultToString (&string, &len, res, cur) < 0)
        problem = 1;

    /* lets find out the content type to use */
    if (cur->mediaType)
        mediatype = (char *)cur->mediaType;
    else
    {
        /* check method for the default, a missing method assumes xml */
        if (cur->method && xmlStrcmp (cur->method, XMLSTR("html")) == 0)
            mediatype = "text/html";
        else
            if (cur->method && xmlStrcmp (cur->method, XMLSTR("text")) == 0)
                mediatype = "text/plain";
            else
                mediatype = "text/xml";
    }
    if (problem == 0)
    {
        /* the 100 is to allow for the hardcoded headers */
        unsigned int full_len = strlen (mediatype) + len + 256;
        refbuf_t *refbuf = refbuf_new (full_len);
	ssize_t ret;

        if (string == NULL)
            string = xmlCharStrdup ("");
        ret = util_http_build_header(refbuf->data, full_len, 0, 0, 200, NULL, mediatype, NULL, NULL);
	snprintf (refbuf->data + ret, full_len - ret,
                "Content-Length: %d\r\n\r\n%s",
                len, string);

        client->respcode = 200;
        client_set_queue (client, NULL);
        client->refbuf = refbuf;
        refbuf->len = strlen (refbuf->data);
        fserve_add_client (client, NULL);
        xmlFree (string);
    }
    else
    {
        WARN1 ("problem applying stylesheet \"%s\"", xslfilename);
        client_send_404 (client, "XSLT problem");
    }
    thread_mutex_unlock (&xsltlock);
    xmlFreeDoc(res);
}
Example #28
0
/**1 output_file = new file()
  2 dict =  new hash()
  3 while (free memory available)
  4 do token = next_token()
  5     if token not in dict
  6  	   postinglist = addtodict(dict, token)
  7     else postinglist = getpostinglist(dict, token)
  8     if full(postinglist)
  9   	   postinglist = doublepostinglist(dict, token)
  10    addtopostinglist(postinglist, docid(token))
  11 sorted_terms = sortterm(dict)	// for merge purpose 
 *12 writeblock(sorted_terms, dict, output_file)
 */
int
build_board_index(char *bname)
{
	char *word;
	char dirfile[PATH_MAX], docid2path[PATH_MAX], indexfile[PATH_MAX];
	char filepath[PATH_MAX]; /* article file path */
	char filename[20];
	char cachedir[PATH_MAX];
	char cachefile[PATH_MAX];
	char ndocsfile[PATH_MAX];
	DB *dbp;
	DBT key, data;
	int ret;
	int result = -1;
	FILE *filelist, *fp;
	struct postinglist *p;
	unsigned int docid = 1;
	gzFile cachefp;
	int gzerr;

	
	setboardfile(dirfile, bname, bname);
	set_brddocid2path_file(docid2path, bname);
	set_brdindex_file(indexfile, bname);

	/* Initialize the  DB structure.*/
	ret = db_create(&dbp, NULL, 0);
	if (ret != 0) {
		ERROR("create db hanldle failed");
		goto RETURN;
	}

	if (dbopen(dbp, docid2path, 1) != 0) {
		ERROR1("open db %s failed", docid2path);
		goto RETURN;		
	}
		
	if (!(filelist = fopen(dirfile, "r"))) {
		ERROR1("open file %s failed", dirfile);
		goto CLEAN_DB;
	}
	
	size_t size = 300000;	/* TODO: define this constant */
	struct dict_t **bucket = new_postinglist_bucket(size);
	if (bucket == NULL) {
		ERROR1("new_dict size=%u failed", size);
		goto CLEAN_FP;
	}

	g_text = malloc(MAX_FILE_SIZE);
	if (g_text == NULL) {
		ERROR("malloc failed");
		goto CLEAN_MEM;
	}

	/* Zero out the DBTs before using them. */
	memset(&key, 0, sizeof(DBT));
	memset(&data, 0, sizeof(DBT));
	
	key.size = sizeof(unsigned int);
	key.data = &docid;
	
	/* ensure the cache directory exists */
	setcachepath(cachedir, bname);
	f_mkdir(cachedir, 0755);

	while (fgets(filename, sizeof(filename), filelist)) {
		filename[strlen(filename) - 1] = '\0';
	
		data.size = strlen(filename) + 1;
		data.data = filename;
		
		setboardfile(filepath, bname, filename);
		ansi_filter(filepath);
		
		if (g_len != 0) {
			fprintf(stderr, "%d indexing %s\n", docid, filename);
			/* save to cache file */
			setcachefile(cachefile, bname, filename);
			cachefp = gzopen(cachefile, "wb");
			if (cachefp != NULL) {
				if (gzwrite(cachefp, g_text, g_len) != g_len) 
					ERROR(gzerror(cachefp, &gzerr));
				gzclose(cachefp);
			}
			
			g_pos = 0;
			while ((word = next_token())) {
				//DEBUG1("%s", word);
				p = get_postinglist(bucket, size, word);
				if (p->freq == p->size) /* is full */
					double_postinglist(p);
				addto_postinglist(p, docid);
			}
			
			/* write_docid2path */
			dbp->put(dbp, NULL, &key, &data, 0);
			docid++;
		}
	}

	write_index_file(bucket, size, indexfile);
	calc_doc_weight(bname, BOARD, docid - 1);
	set_brdndocs_file(ndocsfile, bname);
	fp = fopen(ndocsfile, "w");
	if (fp == NULL) {
		ERROR1("fopen %s failed", ndocsfile);
		goto CLEAN;
	}
	fprintf(fp, "%u", docid - 1);
	fclose(fp);

	/* it's ok */
	result = 0;
CLEAN:	
	free(g_text);	
CLEAN_MEM:
	free(bucket);
CLEAN_FP:
	fclose(filelist);	
CLEAN_DB:
	if (dbp != NULL)
		dbp->close(dbp, 0);
RETURN:
	return result;
}
Example #29
0
		// add new line at the end of log file
		extern void userlog_append(t_account * account, const char * text)
		{
			// is logging enabled?
			if (!prefs_get_log_commands())
				return;
			
			unsigned int groups = 0;
			const char * cglist = prefs_get_log_command_groups();

			// convert string groups from config to integer
			for (int i = 0; i < strlen(cglist); i++)
			{
				if (cglist[i] == '1') groups |= 1;
				else if (cglist[i] == '2') groups |= 2;
				else if (cglist[i] == '3') groups |= 4;
				else if (cglist[i] == '4') groups |= 8;
				else if (cglist[i] == '5') groups |= 16;
				else if (cglist[i] == '6') groups |= 32;
				else if (cglist[i] == '7') groups |= 64;
				else if (cglist[i] == '8') groups |= 128;
			}

			// log only commands for admins/operators and users in "groups" defined in config
			if (!account_is_operator_or_admin(account, NULL) && !(account_get_command_groups(account) & groups))
				return;

			bool is_cmd_found = false;

			// if command list empty then log all commands
			if (userlog_commands.size() == 0)
				is_cmd_found = true;
			else
			{
				// get command name
				std::vector<std::string> args = split_command(text, 0);
				std::string cmd = args[0];

				// find command in defined command list
				for (std::vector<std::string>::iterator it = userlog_commands.begin(); it != userlog_commands.end(); ++it) {
					if (*it == cmd)
					{
						is_cmd_found = true;
						break;
					}
				}
			}
			if (!is_cmd_found)
				return;

			// get time string
			char        time_string[USEREVENT_TIME_MAXLEN];
			struct std::tm * tmnow;
			std::time_t      now;

			std::time(&now);
			if (!(tmnow = std::localtime(&now)))
				std::strcpy(time_string, "?");
			else
				std::strftime(time_string, USEREVENT_TIME_MAXLEN, USEREVENT_TIME_FORMAT, tmnow);


			char * filename = userlog_filename(account_get_name(account), true);

			if (FILE *fp = fopen(filename, "a"))
			{
				// append date and text
				std::fprintf(fp, "[%s] %s\n", time_string, text);
				std::fclose(fp);
			}
			else
			{
				ERROR1("could not write into user log file \"%s\"", filename);
			}
		}
Example #30
0
//该函数主要是创建DirectSound接口对象、设置协作级别以及创建辅助缓冲区
void* DAUDIO_Open(signed int mixerIndex, signed int deviceID, int isSource,
                  int encoding, float sampleRate /*44100*/, int sampleSizeInBits/*16*/,
                  int frameSize/*4*/, int channels/*2*/,
                  int isSigned, int isBigEndian, int bufferSizeInBytes)
{
    DS_Info* info;
    void* buffer;

    //TRACE0("> DAUDIO_Open\n");

    /* some sanity checks */
    if (deviceID >= g_cacheCount)
    {
        ERROR1("DAUDIO_Open: ERROR: cannot open the device with deviceID=%d!\n", deviceID);
        return NULL;
    }
    if ((g_audioDeviceCache[deviceID].isSource && !isSource) || (!g_audioDeviceCache[deviceID].isSource && isSource))
    {
        /* only support Playback or Capture */
        ERROR0("DAUDIO_Open: ERROR: Cache is corrupt: cannot open the device in specified isSource mode!\n");
        return NULL;
    }
    if (encoding != DAUDIO_PCM)
    {
        ERROR1("DAUDIO_Open: ERROR: cannot open the device with encoding=%d!\n", encoding);
        return NULL;
    }
    if (sampleSizeInBits > 8 &&
#ifdef _LITTLE_ENDIAN
        isBigEndian
#else
        !isBigEndian
#endif
        )
    {
            ERROR1("DAUDIO_Open: ERROR: wrong endianness: isBigEndian==%d!\n", isBigEndian);
            return NULL;
    }
    if (sampleSizeInBits == 8 && isSigned)
    {
        ERROR0("DAUDIO_Open: ERROR: wrong signed'ness: with 8 bits, data must be unsigned!\n");
        return NULL;
    }
    if (!DS_StartBufferHelper::isInitialized())		//初始化线程句柄
    {
        ERROR0("DAUDIO_Open: ERROR: StartBufferHelper initialization was failed!\n");
        return NULL;
    }

    info = (DS_Info*) malloc(sizeof(DS_Info));
    if (!info)
    {
        ERROR0("DAUDIO_Open: ERROR: Out of memory\n");
        return NULL;
    }
    memset(info, 0, sizeof(DS_Info));

    info->deviceID = deviceID;
    info->isSource = isSource;
    info->bitsPerSample = sampleSizeInBits;
    info->frameSize = frameSize;
    info->framePos = 0;
    info->started = false;
    info->underrun = false;

    if (!DS_addDeviceRef(deviceID))	//该函数主要是用来创建DirectSound对象接口以及设置协作级别
    {
        DS_removeDeviceRef(deviceID);
        free(info);
        return NULL;
    }

    //该函数主要是设置缓冲区格式以及创建辅助缓冲区
    buffer = DS_createSoundBuffer(info, sampleRate, sampleSizeInBits, channels, bufferSizeInBytes);
    if (!buffer)
    {
        DS_removeDeviceRef(deviceID);
        free(info);
        return NULL;
    }

    if (info->isSource)
    {
        info->playBuffer = (LPDIRECTSOUNDBUFFER8) buffer;
    }
    else
    {
        info->captureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER8) buffer;
    }
    DS_clearBuffer(info, false /* entire buffer */);

    /* use writepos of device */
    if (info->isSource)
    {
        info->writePos = -1;
    }
    else
    {
        info->writePos = 0;
    }

    //TRACE0("< DAUDIO_Open: Opened device successfully.\n");
    return (void*) info;
}