Ejemplo n.º 1
0
//this function is called by PortAudio when new audio data arrived
int snd_callback(const void *input,
                 void *output,
                 unsigned long frameCount,
                 const PaStreamCallbackTimeInfo* timeInfo,
                 PaStreamCallbackFlags statusFlags,
                 void *userData)
{
    memcpy(pa_pcm_buf, input, framepacket_size*sizeof(short));
	
    //tell vu_update() that there is new audio data
    pa_new_frames = 1;

	if(streaming)
	{
		rb_write(&stream_rb, (char*)input, framepacket_size*sizeof(short));
		pthread_cond_signal(&stream_cond);
	}
	if(recording)
	{
		rb_write(&rec_rb, (char*)input, framepacket_size*sizeof(short));
		pthread_cond_signal(&rec_cond);
	}

    return 0;
}
Ejemplo n.º 2
0
int main (void)
{
  int i=0;
  struct buf_info test_buffer;
  unsigned char real_buf[20];
  rb_init (&test_buffer, (unsigned char*)&real_buf, 20);

  rb_write (&test_buffer, 'a');
  rb_write (&test_buffer, 'a');

  printf ("got %hhc %hhc\n", rb_read(&test_buffer), rb_read(&test_buffer));

  for (i = 0; i<52; i++)
  {
    rb_write (&test_buffer, (char)(i+33));
  }

  int chr = rb_read (&test_buffer);
  char str [21];
  int npos = 0;
  while (chr != EEMPTY)
  {
    str[npos++]=(char)chr;
    chr = rb_read (&test_buffer);
  }
  str[npos]=0;

  printf ("npos=%d, got %s\n", npos, str);

  return 0;
}
Ejemplo n.º 3
0
END_TEST


START_TEST (test_to_fd_from_rb)
{
    int fds[2];
    ck_assert(pipe(fds) == 0);

    rb_append(rb, sample16, 16);
    ck_assert(rb_is_full(rb));

    ssize_t result = rb_write(rb, fds[1], 10);
    ck_assert_int_eq(result, 10);

    ck_assert_int_eq(rb_used(rb), 6);
    ck_assert_int_eq(rb_space(rb), 10);

    char outbuf[32];
    ck_assert_int_eq(read(fds[0], outbuf, sizeof(outbuf)), 10);
    ck_assert(memcmp(outbuf, "0123456789", 10) == 0);

    result = rb_write(rb, fds[1], 10);
    ck_assert_int_eq(result, 6);
    ck_assert(rb_is_empty(rb));

    ck_assert_int_eq(read(fds[0], outbuf, sizeof(outbuf)), 6);
    ck_assert(memcmp(outbuf, "ABCDEF", 6) == 0);
}
Ejemplo n.º 4
0
//=============================================================================
static void *writer_thread_func(void *arg)
{
	if(rb_==NULL)
	{
		fprintf(stderr,"ringbuffer was NULL.\n");
		exit(1);
	}
	debug(rb_,WRITER_THREAD);
	//srand(1234);

	//example data buffer
	const char *buf="ringbuffers are cool. ";
	const int content_length=22;

	//in one rb_write operation (reset each cylce)
	int write=0;
	//relative to full content length (reset after fully written)
	int write_total=0;

	//repeat to write contents of buf to ringbuffer
	//handle case when rb_write returns less bytes than requested
	//a reading process should get a stream of identical sentences
	while(1==1)
	{
		if(write_total>=content_length)
		{
			write_total=0;
//			fprintf(stdout,"\n");
//			fflush(stdout);
		}

		write=rb_write(
			rb_				//write to this ringbuffer
			,buf+write_total		//from source buffer, starting at offset 'write_total'
			,content_length-write_total	//request to write all remaining bytes
		);

		//buffer to indicate which part of source buffer could be written
		char buf_written[write+1];
		buf_written[write]='\0';

		//copy from source buffer
		memcpy(buf_written,buf+write_total,write);

		write_total+=write;

		fprintf(stderr,"write %d write_total %d '%s'\n"
			,write		//bytes written in last rb_write
			,write_total	//bytes written relative to source buffer pos 0
			,buf_written	//contents that were written
		);
//		fprintf(stdout,"%s",buf_written);
//		fflush(stdout);
		debug(rb_,WRITER_THREAD);

		//int r=rand()/100000;
		//fprintf(stderr,"rand %d\n",r);
		//usleep(r); //random sleep
	}
}
Ejemplo n.º 5
0
Archivo: main.c Proyecto: lythm/orb3d
int main(int argc, char* argv[])
{
	unsigned int left = 0;
	unsigned int size = 0;
	unsigned int i = 0;
	struct ring_buffer rb;
	char buffer[100];

	for(i = 0; i < 100; ++i)
	{
		buffer[i] = i;
	}
	
	rb_alloc(&rb, 100);

	for(i = 0; i < 100; ++i)
	{
		rb_write(&rb, buffer, 33);
		rb_read(&rb, buffer, 32);
	}
	

	printf("%d,%d  %d,%d\n", rb_length(&rb), rb_left(&rb), rb_is_full(&rb), rb_is_empty(&rb));

	rb_free(&rb);

	
	return 0;
}
Ejemplo n.º 6
0
size_t     rb_write(RingBuffer *rb, const void *data, size_t count)
{
    //assert(rb != NULL);
    //assert(data != NULL);
    
    if (count >= rb_can_write(rb)) 
			return -1;
    
    if (rb->rb_head <= rb->rb_tail)
    {
        int tail_avail_sz = rb_capacity(rb) - (rb->rb_tail - rb->rb_buff);
        if (count <= tail_avail_sz)
        {
            memcpy(rb->rb_tail, data, count);
            rb->rb_tail += count;
            if (rb->rb_tail == rb->rb_buff+rb_capacity(rb))
                rb->rb_tail = rb->rb_buff;
            return count;
        }
        else
        {
            memcpy(rb->rb_tail, data, tail_avail_sz);
            rb->rb_tail = rb->rb_buff;
            
            return tail_avail_sz + rb_write(rb, (char*)data+tail_avail_sz, count-tail_avail_sz);
        }
    }
    else
    {
        memcpy(rb->rb_tail, data, count);
        rb->rb_tail += count;
        return count;
    }
}
Ejemplo n.º 7
0
static ssize_t
mydev_write(struct file *filp, const char __user *buf, size_t nbuf, loff_t *offs)
{
	unsigned minor = MINOR(filp->f_dentry->d_inode->i_rdev);
	int rc;

	/* obtain lock before accessing rwbuf */
	if (mutex_lock_interruptible(&mydev_mutex))
		return -EINTR;

	if ((rc = chk_rwbuf(nbuf))) {
		return rc;
	}
	
	/* copy the data from the user-supplied buffer to the tmp buffer, since device cannot
	   directly read from user-space memory */
	copy_from_user(rwbuf, buf, nbuf);

	/* write data out to device */
	nbuf = rb_write(mydev_ring[minor], rwbuf, nbuf);

	/* done with rwbuf, unlock mutex */
	mutex_unlock(&mydev_mutex);

	/* adjust file offset */
	*offs += nbuf;

	/* return number of bytes written */
	return nbuf;
}
Ejemplo n.º 8
0
/*! @brief Helper function to delegate fault message to an external endpoint.
    
    Writes the given message to the delegator's notification ring buffer,  and then sends an async
    notification along the EP the delegator has set up previously.  This helper function is used for
    every kind of notification.

    @param f The fault message info structure.
    @param delegationPCB The PCB structure of the delegator recieving the notification.
    @param delegationEP The async endpoint of delegator to notify.
    @param vmFaultNotification The VM fault noficfiation message contents.
    @param saveReply Whether to save the falunt client's reply EP.
*/
static void
fault_delegate_notification(struct procserv_vmfault_msg *f, struct proc_pcb *delegationPCB,
        cspacepath_t delegationEP, struct proc_notification vmFaultNotification, bool saveReply)
{
    assert(f && f->pcb);
    assert(delegationPCB && delegationPCB->magic == REFOS_PCB_MAGIC);

    if (!delegationPCB->notificationBuffer) {
        printf("PID notif buffer NULL! %d\n", delegationPCB->pid);
        output_segmentation_fault("Delegator dataspace server has no notification buffer.", f);
        return;
    }

    /* Save the caller reply cap to reply to later. */
    if (saveReply) {
        int error = proc_save_caller(f->pcb);
        if (error) {
            output_segmentation_fault("Failed to save caller reply cap.", f);
            return;
        }
    }

    /* Append notification to pager's notification buffer. */
    int error = rb_write(delegationPCB->notificationBuffer, (char*)(&vmFaultNotification),
            sizeof(vmFaultNotification));
    if (error) {
        output_segmentation_fault("Failed to write VM fault notification to buffer.", f);
        return;
    }

    /* Notify the pager of this fault. */
    dispatcher_notify(delegationEP.capPtr);
}
Ejemplo n.º 9
0
void	connect_nbr(t_env *e, t_players *player)
{
  char	buff[WR_SIZE];
  int	free_slots;

  free_slots = get_free_slots_byteam(e, player->id_team);
  sprintf(buff, "%d\n", free_slots);
	  rb_write(player->wr_rb, buff, strlen(buff));
  e->network->fdt[player->fd_associate]->type |= T_WRITE;
}
Ejemplo n.º 10
0
/******************************************************
 *    function    : serialEvent
 *    Description : arduino serial uart receive  interrupt 
 *                  function
 *   
 *    return      : none.
 *    Add by Alex.lin    --2014-12-24
******************************************************/
void serialEvent(void)
{
	uint8_t value = 0;
	value = (unsigned char)Serial1.read();
	if(rb_can_write(&u_ring_buff) > 0)
	{
		rb_write(&u_ring_buff, &value, 1);
	}

	Serial.println(value, HEX);//不加这句容易出BUG
}
Ejemplo n.º 11
0
static ssize_t
mydev_write(struct file *filp, const char __user *buf, size_t nbuf, loff_t *offs)
{
	unsigned minor = MINOR(filp->f_dentry->d_inode->i_rdev);
	int rc;

	/* obtain lock before accessing rwbuf */
	if (mutex_lock_interruptible(&mydev_mutex))
		return -EINTR;

	if ((rc = chk_rwbuf(nbuf))) {
		return rc;
	}

	/* check if there is room in the ring */
	while (!rb_free(mydev_ring[minor])) {
		/* no room in the buffer, we're either going to return (non-blocking case) or block.
                   in either case we need to release the lock first to avoid deadlock */

		mutex_unlock(&mydev_mutex);

		/* handle non-blocking writes */
		if (filp->f_flags & O_NONBLOCK)
			return -EAGAIN;

		/* block until notified (by read) that there is room */
		if (wait_event_interruptible(mydev_wqueue, rb_free(mydev_ring[minor]) > 0))
			return -ERESTARTSYS;

		/* restore lock before proceeding */
		if (mutex_lock_interruptible(&mydev_mutex))
			return -ERESTARTSYS;
	}
	
	/* copy the data from the user-supplied buffer to the tmp buffer, since device cannot
	   directly read from user-space memory */
	copy_from_user(rwbuf, buf, nbuf);

	/* write data out to device */
	nbuf = rb_write(mydev_ring[minor], rwbuf, nbuf);

	/* done with rwbuf, unlock mutex */
	mutex_unlock(&mydev_mutex);

	/* adjust file offset */
	*offs += nbuf;

	wake_up_interruptible(&mydev_rqueue);

	/* return number of bytes written */
	return nbuf;
}
Ejemplo n.º 12
0
void
cdda_send_event(int event_type, char * drive) {

	cdda_notify_t notify;

	/* If there is no space for the message, it is dropped.
	 * This may happen if GUI gets blocked (unable to run cdda_timeout_callback()
	 * for several seconds), however it is not anticipated to happen very often.
	 * In such case these events are not very much of use, anyway.
	 */
	if (rb_write_space(cdda_notify_rb) >= sizeof(cdda_notify_t)) {
		notify.event_type = event_type;
		notify.device_path = strdup(drive);
		rb_write(cdda_notify_rb, (char *)&notify, sizeof(cdda_notify_t));
	}
}
Ejemplo n.º 13
0
/* return 1 if reached end of stream, 0 else */
int
decode_vorbis(decoder_t * dec) {

	vorbis_pdata_t * pd = (vorbis_pdata_t *)dec->pdata;
	file_decoder_t * fdec = dec->fdec;

	int i;
	long bytes_read;
        float fbuffer[VORBIS_BUFSIZE/2];
        char buffer[VORBIS_BUFSIZE];
	int current_section;


	bytes_read = ov_read(&(pd->vf), buffer, VORBIS_BUFSIZE, bigendianp(), 2, 1, &current_section);

	switch (bytes_read) {
	case 0:
		/* end of file */
                return 1;
		break;
	case OV_HOLE:
		if (fdec->is_stream) {
			vorbis_send_metadata(fdec, pd);
			vorbis_decoder_send_metadata(dec);
			break;
		} else {
			printf("dec_vorbis.c/decode_vorbis(): ov_read() returned OV_HOLE\n");
			printf("This indicates an interruption in the Vorbis data (one of:\n");
			printf("garbage between Ogg pages, loss of sync, or corrupt page).\n");
		}
		break;
	case OV_EBADLINK:
		printf("dec_vorbis.c/decode_vorbis(): ov_read() returned OV_EBADLINK\n");
		printf("An invalid stream section was supplied to libvorbisfile.\n");
		break;
	default:
                for (i = 0; i < bytes_read/2; i++) {
                        fbuffer[i] = *((short *)(buffer + 2*i)) * fdec->voladj_lin / 32768.f;
		}
                rb_write(pd->rb, (char *)fbuffer,
                                      bytes_read/2 * sample_size);
		break;
	}
	return 0;
}
Ejemplo n.º 14
0
size_t rbs_write(const void *ptr, size_t size, size_t nmemb, rbstream_p rbsp)
{
	medvdbg("[%s] ptr %p nmemb %lu\n", __FUNCTION__, ptr, nmemb);
	RETURN_VAL_IF_FAIL(ptr != NULL, SIZE_ZERO);
	RETURN_VAL_IF_FAIL(rbsp != NULL, SIZE_ZERO);

	// only size:1 supported
	assert(size == 1);

	size_t len = size * nmemb;
	size_t wlen;

	wlen = rb_write(rbsp->rbp, ptr, len);
	// increase wr_size
	rbsp->wr_size += wlen;

	medvdbg("[%s] done, wlen %lu\n", __FUNCTION__, wlen);
	return wlen;
}
Ejemplo n.º 15
0
static void	joined(t_env *e, t_players *player, int id_team,
		       char *team, int slots)
{
  char		buff[WR_SIZE];

  player->active = 1;
  player->id_team = id_team;
  sprintf(buff, "%d\n%d %d\n", slots - 1,
	  e->params->width, e->params->height);
  rb_write(player->wr_rb, buff, strlen(buff));
  e->world->map[player->posx][player->posy].nb_player++;
  e->network->fdt[player->fd_associate]->type |= T_WRITE;
  add_stack_healthcare(e, player, HEALTHCARE, HEALTHCARE_T);
  printf("%sPlayer #%d successfully joined team '%s'.%s\n",
	 GREEN, player->fd_associate, team, WHITE);
  sprintf(buff + strlen(buff), "pnw %d %d %d %d %d %s\n", player->fd_associate,
	  player->posx, player->posy, player->direction,
	  player->level, get_team_byid(e, player->id_team));
  send_graphic(e, NULL, buff);
}
Ejemplo n.º 16
0
int vc_queue_message(Mono_Time *mono_time, void *vcp, struct RTPMessage *msg)
{
    /* This function is called with complete messages
     * they have already been assembled.
     * this function gets called from handle_rtp_packet() and handle_rtp_packet_v3()
     */
    if (!vcp || !msg) {
        return -1;
    }

    VCSession *vc = (VCSession *)vcp;
    const struct RTPHeader *const header = &msg->header;

    if (msg->header.pt == (RTP_TYPE_VIDEO + 2) % 128) {
        LOGGER_WARNING(vc->log, "Got dummy!");
        free(msg);
        return 0;
    }

    if (msg->header.pt != RTP_TYPE_VIDEO % 128) {
        LOGGER_WARNING(vc->log, "Invalid payload type! pt=%d", (int)msg->header.pt);
        free(msg);
        return -1;
    }

    pthread_mutex_lock(vc->queue_mutex);

    if ((header->flags & RTP_LARGE_FRAME) && header->pt == RTP_TYPE_VIDEO % 128) {
        LOGGER_DEBUG(vc->log, "rb_write msg->len=%d b0=%d b1=%d", (int)msg->len, (int)msg->data[0], (int)msg->data[1]);
    }

    free(rb_write(vc->vbuf_raw, msg));

    /* Calculate time it took for peer to send us this frame */
    uint32_t t_lcfd = current_time_monotonic(mono_time) - vc->linfts;
    vc->lcfd = t_lcfd > 100 ? vc->lcfd : t_lcfd;
    vc->linfts = current_time_monotonic(mono_time);
    pthread_mutex_unlock(vc->queue_mutex);
    return 0;
}
Ejemplo n.º 17
0
//=============================================================================
int main()
{
	rb_t *rb=rb_new(FLOAT_COUNT*sizeof(float));
	if(rb==NULL) {return 1;}
	rb_debug(rb);

	float floats[FLOAT_COUNT]={0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8};
	int wrote=rb_write(rb,(char*)floats,FLOAT_COUNT*sizeof(float));
	fprintf(stderr,"wrote %d bytes (%zu floats)\n",wrote,wrote/sizeof(float));

	rb_debug(rb);
	rb_print_regions(rb);

	float f1;
	int read=rb_read_float(rb,&f1);
	fprintf(stderr,"read %d bytes (%zu float) %f\n",read,read/sizeof(float),f1);

	int peeked=rb_peek_float(rb,&f1);
	fprintf(stderr,"peeked %d bytes (%zu float) %f\n",peeked,peeked/sizeof(float),f1);

	float f2=0.99;
	wrote=rb_write_float(rb,&f2);
	fprintf(stderr,"wrote %d bytes (%zu float) %f\n",wrote,wrote/sizeof(float),f2);

	int skipped=rb_skip_float(rb);
	fprintf(stderr,"skipped %d bytes (%zu float)\n",skipped,skipped/sizeof(float));

	int peek_at=rb_can_read(rb)-sizeof(float);
	peeked=rb_peek_float_at(rb,&f1,peek_at);
	fprintf(stderr,"peeked %d bytes (%zu float) at %d %f\n",peeked,peeked/sizeof(float),peek_at,f1);

	rb_debug(rb);
	rb_print_regions(rb);

	rb_free(rb);
	return 0;
}
Ejemplo n.º 18
0
int
rb_send_fd_buf(rb_fde_t *xF, rb_fde_t **F, int count, void *data, size_t datasize, pid_t pid)
{
	size_t bufsize =
		sizeof(uint32_t) + sizeof(uint8_t) + (sizeof(WSAPROTOCOL_INFO) * (size_t)count) +
		sizeof(size_t) + datasize;
	int i;
	uint32_t magic = MAGIC_CONTROL;
	void *ptr;
	if(count > 4)
	{
		errno = EINVAL;
		return -1;
	}
	if(bufsize > sizeof(fd_buf))
	{
		errno = EINVAL;
		return -1;
	}
	memset(fd_buf, 0, sizeof(fd_buf));

	ptr = fd_buf;
	memcpy(ptr, &magic, sizeof(magic));
	ptr = (void *)((uintptr_t)ptr + (uintptr_t)sizeof(magic));
	*((uint8_t *)ptr) = count;
	ptr = (void *)((uintptr_t)ptr + (uintptr_t)sizeof(uint8_t));

	for(i = 0; i < count; i++)
	{
		make_wsaprotocol_info(pid, F[i], (WSAPROTOCOL_INFO *) ptr);
		ptr = (void *)((uintptr_t)ptr + (uintptr_t)sizeof(WSAPROTOCOL_INFO));
	}
	memcpy(ptr, &datasize, sizeof(size_t));
	ptr = (void *)((uintptr_t)ptr + (uintptr_t)sizeof(size_t));
	memcpy(ptr, data, datasize);
	return rb_write(xF, fd_buf, bufsize);
}
Ejemplo n.º 19
0
static int
read_ogg_packet(OGGZ * oggz, oggz_packet * zp, long serialno, void * user_data) {

	ogg_packet * op = &zp->op;
	decoder_t * dec = (decoder_t *)user_data;
	speex_pdata_t * pd = (speex_pdata_t *)dec->pdata;

	if (pd->exploring && (pd->packetno == 0)) {
		/* Speex header */

		int i;
                int ptr = 0;
                char speex_string[9];
		int enh = 1;

                SpeexHeader * header;


                for (i = 0; i < 8; i++) {
                        speex_string[i] = op->packet[ptr++];
                }
                speex_string[i] = '\0';

                if (strcmp(speex_string, "Speex   ") != 0) {
			printf("read_ogg_packet(): Not a Speex stream\n");
                        pd->error = 1;
			return 0;
                }

                speex_bits_init(&(pd->bits));

                header = speex_packet_to_header((char *)op->packet, op->bytes);
                if (!header) {
                        printf("Cannot read Speex header\n");
			pd->error = 1;
                        return 0;
                }

                pd->mode = speex_mode_list[header->mode];

                if (pd->mode->bitstream_version > header->mode_bitstream_version) {
                        fprintf(stderr, "Unknown bitstream version! The file was encoded with an older version of Speex.\n"
                                "You need to downgrade Speex in order to play it.\n");
			pd->error = 1;
                        return 0;
                }

                if (pd->mode->bitstream_version < header->mode_bitstream_version) {
                        fprintf(stderr, "Unknown bitstream version! The file was encoded with a newer version of Speex.\n"
                                "You need to upgrade Speex in order to play it.\n");
			pd->error = 1;
                        return 0;
                }

		pd->sample_rate = header->rate;
		pd->channels = header->nb_channels;
		pd->vbr = header->vbr;

                if (header->frames_per_packet != 0)
                        pd->nframes = header->frames_per_packet;

                pd->decoder = speex_decoder_init(pd->mode);
                speex_decoder_ctl(pd->decoder, SPEEX_GET_FRAME_SIZE, &(pd->frame_size));
                speex_decoder_ctl(pd->decoder, SPEEX_SET_ENH, &enh);

	} else if (pd->packetno >= 2) {

		int j;
		float output_frame[SPEEX_BUFSIZE];

		pd->granulepos = op->granulepos;

		if (!pd->exploring) {
			speex_bits_read_from(&(pd->bits), (char *)op->packet, op->bytes);
			
			for (j = 0; j < pd->nframes; j++) {
				
				int k;
				
				speex_decode(pd->decoder, &(pd->bits), output_frame);
				
				for (k = 0; k < pd->frame_size * pd->channels; k++) {
					output_frame[k] /= 32768.0f;
					if (output_frame[k] > 1.0f) {
						output_frame[k] = 1.0f;
					} else if (output_frame[k] < -1.0f) {
						output_frame[k] = -1.0f;
					}
				}
				
				rb_write(pd->rb, (char *)output_frame,
						      pd->channels * pd->frame_size * sample_size);
			}
		}
	}
	
	++pd->packetno;
	return 0;
}
Ejemplo n.º 20
0
//this function is called by PortAudio when new audio data arrived
int snd_callback(const void *input,
                 void *output,
                 unsigned long frameCount,
                 const PaStreamCallbackTimeInfo* timeInfo,
                 PaStreamCallbackFlags statusFlags,
                 void *userData)
{
    int samplerate_out;
    bool convert_stream = false;
    bool convert_record = false;


    memcpy(pa_pcm_buf, input, frameCount*cfg.audio.channel*sizeof(short));
    samplerate_out = cfg.audio.samplerate;

    if(dsp->hasToProcessSamples()) {
        dsp->processSamples(pa_pcm_buf);
    }
	
	if (streaming)
	{
        if ((!strcmp(cfg.audio.codec, "opus")) && (cfg.audio.samplerate != 48000))
        {
            convert_stream = true;
            samplerate_out = 48000;
        }

        if (convert_stream == true)
        {
            srconv_stream.end_of_input = 0;
            srconv_stream.src_ratio = (float)samplerate_out/cfg.audio.samplerate;
            srconv_stream.input_frames = frameCount;
            srconv_stream.output_frames = frameCount*cfg.audio.channel * (srconv_stream.src_ratio+1) * sizeof(float);

            src_short_to_float_array((short*)pa_pcm_buf, (float*) srconv_stream.data_in, (int) frameCount*cfg.audio.channel);

            //The actual resample process
            src_process(srconv_state_stream, &srconv_stream);

            src_float_to_short_array(srconv_stream.data_out, (short*)stream_buf, (int) srconv_stream.output_frames_gen*cfg.audio.channel);

            rb_write(&stream_rb, (char*)stream_buf, (int) srconv_stream.output_frames_gen*sizeof(short)*cfg.audio.channel);
        }
        else
            rb_write(&stream_rb, (char*)pa_pcm_buf, (int) frameCount*sizeof(short)*cfg.audio.channel);

		pthread_cond_signal(&stream_cond);
	}

	if(recording)
	{

        if ((!strcmp(cfg.rec.codec, "opus")) && (cfg.audio.samplerate != 48000))
        {
            convert_record = true;
            samplerate_out = 48000;
        }

        if (convert_record == true)
        {
            srconv_record.end_of_input = 0;
            srconv_record.src_ratio = (float)samplerate_out/cfg.audio.samplerate;
            srconv_record.input_frames = frameCount;
            srconv_record.output_frames = frameCount*cfg.audio.channel * (srconv_record.src_ratio+1) * sizeof(float);

            src_short_to_float_array((short*)pa_pcm_buf, (float*) srconv_record.data_in, (int) frameCount*cfg.audio.channel);

            //The actual resample process
            src_process(srconv_state_record, &srconv_record);

            src_float_to_short_array(srconv_record.data_out, (short*)record_buf, (int) srconv_record.output_frames_gen*cfg.audio.channel);

            rb_write(&rec_rb, (char*)record_buf, (int) srconv_record.output_frames_gen*sizeof(short)*cfg.audio.channel);

        }
        else
            rb_write(&rec_rb, (char*)pa_pcm_buf, (int) frameCount*sizeof(short)*cfg.audio.channel);

		pthread_cond_signal(&rec_cond);
	}
    
    //tell vu_update() that there is new audio data
    pa_new_frames = 1;

    return 0;
}
Ejemplo n.º 21
0
// /audio
//handler for audio messages
int audio_handler(const char *path, const char *types, lo_arg **argv, int argc,
	void *data, void *user_data)
{
	if(shutdown_in_progress==1)
	{
		return 0;
	}

	//init to 0, increment before use
	msg_received_counter++;

	gettimeofday(&tv, NULL);

	//first blob is at data_offset+1 (one-based)
	int data_offset=4;

	//ignore first n channels/blobs
	data_offset+=channel_offset;

	message_number_prev=message_number;

	//the messages are numbered sequentially. first msg is numberd 1
	message_number=argv[0]->h;

	if(message_number_prev<message_number-1)
	{
		fprintf(stderr,"\ngap in message sequence! possibly lost %" PRId64" message(s) on the way.\n"
			,message_number-message_number_prev-1);
		fflush(stderr);
	}

	//total args count minus metadata args and channel offset count = number of blobs
	input_port_count=argc-data_offset;

	//only process useful number of channels
	port_count=fmin(input_port_count,output_port_count);

	if(port_count < 1)
	{
		fprintf(stderr,"\n\nchannel offset %d >= available input channels %d! (nothing to receive). shutting down...\n"
			,channel_offset
			,(argc-data_offset+channel_offset));
		fflush(stderr);
		shutdown_in_progress=1;
		return 0;
	}

	//need to warn when offset + outchannels limited

	//check sample rate and period size if sender (re)started or values not yet initialized (=no /offer received)
	if(message_number_prev>message_number || message_number==1 || remote_sample_rate==0 || remote_period_size==0 )
	{
		lo_address loa;

		loa = lo_message_get_source(data);

		strcpy(sender_host,lo_address_get_hostname(loa));
		strcpy(sender_port,lo_address_get_port(loa));

		remote_sample_rate=argv[3]->i;

		remote_period_size=lo_blob_datasize((lo_blob)argv[0+data_offset])/bytes_per_sample;
		fprintf(stderr,"\nsender was (re)started. ");

		if(remote_period_size!=period_size)
		{
			fprintf(stderr,"sender period size: %d samples (%.3f x forward period size)\n\n",remote_period_size,(float)remote_period_size/period_size);
		}
		else
		{
			fprintf(stderr,"equal sender and receiver period size\n\n");
		}

	}//end if "no-offer init" was needed

	remote_xrun_counter=argv[1]->h;

	lo_timetag tt=argv[2]->t;

	double msg_time=tt.sec+(double)tt.frac/1000000;
	double msg_time_prev=tt_prev.sec+(double)tt_prev.frac/1000000;
	double time_now=tv.tv_sec+(double)tv.tv_usec/1000000;

	time_interval=msg_time-msg_time_prev;

	time_interval_sum+=time_interval;
	time_interval_avg=(float)time_interval_sum/msg_received_counter;

	tt_prev=tt;

	//reset avg calc, check and reset after use
	if(msg_received_counter>=avg_calc_interval)
	{
		msg_received_counter=0;
		time_interval_sum=0;
	}

	fflush(stderr);

	//
	process_enabled=1;

	int mc_period_bytes=period_size*bytes_per_sample*port_count;

	//check if a whole mc period can be written to the ringbuffer
	uint64_t can_write_count=rb_can_write(rb);
	if(can_write_count < mc_period_bytes)
	{
			buffer_overflow_counter++;
			/////////////////
			fprintf(stderr,"\nBUFFER OVERFLOW! this is bad -----%s\n","\033[0J");
			return 0;
	}

	//========================================
	//new: support different period sizes on sender / receiver (still need same SR)
	//this needs more tests and optimization
	if(period_size==remote_period_size)
	{
		int i;
		//don't read more channels than we have outputs
		for(i=0;i < port_count;i++)
		{
			//get blob (=one period of one channel)
			unsigned char *data = lo_blob_dataptr((lo_blob)argv[i+data_offset]);
			//fprintf(stderr,"size %d\n",lo_blob_datasize((lo_blob)argv[i+data_offset]));

			//write to ringbuffer
			//==========================================
			int cnt=rb_write(rb, (void *) data, 
				period_size*bytes_per_sample);
		}
	}
	else if(period_size>remote_period_size)
	{
		int i;
		//don't read more channels than we have outputs
		for(i=0;i < port_count;i++)
		{
			//get blob (=one period of one channel)
			unsigned char *data = lo_blob_dataptr((lo_blob)argv[i+data_offset]);
			//fprintf(stderr,"size %d\n",lo_blob_datasize((lo_blob)argv[i+data_offset]));

			//write to temporary ringbuffer until there is enough data
			//==========================================
			int cnt=rb_write(rb_helper, (void *) data, 
				remote_period_size*bytes_per_sample);
		}

		//if enough data collected for one larger multichannel period

		while(rb_can_read(rb_helper)	>=mc_period_bytes
		&& rb_can_write(rb)		>=mc_period_bytes)
		{
			//transfer from helper to main ringbuffer
			unsigned char* data;
			data=malloc(				mc_period_bytes);
			//store orig pointer
			unsigned char* orig_data=data;
			rb_read(rb_helper,data,	mc_period_bytes);

			for(i=0;i < port_count;i++)
			{
				int k;
				for(k=0;k<(period_size/remote_period_size);k++)
				{
					//reset pointer
					data=orig_data;
					//position in helper buffer for next sample for main buffer
					data+=	k*remote_period_size*bytes_per_sample*port_count
							+ i*remote_period_size*bytes_per_sample;

					//write one channel snipped (remote_period_size) to main buffer
					int w=rb_write(rb,(void *)data,remote_period_size*bytes_per_sample);
				}
			}
			data=orig_data;
			free(data);
		}
	}
	else if(period_size<remote_period_size)
	{
		int k;
		for(k=0;k<(remote_period_size/period_size);k++)
		{

			int i;
			//don't read more channels than we have outputs
			for(i=0;i < port_count;i++)
			{
				//get blob (=one period of one channel)
				unsigned char *data = lo_blob_dataptr((lo_blob)argv[i+data_offset]);
				//fprintf(stderr,"size %d\n",lo_blob_datasize((lo_blob)argv[i+data_offset]));

				//write to ringbuffer
				//==========================================
				data+=k*period_size*bytes_per_sample;

				int cnt=rb_write(rb, (void *) data, 
					period_size*bytes_per_sample);
			}
		}
	}

	return 0;
}//end audio_handler
Ejemplo n.º 22
0
static void proc_rx_byte(struct tcp_pcb * pcb, struct telnetio_dev *teldev, char ch)
{
#if (!RT_NEED_FINSH_PROC_LOGIN)
	int num, i;
	unsigned char ch1;
#endif
	TELNETD_DEBUG(("line:%u, iac_s:%d, state:%d, ch:%c(0x%x)\r\n", __LINE__,
				   teldev->iac_state, teldev->state, ch, ch));
	if (0 == teldev->iac_state) {
		if (TELNET_IAC == ch) {
			teldev->iac_state = TELS_IAC;
			return;
		}

		if ('\n' != ch) {
			rb_write(&teldev->rx_rb_buf, &ch, 1);
			if ('\r' != ch)
				return;
		} else {
			return;
		}

		switch (teldev->state) {
		case TELS_LOGIN_NAME:
#if (!RT_NEED_FINSH_PROC_LOGIN)
			do {
				if ((0==rb_first_read_byte_pry(&teldev->rx_rb_buf, &ch1))
					&& '\r'==ch1)
					rb_first_read_byte_drop(&teldev->rx_rb_buf);
				else
					break;
			} while(1);

			num = rb_get_used_bytes_num(&teldev->rx_rb_buf) - 1;
			i = MIN(num, USR_NAME_LEN_MAX);
			rb_read(&teldev->rx_rb_buf, teldev->usrpw.usr, i);
			teldev->usrpw.usr[i] = '\0';

			rb_cleanup(&teldev->rx_rb_buf);

			TELNETD_DEBUG(("line:%u, input:%s\r\n", __LINE__, teldev->usrpw.usr));
			tcp_write(pcb, PASSWORD, strlen(PASSWORD), TCP_WRITE_FLAG_COPY);
			//tcp_output(pcb);
#else
			rt_device_read(&teldev->dev, 0, NULL, 0);
#endif
			rt_device_read(&teldev->dev, 0, NULL, 0);
			teldev->state = TELS_LOGIN_PW;

			write_iac_cmd2tx_buf(teldev, TELNET_WONT, TELNET_SUPPRESS_GO_AHEAD);
			write_iac_cmd2tx_buf(teldev, TELNET_WILL, TELNET_ECHO);
			break;

		case TELS_LOGIN_PW:
#if (!RT_NEED_FINSH_PROC_LOGIN)
			do {
				if ((0==rb_first_read_byte_pry(&teldev->rx_rb_buf, &ch1))
					&& '\r'==ch1)
					rb_first_read_byte_drop(&teldev->rx_rb_buf);
				else
					break;
			} while(1);

			num = rb_get_used_bytes_num(&teldev->rx_rb_buf) - 1;
			i = MIN(num, PW_LEN_MAX);
			rb_read(&teldev->rx_rb_buf, teldev->usrpw.pw, i);
			teldev->usrpw.pw[i] = '\0';

			rb_cleanup(&teldev->rx_rb_buf);

			TELNETD_DEBUG(("line:%u, usr:%s, pw:%s\r\n", __LINE__, teldev->usrpw.usr,
						   teldev->usrpw.pw));
			if (is_usr_pw_matching(teldev->usrpw.usr, teldev->usrpw.pw)) {
				teldev->state = TELS_NORMAL;
				teldev->iac_state = 0;

				rb_write(&teldev->rx_rb_buf, "\r", 1);
				rt_device_read(&teldev->dev, 0, NULL, 0);
			} else {
				tcp_write(pcb, LOGIN_NAME, strlen(LOGIN_NAME), TCP_WRITE_FLAG_COPY);
				teldev->state = TELS_LOGIN_NAME;
			}
#else
			rt_device_read(&teldev->dev, 0, NULL, 0);
#endif
			write_iac_cmd2tx_buf(teldev, TELNET_WONT, TELNET_SUPPRESS_GO_AHEAD);
			write_iac_cmd2tx_buf(teldev, TELNET_WONT, TELNET_ECHO);
			break;

		case TELS_NORMAL :
			rt_device_read(&teldev->dev, 0, NULL, 0);
			break;

		case TELS_CLOSE :
		case TELS_LOGOUT:
		default:
			break;
		}
	} else {
		switch (teldev->iac_state) {
		case TELS_IAC :
			switch (ch) {
			case TELNET_WILL :
				teldev->iac_state = TELS_WILL;
				break;

			case TELNET_WONT :
				teldev->iac_state = TELS_WONT;
				break;

			case TELNET_DO :
				teldev->iac_state = TELS_DO;
				break;

			case TELNET_DONT :
				teldev->iac_state = TELS_DONT;
				break;

			case TELNET_IAC:
			default :
				teldev->iac_state = 0;//TELS_NORMAL;
				break;
			}
			break;

		case TELS_WILL : /* Reply with a DONT */
			write_iac_cmd2tx_buf (teldev, TELNET_DONT, ch);
			teldev->iac_state = 0;
			break;

		case TELS_WONT : /* Reply with a DONT */
			write_iac_cmd2tx_buf (teldev, TELNET_DONT, ch);
			teldev->iac_state = 0;
			break;

		case TELS_DO : /* Reply with a WONT */
			if ((TELS_LOGIN_PW == teldev->state) && TELNET_ECHO==ch)
				write_iac_cmd2tx_buf (teldev, TELNET_WILL, ch);
			else
				write_iac_cmd2tx_buf (teldev, TELNET_WONT, ch);
			teldev->iac_state = 0;
			break;

		case TELS_DONT : /* Reply with a WONT */
			write_iac_cmd2tx_buf (teldev, TELNET_WONT, ch);
			teldev->iac_state = 0;
			break;
		default:
			teldev->iac_state = 0;
			break;
		}
	}
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
	pid_t child_pid;
	int child_exit_status;
	struct termios tty_attr;
	struct winsize window_size;
	int pty_master;

	/* for select */
	fd_set readfds;
	fd_set writefds;

	unsigned err_n_rpty = 0;
	unsigned err_n_wpty = 0;
	unsigned err_n_stdin = 0;
	unsigned err_n_stdout = 0;

	int done = 0;

	/* the ring buffers */
	char inbuf_mem[BUFSIZE];
	char outbuf_mem[BUFSIZE];
	struct ring_buffer inbuf;
	struct ring_buffer outbuf;
	rb_init(&inbuf, inbuf_mem, sizeof(inbuf_mem));
	rb_init(&outbuf, outbuf_mem, sizeof(outbuf_mem));

	if (argc == 1) {
		printf("usage: %s PROGRAM [ARGS]...\n", argv[0]);
		exit(1);
	}

	/* We need I/O calls to fail with EINTR on SIGCHLD... */
	if (signal(SIGCHLD, sigchld_handler) == SIG_ERR) {
		perror("signal(SIGCHLD,...)");
		exit(EX_OSERR);
	}

	if (isatty(STDIN_FILENO)) {
		/* get terminal parameters associated with stdout */
		if (tcgetattr(STDOUT_FILENO, &tty_attr) < 0) {
			perror("tcgetattr(stdout,...)");
			exit(EX_OSERR);
		}

		/* get window size */
		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &window_size) < 0) {
			perror("ioctl(stdout,...)");
			exit(1);
		}

		child_pid = forkpty(&pty_master, NULL, &tty_attr, &window_size);
	} else { /* not interactive */
		child_pid = forkpty(&pty_master, NULL, NULL, NULL);
	}

	if (child_pid < 0) {
		perror("forkpty()");
		exit(EX_OSERR);
	}
	if (child_pid == 0) { /* in the child */
		struct termios s_tty_attr;
		if (tcgetattr(STDIN_FILENO, &s_tty_attr)) {
			perror("tcgetattr(stdin,...)");
			exit(EXIT_FAILURE);
		}
		/* Turn off echo */
		s_tty_attr.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
		/* Also turn of NL to CR?LF on output */
		s_tty_attr.c_oflag &= ~(ONLCR);
		if (tcsetattr(STDIN_FILENO, TCSANOW, &s_tty_attr)) {
			perror("tcsetattr(stdin,...)");
			exit(EXIT_FAILURE);
		}

		if (execvp(argv[1], argv + 1)) {
			perror("execvp()");
			exit(EXIT_FAILURE);
		}
	}

	/* Non blocking mode for all file descriptors. */
	setfd_nonblock(pty_master);
	setfd_nonblock(STDIN_FILENO);
	setfd_nonblock(STDOUT_FILENO);

	if (isatty(STDIN_FILENO)) {
		if (tty_semi_raw(STDIN_FILENO) < 0) {
			perror("tty_semi_raw(stdin)");
		}
		if (atexit(tty_atexit) < 0) {
			perror("atexit()");
		}
	}

	do {
		/* Accept events only on fds, that we can handle now. */
		int do_select = 0;
		FD_ZERO(&readfds);
		FD_ZERO(&writefds);

		if (rb_space(&outbuf) > 0 && err_n_rpty < MAXRETR) {
			FD_SET(pty_master, &readfds);
			do_select = 1;
		}

		if (!rb_isempty(&inbuf) && err_n_wpty < MAXRETR) {
			FD_SET(pty_master, &writefds);
			do_select = 1;
		}

		if (rb_space(&inbuf) > 0 && err_n_stdin < MAXRETR) {
			FD_SET(STDIN_FILENO, &readfds);
			do_select = 1;
		}

		if (!rb_isempty(&outbuf) && err_n_stdout < MAXRETR) {
			FD_SET(STDOUT_FILENO, &writefds);
			do_select = 1;
		}

		if (!do_select) {
#ifdef DEBUG
			fprintf(stderr, "No I/O job for us, calling waitpid()...\n");
#endif
			while (waitpid(child_pid, &child_exit_status, 0) < 0)
			{
				/* nothing */
			}
			break;
		}

		errno = 0;
		int select_rc = select(pty_master + 1, &readfds, &writefds, NULL, NULL);
		if (select_rc < 0 && errno != EINTR) {
			perror("select()");
			exit(EX_IOERR);
		}
#ifdef DEBUG
		fprintf(stderr, "select() returned %d\n", select_rc);
#endif

		if (FD_ISSET(STDOUT_FILENO, &writefds)) {
#ifdef DEBUG
			fprintf(stderr, "stdout can be written\n");
#endif
			ssize_t n = rb_write(&outbuf, STDOUT_FILENO);
			if (n <= 0 && n != EINTR && n != EAGAIN)
				err_n_stdout++;
#ifdef DEBUG
			if (n >= 0)
				fprintf(stderr, "%d bytes written into stdout\n", n);
			else
				perror("write(stdout,...)");
#endif
		}

		if (FD_ISSET(pty_master, &writefds)) {
#ifdef DEBUG
			fprintf(stderr, "pty_master can be written\n");
#endif
			ssize_t n = rb_write(&inbuf, pty_master);
			if (n <= 0 && n != EINTR && n != EAGAIN)
				err_n_wpty++;
#ifdef DEBUG
			if (n >= 0)
				fprintf(stderr, "%d bytes written into pty_master\n", n);
			else
				perror("write(pty_master,...)");
#endif
		}

		if (FD_ISSET(STDIN_FILENO, &readfds)) {
#ifdef DEBUG
			fprintf(stderr, "stdin can be read\n");
#endif
			ssize_t n = rb_read(&inbuf, STDIN_FILENO);
			if (n <= 0 && n != EINTR && n != EAGAIN)
				err_n_stdin++;
#ifdef DEBUG
			if (n >= 0)
				fprintf(stderr, "%d bytes read from stdin\n", n);
			else
				perror("read(stdin,...)");
#endif
		}

		if (FD_ISSET(pty_master, &readfds)) {
#ifdef DEBUG
			fprintf(stderr, "pty_master can be read\n");
#endif
			ssize_t n = rb_read(&outbuf, pty_master);
			if (n <= 0 && n != EINTR && n != EAGAIN)
				err_n_rpty++;
#ifdef DEBUG
			if (n >= 0)
				fprintf(stderr, "%d bytes read from pty_master\n", n);
			else
				perror("read(pty_master,...)");
#endif
		}

		if (!done && waitpid(child_pid, &child_exit_status, WNOHANG) > 0)
			done = 1;

	} while (!done
		|| !(rb_isempty(&inbuf) || err_n_wpty >= MAXRETR)
		|| !(rb_isempty(&outbuf) || err_n_stdout >= MAXRETR));

#ifdef DEBUG
	fprintf(stderr, "inbuf: %u bytes left, outbuf: %u bytes left\n", inbuf.count, outbuf.count);
	fprintf(stderr, "err_n_rpty=%u, err_n_wpty=%u, err_n_stdin=%u, err_n_stdout=%u\n",
		err_n_rpty, err_n_wpty, err_n_stdin, err_n_stdout);
#endif

	if (WIFEXITED(child_exit_status))
		exit(WEXITSTATUS(child_exit_status));
	else if (WIFSIGNALED(child_exit_status))
		exit(128 + WTERMSIG(child_exit_status));

	exit(EXIT_FAILURE);
}
Ejemplo n.º 24
0
static int
accept_precallback(rb_fde_t *F, struct sockaddr *addr, rb_socklen_t addrlen, void *data)
{
	struct Listener *listener = (struct Listener *)data;
	char buf[BUFSIZE];
	struct ConfItem *aconf;
	static time_t last_oper_notice = 0;
	int len;

	if(listener->ssl && (!ssl_ok || !get_ssld_count()))
	{
		rb_close(F);
		return 0;
	}

	if((maxconnections - 10) < rb_get_fd(F)) /* XXX this is kinda bogus */
	{
		++ServerStats.is_ref;
		/*
		 * slow down the whining to opers bit
		 */
		if((last_oper_notice + 20) <= rb_current_time())
		{
			sendto_realops_snomask(SNO_GENERAL, L_ALL,
					     "All connections in use. (%s)",
					     get_listener_name(listener));
			last_oper_notice = rb_current_time();
		}
			
		rb_write(F, "ERROR :All connections in use\r\n", 32);
		rb_close(F);
		/* Re-register a new IO request for the next accept .. */
		return 0;
	}

	aconf = find_dline(addr, addr->sa_family);
	if(aconf != NULL && (aconf->status & CONF_EXEMPTDLINE))
		return 1;
	
	/* Do an initial check we aren't connecting too fast or with too many
	 * from this IP... */
	if(aconf != NULL)
	{
		ServerStats.is_ref++;
			
		if(ConfigFileEntry.dline_with_reason)
		{
			len = rb_snprintf(buf, sizeof(buf), "ERROR :*** Banned: %s\r\n", get_user_ban_reason(aconf));
			if (len >= (int)(sizeof(buf)-1))
			{
				buf[sizeof(buf) - 3] = '\r';
				buf[sizeof(buf) - 2] = '\n';
				buf[sizeof(buf) - 1] = '\0';
			}
		}
		else
			strcpy(buf, "ERROR :You have been D-lined.\r\n");
	
		rb_write(F, buf, strlen(buf));
		rb_close(F);
		return 0;
	}

	if(check_reject(F, addr))
		return 0;
		
	if(throttle_add(addr))
	{
		rb_write(F, toofast, strlen(toofast));
		rb_close(F);
		return 0;
	}

	return 1;
}
Ejemplo n.º 25
0
__interrupt void USCI0RX_ISR(void)
{
	uint8_t data;
	data = UCA0RXBUF;
	rb_write(rx_uart_buffer, data);
}
Ejemplo n.º 26
0
//=============================================================================
int main(int argc, char *argv[])
{
	if(argc<2)
	{
		fprintf(stderr,"need number\n");
		exit(1);
	}

	int rb_size_request=atoi(argv[1]);

	fprintf(stderr,"\n==creating new ringbuffer of size %d\n",rb_size_request);
	
	rb_t *rb=rb_new(rb_size_request);
	if(rb==NULL)
	{
		fprintf(stderr,"ringbuffer with size 0?\n");
		exit(1);
	}
	rb_debug(rb);

	fprintf(stderr,"\n==write full + 1\n");
	int i;
	for(i=0;i<rb_size_request+1;i++)
	{
		char put[1]={i};
		int wrote=rb_write(rb,put,1);
		rb_debug(rb);
	}

	fprintf(stderr,"\n==peek full + 1\n");
	char pull[rb_size_request];
	int peeked=rb_peek(rb,pull,rb_size_request+1);
	rb_debug(rb);

	fprintf(stderr,"\n==read full + 1\n");
	for(i=0;i<rb_size_request+1;i++)
	{
		char pull[1];
		int read=rb_read(rb,pull,1);
		rb_debug(rb);
	}

	fprintf(stderr,"\n==write full\n");
	for(i=0;i<rb_size_request;i++)
	{
		char put[1]={i};
		int wrote=rb_write(rb,put,1);
		rb_debug(rb);
	}

	rb_print_regions(rb);

	fprintf(stderr,"\n==advance read pointer 1\n");
	rb_advance_read_index(rb,1);
	rb_debug(rb);

	fprintf(stderr,"\n==drop\n");
	rb_drop(rb);
	rb_debug(rb);
	rb_print_regions(rb);

	fprintf(stderr,"\n==write 1\n");
	char put[1]={'a'};
	int wrote=rb_write(rb,put,1);
	rb_debug(rb);
	rb_print_regions(rb);

	fprintf(stderr,"\n==read 1\n");
	char put2[1];
	int read=rb_read(rb,put2,1);
	rb_debug(rb);
	rb_print_regions(rb);

	fprintf(stderr,"\n==write 4\n");
	char put3[4]={'a','b','c','d'};
	wrote=rb_write(rb,put3,4);
	rb_debug(rb);

	rb_print_regions(rb);

	int advanced;
	int k;
	for(k=0;k<20;k++)
	{
		fprintf(stderr,"\n==advance write 3\n");
		advanced=rb_advance_write_index(rb,3);
		rb_debug(rb);
		rb_print_regions(rb);

		fprintf(stderr,"\n==advance read 2\n");
		advanced=rb_advance_read_index(rb,2);
		rb_debug(rb);
		rb_print_regions(rb);
	}
	for(k=0;k<20;k++)
	{
		fprintf(stderr,"\n==advance read 3\n");
		advanced=rb_advance_read_index(rb,2);
		rb_debug(rb);
		rb_print_regions(rb);

		fprintf(stderr,"\n==advance write 2\n");
		advanced=rb_advance_write_index(rb,3);
		rb_debug(rb);
		rb_print_regions(rb);
	}

	rb_region_t d;
	rb_get_next_write_region(rb,&d);

	fprintf(stderr,"\n==got next write buffer, can write %" PRId64 "\n",d.size);

	fprintf(stderr,"\n==drop\n");
	rb_drop(rb);
	rb_debug(rb);
	rb_print_regions(rb);

	rb_get_next_write_region(rb,&d);

	fprintf(stderr,"\n==got next write buffer, can write %" PRId64 "\n",d.size);
	d.buffer[0]='x';

	fprintf(stderr,"\n==advance write 4\n");
	advanced=rb_advance_write_index(rb,4);
	rb_debug(rb);
	rb_print_regions(rb);

	rb_get_next_read_region(rb,&d);

	fprintf(stderr,"\n==got next read buffer, can read %" PRId64 "\n",d.size);

	fprintf(stderr,"\n==advance read 4\n");
	rb_advance_read_index(rb,4);
	rb_debug(rb);
	rb_print_regions(rb);

	rb_get_next_read_region(rb,&d);

	fprintf(stderr,"\n==got next read buffer, can read %" PRId64 "\n",d.size);
	d.buffer[0]='x';

	fprintf(stderr,"\n==advance read 1\n");
	advanced=rb_advance_read_index(rb,1);
	rb_debug(rb);
	rb_print_regions(rb);
	
	fprintf(stderr,"\n==reset\n");
	rb_reset(rb);
	rb_debug(rb);
	fprintf(stderr,"\n==free\n");
	rb_free(rb);
	rb_debug(rb);

	return 0;
}//end main
Ejemplo n.º 27
0
static ssize_t ringbuf_write(struct file *file, const char *buf, size_t count, loff_t *offset) 
{
	return rb_write(file, buf, count, offset);
}