Example #1
0
// playing thread
static DWORD __stdcall dsound_play_thread(void *param) {
  // primary buffer caps
  DSBCAPS caps;
  caps.dwSize = sizeof(caps);
  primary_buffer->GetCaps(&caps);

  // primary buffer format
  WAVEFORMATEX format;
  primary_buffer->GetFormat(&format, sizeof(format), NULL);

  // timer resolustion
  timeBeginPeriod(1);

  // temp buffer for vsti process
  float output_buffer[2][4096];

  // data write posision
  int write_position = 0;

  // start playing primary buffer
  primary_buffer->Play(0, 0, DSBPLAY_LOOPING);

  while (dsound_thread) {
    DWORD play_pos, write_pos;

    // get current position
    primary_buffer->GetCurrentPosition(&play_pos, &write_pos);

    // size left in buffer to write.
    int data_buffer_size = (caps.dwBufferBytes + write_position - write_pos) % caps.dwBufferBytes;

    // write buffer size
    int write_buffer_size = buffer_size * format.nBlockAlign;

    // size left in buffer
    int write_size = write_buffer_size - data_buffer_size;

    // maybe data buffer is underflowed.
    if (write_size < 0) {
      write_size = (caps.dwBufferBytes + write_pos + write_buffer_size - write_position) % caps.dwBufferBytes;
    }

    // write data at least 32 samles
    if (write_size >= 32 * format.nBlockAlign) {
      //printf("%8d, %8d, %8d, %8d, %8d\n", timeGetTime(),  (caps.dwBufferBytes + write_position + write_size - write_pos) % caps.dwBufferBytes, write_pos, write_size, write_buffer_size);

      // samples
      uint samples = write_size / format.nBlockAlign;

      if (export_rendering()) {
        memset(output_buffer[0], 0, samples * sizeof(float));
        memset(output_buffer[1], 0, samples * sizeof(float));
      } else   {
        // update
        song_update(1000.0 * (double)samples / (double)format.nSamplesPerSec);

        // call vsti process func
        vsti_update_config((float)format.nSamplesPerSec, 4096);
        vsti_process(output_buffer[0], output_buffer[1], samples);
      }

      // lock primary buffer
      void  *ptr1, *ptr2;
      DWORD size1, size2;
      HRESULT hr = primary_buffer->Lock(write_position, write_size, &ptr1, &size1, &ptr2, &size2, 0);

      // device lost, restore and try again
      if (DSERR_BUFFERLOST == hr) {
        primary_buffer->Restore();
        hr = primary_buffer->Lock(write_position, write_size, &ptr1, &size1, &ptr2, &size2, 0);
      }

      // lock succeeded
      if (SUCCEEDED(hr)) {
        float *left = output_buffer[0];
        float *right = output_buffer[1];

        uint samples1 = size1 / format.nBlockAlign;
        uint samples2 = size2 / format.nBlockAlign;

        if (ptr1) write_buffer((short *)ptr1, left, right, samples1);
        if (ptr2) write_buffer((short *)ptr2, left + samples1, right + samples1, samples2);

        hr = primary_buffer->Unlock(ptr1, size1, ptr2, size2);

        write_position = (write_position + write_size) % caps.dwBufferBytes;
      }

    } else   {
      Sleep(1);
    }
  }

  // stop sound buffer
  primary_buffer->Stop();

  // timer resolustion
  timeEndPeriod(10);

  return 0;
}
Example #2
0
bool writePRT(const char* filename,const ParticlesData& p,const bool /*compressed*/,std::ostream* errorStream)
{
	/// Krakatoa pukes on 0 particle files for some reason so don't export at all....
    int numParts = p.numParticles();
    if (numParts)
    {
        std::unique_ptr<std::ostream> output(
        new std::ofstream(filename,std::ios::out|std::ios::binary));

        if (!*output) {
            if(errorStream) *errorStream <<"Partio Unable to open file "<<filename<<std::endl;
            return false;
        }

        FileHeadder header;
        memcpy(header.magic, magic, sizeof(magic));
        memcpy(header.signature, signature, sizeof(signature));
        header.headersize = 0x38;
        header.version = 1;
        header.numParticles = p.numParticles();
        int reserve = 4;
        output->write((char*)&header,sizeof(FileHeadder));
        write<LITEND>(*output, reserve);
        write<LITEND>(*output, (int)p.numAttributes());
            reserve = 0x2c;
        write<LITEND>(*output, reserve);

        std::vector<ParticleAttribute> attrs;
        int offset = 0;
        for (int i=0;i<p.numAttributes();i++) {
            ParticleAttribute attr;
            p.attributeInfo(i,attr);
            Channel ch;
            memset(&ch, 0, sizeof(Channel));
                    memcpy((char*)ch.name, attr.name.c_str(), attr.name.size());
            ch.offset = offset;
            switch (attr.type) {
            case FLOAT: ch.type=4; ch.arity=attr.count; offset += sizeof(float)*attr.count; break;
            case INT: ch.type=1; ch.arity=attr.count; offset += sizeof(int)*attr.count; break;
            case VECTOR: ch.type=4; ch.arity=attr.count; offset += sizeof(float)*attr.count; break;
			case INDEXEDSTR:; break;
            case NONE:;break;
            }
            if (ch.arity) {
    #ifdef AUTO_CASES
                if (ch.name[0] >= 'a' && ch.name[0] <= 'z') {
                    ch.name[0] -= 0x20;
                }
    #endif
                output->write((char*)&ch,sizeof(Channel));
                attrs.push_back(attr);
            }
        }

        z_stream z;
        z.zalloc = Z_NULL;z.zfree = Z_NULL;z.opaque = Z_NULL;
        if (deflateInit( &z, Z_DEFAULT_COMPRESSION ) != Z_OK) {
            if(errorStream) *errorStream<<"Zlib deflateInit error"<<std::endl;
            return false;
        }

        char out_buf[OUT_BUFSIZE+10];
        for (int particleIndex=0;particleIndex<p.numParticles();particleIndex++) {
            for (unsigned int attrIndex=0;attrIndex<attrs.size();attrIndex++) {
                if (attrs[attrIndex].type==Partio::INT) {
                    const int* data=p.data<int>(attrs[attrIndex],particleIndex);
                    if (!write_buffer(*output, z, (char*)out_buf, (void*)data, sizeof(int)*attrs[attrIndex].count, false, errorStream))
                        return false;
                } else if (attrs[attrIndex].type==Partio::FLOAT || attrs[attrIndex].type==Partio::VECTOR) {
                    const float* data=p.data<float>(attrs[attrIndex],particleIndex);
                    if (!write_buffer(*output, z, (char*)out_buf, (void*)data, sizeof(int)*attrs[attrIndex].count, false, errorStream))
                        return false;
                }
            }
        }
        write_buffer(*output, z, (char*)out_buf, 0, 0, true, errorStream);
        if (deflateEnd( &z ) != Z_OK) {
            if(errorStream) *errorStream<<"Zlib deflateEnd error"<<std::endl;
            return false;
        }
        // success
    }// end if numParticles > 0
    return true;
}
Example #3
0
int LUKS_hdr_backup(const char *backup_file, struct crypt_device *ctx)
{
	struct device *device = crypt_metadata_device(ctx);
	struct luks_phdr hdr;
	int fd, devfd, r = 0;
	size_t hdr_size;
	size_t buffer_size;
	ssize_t ret;
	char *buffer = NULL;

	r = LUKS_read_phdr(&hdr, 1, 0, ctx);
	if (r)
		return r;

	hdr_size = LUKS_device_sectors(&hdr) << SECTOR_SHIFT;
	buffer_size = size_round_up(hdr_size, crypt_getpagesize());

	buffer = crypt_safe_alloc(buffer_size);
	if (!buffer || hdr_size < LUKS_ALIGN_KEYSLOTS || hdr_size > buffer_size) {
		r = -ENOMEM;
		goto out;
	}

	log_dbg(ctx, "Storing backup of header (%zu bytes) and keyslot area (%zu bytes).",
		sizeof(hdr), hdr_size - LUKS_ALIGN_KEYSLOTS);

	log_dbg(ctx, "Output backup file size: %zu bytes.", buffer_size);

	devfd = device_open(ctx, device, O_RDONLY);
	if (devfd < 0) {
		log_err(ctx, _("Device %s is not a valid LUKS device."), device_path(device));
		r = -EINVAL;
		goto out;
	}

	if (read_lseek_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
			   buffer, hdr_size, 0) < (ssize_t)hdr_size) {
		r = -EIO;
		goto out;
	}

	/* Wipe unused area, so backup cannot contain old signatures */
	if (hdr.keyblock[0].keyMaterialOffset * SECTOR_SIZE == LUKS_ALIGN_KEYSLOTS)
		memset(buffer + sizeof(hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(hdr));

	fd = open(backup_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR);
	if (fd == -1) {
		if (errno == EEXIST)
			log_err(ctx, _("Requested header backup file %s already exists."), backup_file);
		else
			log_err(ctx, _("Cannot create header backup file %s."), backup_file);
		r = -EINVAL;
		goto out;
	}
	ret = write_buffer(fd, buffer, buffer_size);
	close(fd);
	if (ret < (ssize_t)buffer_size) {
		log_err(ctx, _("Cannot write header backup file %s."), backup_file);
		r = -EIO;
		goto out;
	}

	r = 0;
out:
	crypt_memzero(&hdr, sizeof(hdr));
	crypt_safe_free(buffer);
	return r;
}
Example #4
0
/*!
  @abstract Sort an unsorted BAM file based on the chromosome order
  and the leftmost position of an alignment

  @param  is_by_qname whether to sort by query name
  @param  fn       name of the file to be sorted
  @param  prefix   prefix of the output and the temporary files; upon
	                   sucessess, prefix.bam will be written.
  @param  max_mem  approxiate maximum memory (very inaccurate)
  @param full_path the given output path is the full path and not just the prefix

  @discussion It may create multiple temporary subalignment files
  and then merge them by calling bam_merge_core(). This function is
  NOT thread safe.
 */
void bam_sort_core_ext(int is_by_qname, const char *fn, const char *prefix, size_t _max_mem, int is_stdout, int n_threads, int level, int full_path)
{
	int ret, i, n_files = 0;
	size_t mem, max_k, k, max_mem;
	bam_header_t *header;
	bamFile fp;
	bam1_t *b, **buf;
	char *fnout = 0;
	char const *suffix = ".bam";
	if (full_path) suffix += 4;

	if (n_threads < 2) n_threads = 1;
	g_is_by_qname = is_by_qname;
	max_k = k = 0; mem = 0;
	max_mem = _max_mem * n_threads;
	buf = 0;
	fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
	if (fp == 0) {
		fprintf(stderr, "[bam_sort_core] fail to open file %s\n", fn);
		return;
	}
	header = bam_header_read(fp);
	if (is_by_qname) change_SO(header, "queryname");
	else change_SO(header, "coordinate");
	// write sub files
	for (;;) {
		if (k == max_k) {
			size_t old_max = max_k;
			max_k = max_k? max_k<<1 : 0x10000;
			buf = realloc(buf, max_k * sizeof(void*));
			memset(buf + old_max, 0, sizeof(void*) * (max_k - old_max));
		}
		if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
		b = buf[k];
		if ((ret = bam_read1(fp, b)) < 0) break;
		if (b->data_len < b->m_data>>2) { // shrink
			b->m_data = b->data_len;
			kroundup32(b->m_data);
			b->data = realloc(b->data, b->m_data);
		}
		mem += sizeof(bam1_t) + b->m_data + sizeof(void*) + sizeof(void*); // two sizeof(void*) for the data allocated to pointer arrays
		++k;
		if (mem >= max_mem) {
			n_files = sort_blocks(n_files, k, buf, prefix, header, n_threads);
			mem = k = 0;
		}
	}
	if (ret != -1)
		fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
	// output file name
	fnout = calloc(strlen(prefix) + 20, 1);
	if (is_stdout) sprintf(fnout, "-");
	else sprintf(fnout, "%s%s", prefix, suffix);
	// write the final output
	if (n_files == 0) { // a single block
		char mode[8];
		strcpy(mode, "w");
		if (level >= 0) sprintf(mode + 1, "%d", level < 9? level : 9);
		ks_mergesort(sort, k, buf, 0);
		write_buffer(fnout, mode, k, buf, header, n_threads);
	} else { // then merge
		char **fns;
		n_files = sort_blocks(n_files, k, buf, prefix, header, n_threads);
		fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n_files);
		fns = (char**)calloc(n_files, sizeof(char*));
		for (i = 0; i < n_files; ++i) {
			fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
			sprintf(fns[i], "%s.%.4d%s", prefix, i, suffix);
		}
		bam_merge_core2(is_by_qname, fnout, 0, n_files, fns, 0, 0, n_threads, level);
		for (i = 0; i < n_files; ++i) {
			unlink(fns[i]);
			free(fns[i]);
		}
		free(fns);
	}
	free(fnout);
	// free
	for (k = 0; k < max_k; ++k) {
		if (!buf[k]) continue;
		free(buf[k]->data);
		free(buf[k]);
	}
	free(buf);
	bam_header_destroy(header);
	bam_close(fp);
}
Example #5
0
void nbody_engine_cuda_bh_tex::fcompute(const nbcoord_t& t, const memory* _y, memory* _f)
{
	Q_UNUSED(t);
	const smemory*	y = dynamic_cast<const smemory*>(_y);
	smemory*		f = dynamic_cast<smemory*>(_f);

	if(y == NULL)
	{
		qDebug() << "y is not smemory";
		return;
	}

	if(f == NULL)
	{
		qDebug() << "f is not smemory";
		return;
	}

	advise_compute_count();

	size_t					count = m_data->get_count();
	std::vector<nbcoord_t>	host_y(y->size() / sizeof(nbcoord_t));
	std::vector<nbcoord_t>	host_mass(count);

	read_buffer(host_y.data(), y);
	read_buffer(host_mass.data(), m_mass);

	const nbcoord_t*	rx = host_y.data();
	const nbcoord_t*	ry = rx + count;
	const nbcoord_t*	rz = rx + 2 * count;
	const nbcoord_t*	mass = host_mass.data();

	nbody_space_heap	heap;
	heap.build(count, rx, ry, rz, mass, m_distance_to_node_radius_ratio);

	size_t			tree_size = heap.get_radius_sqr().size();

	if(m_dev_indites == NULL)
	{
		m_dev_tree_xyzr = dynamic_cast<smemory*>(create_buffer(tree_size * sizeof(nbcoord_t) * 4));
		m_dev_tree_mass = dynamic_cast<smemory*>(create_buffer(tree_size * sizeof(nbcoord_t)));
		m_dev_indites = dynamic_cast<smemory*>(create_buffer(tree_size * sizeof(int)));
	}

	const nbcoord_t*	dev_y = static_cast<const nbcoord_t*>(y->data());
	nbcoord_t*			dev_f = static_cast<nbcoord_t*>(f->data());
	int*				dev_indites = static_cast<int*>(m_dev_indites->data());

	static_assert(sizeof(vertex4<nbcoord_t>) == sizeof(nbcoord_t) * 4,
				  "sizeof(vertex4) must be equal to sizeof(nbcoord_t)*4");

	std::vector<vertex4<nbcoord_t>>	host_tree_xyzr(tree_size);
	std::vector<int>				host_indites(tree_size);

	#pragma omp parallel for
	for(size_t n = 0; n < tree_size; ++n)
	{
		host_tree_xyzr[n].x = heap.get_mass_center()[n].x;
		host_tree_xyzr[n].y = heap.get_mass_center()[n].y;
		host_tree_xyzr[n].z = heap.get_mass_center()[n].z;
		host_tree_xyzr[n].w = heap.get_radius_sqr()[n];
		host_indites[n] = static_cast<int>(heap.get_body_n()[n]);
	}

	write_buffer(m_dev_tree_xyzr, host_tree_xyzr.data());
	write_buffer(m_dev_tree_mass, heap.get_mass().data());
	write_buffer(m_dev_indites, host_indites.data());

	if(m_tree_layout == etl_heap)
	{
		fcompute_heap_bh_tex(0, static_cast<int>(count), static_cast<int>(tree_size), dev_f,
							 m_dev_tree_xyzr->tex(4), m_dev_tree_mass->tex(),
							 dev_indites, get_block_size());
	}
	else if(m_tree_layout == etl_heap_stackless)
	{
		fcompute_heap_bh_stackless(0, static_cast<int>(count), static_cast<int>(tree_size), dev_f,
								   m_dev_tree_xyzr->tex(4), m_dev_tree_mass->tex(),
								   dev_indites, get_block_size());
	}

	fcompute_xyz(dev_y, dev_f, static_cast<int>(count), get_block_size());
}
Example #6
0
static int write_byte(dest_t *dest, unsigned char val)
{
  return write_buffer(dest, &val, 1);
}
Example #7
0
int svr_save_xml(

  struct server *ps,
  int            mode)

  {
  char *id   = "svr_save_xml";
  char  buf[MAXLINE<<8];
  dynamic_string *ds;

  int   fds;
  int   rc;
  int   len;
  int   i;

  fds = open(path_svrdb, O_WRONLY | O_CREAT | O_Sync | O_TRUNC, 0600);

  if (fds < 0)
    {
    log_err(errno,id,msg_svdbopen);

    return(-1);
    }

  /* write the sv_qs info */
  snprintf(buf,sizeof(buf),
    "<server_db>\n<numjobs>%d</numjobs>\n<numque>%d</numque>\n<nextjobid>%d</nextjobid>\n<savetime>%ld</savetime>\n",
    ps->sv_qs.sv_numjobs,
    ps->sv_qs.sv_numque,
    ps->sv_qs.sv_jobidnumber,
    time_now);
  len = strlen(buf);

  if ((rc = write_buffer(buf,len,fds)))
    return(rc);

  /* write the attribute info */
  snprintf(buf,sizeof(buf),"<attributes>");
  if ((rc = write_buffer(buf,strlen(buf),fds)))
    return(rc);

  if ((ds = get_dynamic_string(-1, NULL)) == NULL)
    {
    log_err(ENOMEM, id, "");
    return(ENOMEM);
    }

  i = 0;
  while (i != SRV_ATR_LAST)
    {
    if (ps->sv_attr[i].at_flags & ATR_VFLAG_SET)
      {
      buf[0] = '\0';
      clear_dynamic_string(ds);

      if ((rc = attr_to_str(ds, svr_attr_def + i, ps->sv_attr[i], TRUE) != 0))
        {
        if (rc != NO_ATTR_DATA)
          {
          /* ERROR */
          snprintf(log_buffer,sizeof(log_buffer),
            "Not enough space to print attribute %s",
            svr_attr_def[i].at_name);
          log_err(-1,id,log_buffer);

          free_dynamic_string(ds);
          return(rc);
          }
        }
      else
        {
        snprintf(buf,sizeof(buf),"<%s>%s</%s>\n",
          svr_attr_def[i].at_name,
          ds->str,
          svr_attr_def[i].at_name);
        
        if (buf[0] != '\0')
          {
          if ((rc = write_buffer(buf,strlen(buf),fds)))
            {
            free_dynamic_string(ds);
            return(rc);
            }
          }
        }      
      }

    i++;
    }

  free_dynamic_string(ds);
  
  snprintf(buf,sizeof(buf),"</attributes>\n");
  if ((rc = write_buffer(buf,strlen(buf),fds)))
    return(rc);

  /* close the server_db */
  snprintf(buf,sizeof(buf),"</server_db>");
  if ((rc = write_buffer(buf,strlen(buf),fds)))
    return(rc);

  close(fds);

  return(0);

  } /* END svr_save_xml */
Example #8
0
void RecordVideo::run()
{
// Number of frames for user to know about.
	gui->reset_video();

// Wait for trigger
	trigger_lock->lock("RecordVideo::run");

	while( !done && !write_result ) {
		if( recording_paused ) {
			pause_record_lock->unlock();
			record_paused_lock->lock();
		}
		if( done ) break;
		VideoDevice *vdevice = record->vdevice;
		VFrame *capture_frame = get_buffer();
		vdevice->set_field_order(record->reverse_interlace);
// Capture a frame
		grab_result = read_buffer(capture_frame);
		if( done ) break;
		if( vdevice->config_updated() ) {
			flush_buffer();
			delete_buffer();
			config_update();
			gui->reset_video();
			record->record_monitor->reconfig();
			continue;
		}
		if( grab_result ) {
			Timer::delay(250);
			continue;
		}
		decompress_buffer(capture_frame);
		record->resync();
		write_buffer();
		if( record->monitor_video && capture_frame->get_data() )
			if( !writing_file || !record->is_behind() )
				record->record_monitor->update(capture_frame);
		if( writing_file && record->fill_underrun_frames ) {
			VFrame *last_frame = capture_frame;
			int fill = record->dropped;
			while( --fill >= 0 ) {
				capture_frame = get_buffer();
				capture_frame->copy_from(last_frame);
				last_frame = capture_frame;
				write_buffer();
			}
		}
		else
			record->written_frames += record->dropped;
		if( record->single_frame ) {
			record->single_frame = 0;
			record->stop_writing_file();
		}
		if( done ) break;
		if( !done ) done = write_result;
		if( done ) break;
		record->check_batch_complete();
	}

SET_TRACE
	flush_buffer();
	delete_buffer();
SET_TRACE
//TRACE("RecordVideo::run 2");
	if( write_result ) {
		ErrorBox error_box(PROGRAM_NAME ": Error",
			mwindow->gui->get_abs_cursor_x(1),
			mwindow->gui->get_abs_cursor_y(1));
			error_box.create_objects(_("No space left on disk."));
		error_box.run_window();
	}
SET_TRACE
}
Example #9
0
File: tospdif.c Project: IAPark/vlc
/* Adapted from libavformat/spdifenc.c:
 * It seems Dolby TrueHD frames have to be encapsulated in MAT frames before
 * they can be encapsulated in IEC 61937.
 * Here we encapsulate 24 TrueHD frames in a single MAT frame, padding them
 * to achieve constant rate.
 * The actual format of a MAT frame is unknown, but the below seems to work.
 * However, it seems it is not actually necessary for the 24 TrueHD frames to
 * be in an exact alignment with the MAT frame
 */
static int write_buffer_truehd( filter_t *p_filter, block_t *p_in_buf )
{
#define TRUEHD_FRAME_OFFSET     2560

    filter_sys_t *p_sys = p_filter->p_sys;

    if( !p_sys->p_out_buf
     && write_init( p_filter, p_in_buf, 61440, 61440 / 16 ) )
        return SPDIF_ERROR;

    int i_padding = 0;
    if( p_sys->truehd.i_frame_count == 0 )
    {
        static const char p_mat_start_code[20] = {
            0x07, 0x9E, 0x00, 0x03, 0x84, 0x01, 0x01, 0x01, 0x80, 0x00,
            0x56, 0xA5, 0x3B, 0xF4, 0x81, 0x83, 0x49, 0x80, 0x77, 0xE0
        };
        write_data( p_filter, p_mat_start_code, 20, true );
        /* We need to include the S/PDIF header in the first MAT frame */
        i_padding = TRUEHD_FRAME_OFFSET - p_in_buf->i_buffer - 20
                  - SPDIF_HEADER_SIZE;
    }
    else if( p_sys->truehd.i_frame_count == 11 )
    {
        /* The middle mat code need to be at the ((2560 * 12) - 4) offset */
        i_padding = TRUEHD_FRAME_OFFSET - p_in_buf->i_buffer - 4;
    }
    else if( p_sys->truehd.i_frame_count == 12 )
    {
        static const char p_mat_middle_code[12] = {
            0xC3, 0xC1, 0x42, 0x49, 0x3B, 0xFA,
            0x82, 0x83, 0x49, 0x80, 0x77, 0xE0
        };
        write_data( p_filter, p_mat_middle_code, 12, true );
        i_padding = TRUEHD_FRAME_OFFSET - p_in_buf->i_buffer - ( 12 - 4 );
    }
    else if( p_sys->truehd.i_frame_count == 23 )
    {
        static const char p_mat_end_code[16] = {
            0xC3, 0xC2, 0xC0, 0xC4, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x97, 0x11
        };

        /* The end mat code need to be at the ((2560 * 24) - 24) offset */
        i_padding = TRUEHD_FRAME_OFFSET - p_in_buf->i_buffer - 24;

        if( i_padding < 0 || p_in_buf->i_buffer + i_padding >
            p_sys->p_out_buf->i_buffer - p_sys->i_out_offset )
            return SPDIF_ERROR;

        write_buffer( p_filter, p_in_buf );
        write_padding( p_filter, i_padding );
        write_data( p_filter, p_mat_end_code, 16, true );
        write_finalize( p_filter, IEC61937_TRUEHD, 1 /* in bytes */ );
        p_sys->truehd.i_frame_count = 0;
        return SPDIF_SUCCESS;
    }
    else
        i_padding = TRUEHD_FRAME_OFFSET - p_in_buf->i_buffer;

    if( i_padding < 0 || p_in_buf->i_buffer + i_padding >
        p_sys->p_out_buf->i_buffer - p_sys->i_out_offset )
        return SPDIF_ERROR;

    write_buffer( p_filter, p_in_buf );
    write_padding( p_filter, i_padding );
    p_sys->truehd.i_frame_count++;
    return SPDIF_MORE_DATA;
}
Example #10
0
int
serialize_krb5_ctx(gss_ctx_id_t ctx, gss_buffer_desc *buf, int32_t *endtime)
{

	char *p, *end;
	static int constant_one = 1;
	static int constant_zero = 0;
	unsigned char fakeseed[16];
	uint32_t algorithm;

	if (!(buf->value = calloc(1, MAX_CTX_LEN)))
		goto out_err;
	p = buf->value;
	end = buf->value + MAX_CTX_LEN;


	/* initiate:  1 => initiating 0 => accepting */
	if (ctx->more_flags & LOCAL) {
		if (WRITE_BYTES(&p, end, constant_one)) goto out_err;
	}
	else {
		if (WRITE_BYTES(&p, end, constant_zero)) goto out_err;
	}

	/* seed_init: not used by kernel code */
	if (WRITE_BYTES(&p, end, constant_zero)) goto out_err;

	/* seed: not used by kernel code */
	memset(&fakeseed, 0, sizeof(fakeseed));
	if (write_bytes(&p, end, &fakeseed, 16)) goto out_err;

	/* signalg */
	algorithm = 0; /* SGN_ALG_DES_MAC_MD5	XXX */
	if (WRITE_BYTES(&p, end, algorithm)) goto out_err;

	/* sealalg */
	algorithm = 0; /* SEAL_ALG_DES		XXX */
	if (WRITE_BYTES(&p, end, algorithm)) goto out_err;

	/* endtime */
	if (WRITE_BYTES(&p, end, ctx->lifetime)) goto out_err;

	if (endtime)
		*endtime = ctx->lifetime;

	/* seq_send */
	if (WRITE_BYTES(&p, end, ctx->auth_context->local_seqnumber))
		goto out_err;
	/* mech_used */
	if (write_buffer(&p, end, (gss_buffer_desc*)&krb5oid)) goto out_err;

	/* enc: derive the encryption key and copy it into buffer */
	if (write_heimdal_enc_key(&p, end, ctx)) goto out_err;

	/* seq: get the sequence number key and copy it into buffer */
	if (write_heimdal_seq_key(&p, end, ctx)) goto out_err;

	buf->length = p - (char *)buf->value;
	printerr(2, "serialize_krb5_ctx: returning buffer "
		    "with %d bytes\n", buf->length);

	return 0;
out_err:
	printerr(0, "ERROR: failed exporting Heimdal krb5 ctx to kernel\n");
	if (buf->value) free(buf->value);
	buf->length = 0;
	return -1;
}
Example #11
0
caddr_t
ctf_gen(iiburst_t *iiburst, size_t *resszp, int do_compress)
{
	ctf_buf_t *buf = ctf_buf_new();
	ctf_header_t h;
	caddr_t outbuf;

	int i;

	target_requires_swap = do_compress & CTF_SWAP_BYTES;
	do_compress &= ~CTF_SWAP_BYTES;

	/*
	 * Prepare the header, and create the CTF output buffers.  The data
	 * object section and function section are both lists of 2-byte
	 * integers; we pad these out to the next 4-byte boundary if needed.
	 */
	h.cth_magic = CTF_MAGIC;
	h.cth_version = CTF_VERSION;
	h.cth_flags = do_compress ? CTF_F_COMPRESS : 0;
	h.cth_parlabel = strtab_insert(&buf->ctb_strtab,
	    iiburst->iib_td->td_parlabel);
	h.cth_parname = strtab_insert(&buf->ctb_strtab,
	    iiburst->iib_td->td_parname);

	h.cth_lbloff = 0;
	(void) list_iter(iiburst->iib_td->td_labels, write_label,
	    buf);

	pad_buffer(buf, 2);
	h.cth_objtoff = ctf_buf_cur(buf);
	for (i = 0; i < iiburst->iib_nobjts; i++)
		write_objects(iiburst->iib_objts[i], buf);

	pad_buffer(buf, 2);
	h.cth_funcoff = ctf_buf_cur(buf);
	for (i = 0; i < iiburst->iib_nfuncs; i++)
		write_functions(iiburst->iib_funcs[i], buf);

	pad_buffer(buf, 4);
	h.cth_typeoff = ctf_buf_cur(buf);
	(void) list_iter(iiburst->iib_types, write_type, buf);

	debug(2, "CTF wrote %d types\n", list_count(iiburst->iib_types));

	h.cth_stroff = ctf_buf_cur(buf);
	h.cth_strlen = strtab_size(&buf->ctb_strtab);

	if (target_requires_swap) {
		SWAP_16(h.cth_preamble.ctp_magic);
		SWAP_32(h.cth_parlabel);
		SWAP_32(h.cth_parname);
		SWAP_32(h.cth_lbloff);
		SWAP_32(h.cth_objtoff);
		SWAP_32(h.cth_funcoff);
		SWAP_32(h.cth_typeoff);
		SWAP_32(h.cth_stroff);
		SWAP_32(h.cth_strlen);
	}

	/*
	 * We only do compression for ctfmerge, as ctfconvert is only
	 * supposed to be used on intermediary build objects. This is
	 * significantly faster.
	 */
	if (do_compress)
		outbuf = write_compressed_buffer(&h, buf, resszp);
	else
		outbuf = write_buffer(&h, buf, resszp);

	ctf_buf_free(buf);
	return (outbuf);
}
Example #12
0
/*-------------------------------------------------------------------*/
static void printer_execute_ccw (DEVBLK *dev, BYTE code, BYTE flags,
        BYTE chained, U32 count, BYTE prevcode, int ccwseq,
        BYTE *iobuf, BYTE *more, BYTE *unitstat, U32 *residual)
{
int             rc = 0;                 /* Return code               */
U32             i;                      /* Loop counter              */
U32             num;                    /* Number of bytes to move   */
char           *eor;                    /* -> end of record string   */
char           *nls = "\n\n\n";         /* -> new lines              */
BYTE            c;                      /* Print character           */
char            hex[3];                 /* for hex conversion        */
char            wbuf[150];

    /* Reset flags at start of CCW chain */
    if (chained == 0)
    {
        dev->diaggate = 0;
    }

    /* Open the device file if necessary */
    if (dev->fd < 0 && !IS_CCW_SENSE(code))
        rc = open_printer (dev);
    else
    {
        /* If printer stopped, return intervention required */
        if (dev->stopdev && !IS_CCW_SENSE(code))
            rc = -1;
        else
            rc = 0;
    }

    if (rc < 0)
    {
        /* Set unit check with intervention required */
        dev->sense[0] = SENSE_IR;
        *unitstat = CSW_UC;
        return;
    }

    /* Process depending on CCW opcode */

    switch (code) {

    case 0x01: /* Write     No Space             */
    case 0x09: /* Write and Space 1 Line         */
    case 0x11: /* Write and Space 2 Lines        */
    case 0x19: /* Write and Space 3 Lines        */

    case 0x89: /* Write and Skip to Channel 1    */
    case 0x91: /* Write and Skip to Channel 2    */
    case 0x99: /* Write and Skip to Channel 3    */
    case 0xA1: /* Write and Skip to Channel 4    */
    case 0xA9: /* Write and Skip to Channel 5    */
    case 0xB1: /* Write and Skip to Channel 6    */
    case 0xB9: /* Write and Skip to Channel 7    */
    case 0xC1: /* Write and Skip to Channel 8    */
    case 0xC9: /* Write and Skip to Channel 9    */
    case 0xD1: /* Write and Skip to Channel 10   */
    case 0xD9: /* Write and Skip to Channel 11   */
    case 0xE1: /* Write and Skip to Channel 12   */
        if (dev->rawcc)
        {
            sprintf(hex,"%02x",code);
            write_buffer(dev, hex, 2, unitstat);
            if (*unitstat != 0) return;
            WRITE_LINE();
            write_buffer(dev, "\n", 1, unitstat);
            if (*unitstat == 0)
                *unitstat = CSW_CE | CSW_DE;
            return;
        }

        if ( dev->browse && dev->ccpend && ((chained & CCW_FLAGS_CD) == 0) )
        {
            dev->ccpend = 0;
            /* dev->currline++; */
            write_buffer(dev, "\n", 1, unitstat);
            if (*unitstat != 0) return;
        }
        WRITE_LINE();
        if ((flags & CCW_FLAGS_CD) == 0)
        {
            if    ( code <= 0x80 ) /* line control */
            {
                coun = code / 8;
                if ( coun == 0 )
                {
                    dev->chskip = 1;
                    if ( dev->browse )
                    {
                        dev->ccpend = 1;
                        *unitstat = 0;
                    }
                    else
                        write_buffer(dev, "\r", 1, unitstat);
                    if (*unitstat == 0)
                        *unitstat = CSW_CE | CSW_DE;
                    return;
                }

                dev->ccpend = 0;
                dev->currline += coun;
                write_buffer(dev, nls, coun, unitstat);
                if (*unitstat == 0)
                    *unitstat = CSW_CE | CSW_DE;
                return;
            }
            else  /*code >  0x80*/ /* chan control */
            {
                /*
                if ( dev->browse )
                {
                    dev->currline++;
                    write_buffer(dev, "\n", 1, unitstat);
                    if (*unitstat != 0) return;
                }
                */
                chan = ( code - 128 ) / 8;
                if ( chan == 1 )
                {
                    write_buffer(dev, "\r", 1, unitstat);
                    if (*unitstat != 0)
                        return;
                }
                SKIP_TO_CHAN();
                if (*unitstat == 0)
                    *unitstat = CSW_CE | CSW_DE;
                return;
            }

        }
        *unitstat = CSW_CE | CSW_DE;
        return;

    case 0x03: /* No Operation                   */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x0B: /*           Space 1 Line         */
    case 0x13: /*           Space 2 Lines        */
    case 0x1B: /*           Space 3 Lines        */

    case 0x8B: /*           Skip to Channel 1    */
    case 0x93: /*           Skip to Channel 2    */
    case 0x9B: /*           Skip to Channel 3    */
    case 0xA3: /*           Skip to Channel 4    */
    case 0xAB: /*           Skip to Channel 5    */
    case 0xB3: /*           Skip to Channel 6    */
    case 0xBB: /*           Skip to Channel 7    */
    case 0xC3: /*           Skip to Channel 8    */
    case 0xCB: /*           Skip to Channel 9    */
    case 0xD3: /*           Skip to Channel 10   */
    case 0xDB: /*           Skip to Channel 11   */
    case 0xE3: /*           Skip to Channel 12   */
        if (dev->rawcc)
        {
            sprintf(hex,"%02x",code);
            write_buffer(dev, hex, 2, unitstat);
            if (*unitstat != 0) return;
            eor = (dev->crlf) ? "\r\n" : "\n";
            write_buffer(dev, eor, (int)strlen(eor), unitstat);
            if (*unitstat == 0)
                *unitstat = CSW_CE | CSW_DE;
            return;
        }

        if    ( code <= 0x80 ) /* line control */
        {
            coun = code / 8;
            dev->ccpend = 0;
            dev->currline += coun;
            write_buffer(dev, nls, coun, unitstat);
            if (*unitstat == 0)
                *unitstat = CSW_CE | CSW_DE;
            return;
        }
        else  /*code >  0x80*/ /* chan control */
        {
            /*
            if ( dev->browse && dev->ccpend)
            {
                coun = 1;
                dev->ccpend = 0;
                dev->currline += coun;
                write_buffer(dev, nls, coun, unitstat);
                if (*unitstat != 0) return;
            }
            */
            chan = ( code - 128 ) / 8;
            SKIP_TO_CHAN();
            if (*unitstat == 0)
                *unitstat = CSW_CE | CSW_DE;
            return;
        }
        UNREACHABLE_CODE();

    case 0x63:
    /*---------------------------------------------------------------*/
    /* LOAD FORMS CONTROL BUFFER                                     */
    /*---------------------------------------------------------------*/
        if (dev->rawcc)
        {
            sprintf(hex,"%02x",code);
            write_buffer(dev, hex, 2, unitstat);
            if (*unitstat != 0) return;
            for (i = 0; i < count; i++)
            {
                sprintf(hex,"%02x",iobuf[i]);
                dev->buf[i*2] = hex[0];
                dev->buf[i*2+1] = hex[1];
            } /* end for(i) */
            write_buffer(dev, (char *)dev->buf, i*2, unitstat);
            if (*unitstat != 0) return;
            eor = (dev->crlf) ? "\r\n" : "\n";
            write_buffer(dev, eor, (int)strlen(eor), unitstat);
            if (*unitstat != 0) return;
        }
        else
        {
            U32 i = 0;
            int j = 1;
            int more = 1;
            for (i = 0; i <= FCBSIZE; i++) dev->fcb[i] = 0;

            dev->lpi = 6;
            dev->index = 0;
            i = 0;
            if (iobuf[0] & 0xc0)
            {
                /* First byte is a print position index */
                if ((iobuf[0] & 0xc0) == 0x80)
                    /* Indexing right */
                    dev->index = iobuf[0] & 0x1f;
                else
                    /* Indexing left */
                    dev->index = - (iobuf[0] & 0x1f);
                i = 1;
            }

            for (; i < count && j <= FCBSIZE && more; i++, j++)
            {
                dev->fcb[i] = iobuf[i] & 0x0f;
                if (dev->fcb[j] > 12)
                {
                    *residual = count - i;
                    *unitstat = CSW_CE | CSW_DE | CSW_UC;
                    dev->sense[0] = SENSE_CC;
                    return;
                }

                if (iobuf[i] & 0x10)
                {
                    /* Flag bit is on */
                    if (j == 1)
                        /* Flag bit in first byte means eight lines per inch */
                        dev->lpi = 8;
                    else
                        more = 0;
                }
            }
            if (more)
            {
                /* No flag in last byte or too many bytes */
                *residual = count - i;
                *unitstat = CSW_CE | CSW_DE | CSW_UC;
                dev->sense[0] = SENSE_CC;
                return;
            }
            *residual = count - i;
            dev->lpp = j - 1;

            fcb_dump(dev, wbuf, 150);
            WRMSG(HHC02210, "I", SSID_TO_LCSS(dev->ssid), dev->devnum, wbuf );
        }
        /* Return normal status */
        *residual = 0;
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x06:
    /*---------------------------------------------------------------*/
    /* DIAGNOSTIC CHECK READ                                         */
    /*---------------------------------------------------------------*/
        /* If not 1403, reject if not preceded by DIAGNOSTIC GATE */
        if (dev->devtype != 0x1403 && dev->diaggate == 0)
        {
            dev->sense[0] = SENSE_CR;
            *unitstat = CSW_CE | CSW_DE | CSW_UC;
            break;
        }

        /* Return normal status */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x07:
    /*---------------------------------------------------------------*/
    /* DIAGNOSTIC GATE                                               */
    /*---------------------------------------------------------------*/
        /* Command reject if 1403, or if chained to another CCW
           except a no-operation at the start of the CCW chain */
        if (dev->devtype == 0x1403 || ccwseq > 1
            || (chained && prevcode != 0x03))
        {
            dev->sense[0] = SENSE_CR;
            *unitstat = CSW_CE | CSW_DE | CSW_UC;
            break;
        }

        /* Set diagnostic gate flag */
        dev->diaggate = 1;

        /* Return normal status */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x0A:
    /*---------------------------------------------------------------*/
    /* DIAGNOSTIC READ UCS BUFFER                                    */
    /*---------------------------------------------------------------*/
        /* Reject if 1403 or not preceded by DIAGNOSTIC GATE */
        if (dev->devtype == 0x1403 || dev->diaggate == 0)
        {
            dev->sense[0] = SENSE_CR;
            *unitstat = CSW_CE | CSW_DE | CSW_UC;
            break;
        }

        /* Return normal status */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x12:
    /*---------------------------------------------------------------*/
    /* DIAGNOSTIC READ fcb                                           */
    /*---------------------------------------------------------------*/
        /* Reject if 1403 or not preceded by DIAGNOSTIC GATE */
        if (dev->devtype == 0x1403 || dev->diaggate == 0)
        {
            dev->sense[0] = SENSE_CR;
            *unitstat = CSW_CE | CSW_DE | CSW_UC;
            break;
        }

        /* Return normal status */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x23:
    /*---------------------------------------------------------------*/
    /* UNFOLD                                                        */
    /*---------------------------------------------------------------*/
        dev->fold = 0;
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x43:
    /*---------------------------------------------------------------*/
    /* FOLD                                                          */
    /*---------------------------------------------------------------*/
        dev->fold = 1;
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x73:
    /*---------------------------------------------------------------*/
    /* BLOCK DATA CHECK                                              */
    /*---------------------------------------------------------------*/
    /*
        *residual = 0;
    */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x7B:
    /*---------------------------------------------------------------*/
    /* ALLOW DATA CHECK                                              */
    /*---------------------------------------------------------------*/
    /*
        *residual = 0;
    */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0xEB:
    /*---------------------------------------------------------------*/
    /* UCS GATE LOAD                                                 */
    /*---------------------------------------------------------------*/
        /* Command reject if not first command in chain */
        if (chained != 0)
        {
            dev->sense[0] = SENSE_CR;
            *unitstat = CSW_CE | CSW_DE | CSW_UC;
            break;
        }

        /* Return normal status */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0xF3:
    /*---------------------------------------------------------------*/
    /* LOAD UCS BUFFER AND FOLD                                      */
    /*---------------------------------------------------------------*/
        /* For 1403, command reject if not chained to UCS GATE */
        /* Also allow ALLOW DATA CHECK to get TSS/370 working  */
        /* -- JRM 11/28/2007 */
        if (dev->devtype == 0x1403 &&
            ((prevcode != 0xEB) && (prevcode != 0x7B)))
        {
            dev->sense[0] = SENSE_CR;
            *unitstat = CSW_CE | CSW_DE | CSW_UC;
            break;
        }

        /* Set fold indicator and return normal status */
        dev->fold = 1;
        dev->chskip = 1;
    /*
        *residual = 0;
    */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0xFB:
    /*---------------------------------------------------------------*/
    /* LOAD UCS BUFFER (NO FOLD)                                     */
    /*---------------------------------------------------------------*/
        /* For 1403, command reject if not chained to UCS GATE */
        if (dev->devtype == 0x1403 && prevcode != 0xEB)
        {
            dev->sense[0] = SENSE_CR;
            *unitstat = CSW_CE | CSW_DE | CSW_UC;
            break;
        }

        /* Reset fold indicator and return normal status */
        dev->fold = 0;
        dev->chskip = 1;

    /*
        *residual = 0;
    */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x04:
    /*---------------------------------------------------------------*/
    /* SENSE                                                         */
    /*---------------------------------------------------------------*/
        /* Calculate residual byte count */
        num = (count < dev->numsense) ? count : dev->numsense;
        *residual = count - num;
        if (count < dev->numsense) *more = 1;

        /* Copy device sense bytes to channel I/O buffer */
        memcpy (iobuf, dev->sense, num);

        /* Clear the device sense bytes */
        memset (dev->sense, 0, sizeof(dev->sense));

        /* Return unit status */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0xE4:
    /*---------------------------------------------------------------*/
    /* SENSE ID                                                      */
    /*---------------------------------------------------------------*/

        /* SENSE ID is only supported if LEGACYSENSEID is ON;
         * otherwise, fall through to invalid operation.
         */
        if (sysblk.legacysenseid)
        {
            /* Calculate residual byte count */
            num = (count < dev->numdevid) ? count : dev->numdevid;
            *residual = count - num;
            if (count < dev->numdevid) *more = 1;

            /* Copy device identifier bytes to channel I/O buffer */
            memcpy (iobuf, dev->devid, num);

            /* Return unit status */
            *unitstat = CSW_CE | CSW_DE;
            break;
        }

    default:
    /*---------------------------------------------------------------*/
    /* INVALID OPERATION                                             */
    /*---------------------------------------------------------------*/
        /* Set command reject sense byte, and unit check status */
        dev->sense[0] = SENSE_CR;
        *unitstat = CSW_UC;

    } /* end switch(code) */

} /* end function printer_execute_ccw */
void menu_main(void)
{
	static uint8_t main_cursor = LINE0;	// These are now static so as to remember the main menu position
	static uint8_t main_top = MAINSTART;
	static uint8_t main_temp = 0;
	static uint8_t old_menu = 0;

	button = NONE;

	// Wait until user's finger is off button 1
	while(BUTTON1 == 0)
	{
		_delay_ms(50);
	}

	while(button != BACK)
	{
		// Clear buffer before each update
		clear_buffer(buffer);	

		// Print menu
		print_menu_frame(0);													// Frame
		
		for (uint8_t i = 0; i < 4; i++)
		{
			LCD_Display_Text(main_top+i,(const unsigned char*)Verdana8,ITEMOFFSET,(uint8_t)pgm_read_byte(&lines[i]));	// Lines
		}

		print_cursor(main_cursor);												// Cursor
		write_buffer(buffer,1);

		// Poll buttons when idle
		poll_buttons(true);

		// Handle menu changes
		update_menu(MAINITEMS, MAINSTART, 0, button, &main_cursor, &main_top, &main_temp);

		// If main menu item has changed, reset submenu positions
		// and flag to submenus that positions need to be reset
		if (main_temp != old_menu)
		{
			cursor = LINE0;
			menu_temp = 0;
			old_menu = main_temp;
			menu_flag = 1;
		}

		// If ENTER pressed, jump to menu 
		if (button == ENTER)
		{
			do_main_menu_item(main_temp);
			button = NONE;

			// Wait until user's finger is off button 1
			while(BUTTON1 == 0)
			{
				_delay_ms(50);
			}
		}
	}

//	menu_beep(1);
}
Example #14
0
int save_attr_xml(

  struct attribute_def *padef,   /* pbs_attribute definition array */
  pbs_attribute        *pattr,   /* ptr to pbs_attribute value array */
  int                   numattr, /* number of attributes in array */
  int                   fds)     /* file descriptor where attributes are written */

  {
  int             i;
  int             rc;
  char            buf[MAXLINE<<8];
  char            log_buf[LOCAL_LOG_BUF_SIZE];
  dynamic_string *ds = get_dynamic_string(-1, NULL);

  /* write the opening tag for attributes */
  snprintf(buf,sizeof(buf),"<attributes>\n");
  if ((rc = write_buffer(buf,strlen(buf),fds)) != 0)
    return(rc);

  for (i = 0; i < numattr; i++)
    {
    if (pattr[i].at_flags & ATR_VFLAG_SET)
      {
      buf[0] = '\0';
      clear_dynamic_string(ds);

      if ((rc = attr_to_str(ds, padef+i, pattr[i], TRUE)) != 0)
        {
        if (rc != NO_ATTR_DATA)
          {
          /* ERROR */
          snprintf(log_buf,sizeof(log_buf),
              "Not enough space to print pbs_attribute %s",
              padef[i].at_name);

          free_dynamic_string(ds);
          return(rc);
          }
        }
      else
        {
        snprintf(buf,sizeof(buf),"<%s>%s</%s>\n",
            padef[i].at_name,
            ds->str,
            padef[i].at_name);

        if ((rc = write_buffer(buf,strlen(buf),fds)) != 0)
          {
          free_dynamic_string(ds);
          return(rc);
          }
        }
      }
    } /* END for each pbs_attribute */

  free_dynamic_string(ds);

  /* close the attributes */
  snprintf(buf,sizeof(buf),"</attributes>\n");
  rc = write_buffer(buf,strlen(buf),fds);

  /* we can just return this since its the last write */
  return(rc);
  } /* END save_attr_xml() */
Example #15
0
static int write_long(dest_t *dest, glui32 val)
{
  unsigned char buf[4];
  Write4(buf, val);
  return write_buffer(dest, buf, 4);
}
Example #16
0
int job_save(

  job *pjob,  /* pointer to job structure */
  int  updatetype, /* 0=quick, 1=full, 2=new     */
  int  mom_port)   /* if 0 ignore otherwise append to end of job name. this is for multi-mom mode */

  {
  int     fds;
  int     i;
  char    namebuf1[MAXPATHLEN];
  char    namebuf2[MAXPATHLEN];
  char    save_buf[SAVEJOB_BUF_SIZE];
  const char   *tmp_ptr = NULL;
  size_t  buf_remaining = sizeof(save_buf);

  int     openflags;
  int     redo;
  time_t  time_now = time(NULL);


#ifdef PBS_MOM
  tmp_ptr = JOB_FILE_SUFFIX;
#else
  if (pjob->ji_is_array_template == TRUE)
    tmp_ptr = (char *)JOB_FILE_TMP_SUFFIX;
  else
    tmp_ptr = (char *)JOB_FILE_SUFFIX;
#endif

  if (mom_port)
    {
    snprintf(namebuf1, MAXPATHLEN, "%s%s%d%s",
        path_jobs, pjob->ji_qs.ji_fileprefix, mom_port, tmp_ptr);
    snprintf(namebuf2, MAXPATHLEN, "%s%s%d%s",
        path_jobs, pjob->ji_qs.ji_fileprefix, mom_port, JOB_FILE_COPY);
    }
  else
    {
    snprintf(namebuf1, MAXPATHLEN, "%s%s%s",
        path_jobs, pjob->ji_qs.ji_fileprefix, tmp_ptr);
    snprintf(namebuf2, MAXPATHLEN, "%s%s%s",
        path_jobs, pjob->ji_qs.ji_fileprefix, JOB_FILE_COPY);
    }

  /* if ji_modified is set, ie an pbs_attribute changed, then update mtime */

  if (pjob->ji_modified)
    {
    pjob->ji_wattr[JOB_ATR_mtime].at_val.at_long = time_now;
    }

  if (updatetype == SAVEJOB_QUICK)
    {
    openflags = O_WRONLY | O_Sync;

    /* NOTE:  open, do not create */

    fds = open(namebuf1, openflags, 0600);

    if (fds < 0)
      {
      char tmpLine[1024];

      snprintf(tmpLine, sizeof(tmpLine), "cannot open file '%s' for job %s in state %s (%s)",
               namebuf1,
               pjob->ji_qs.ji_jobid,
               PJobSubState[MAX(0,pjob->ji_qs.ji_substate)],
               (updatetype == 0) ? "quick" : "full");

      log_err(errno, "job_save", tmpLine);

      /* FAILURE */

      return(-1);
      }

    /* just write the "critical" base structure to the file */

    while ((i = write_ac_socket(fds, (char *)&pjob->ji_qs, sizeof(pjob->ji_qs))) != sizeof(pjob->ji_qs))
      {
      if ((i < 0) && (errno == EINTR))
        {
        /* retry the write */

        if (lseek(fds, (off_t)0, SEEK_SET) < 0)
          {
          log_err(errno, "job_save", (char *)"lseek");

          close(fds);

          return(-1);
          }

        continue;
        }
      else
        {
        log_err(errno, "job_save", (char *)"quickwrite");

        close(fds);

        /* FAILURE */

        return(-1);
        }
      }

    close(fds);
    }
  else /* SAVEJOB_FULL, SAVEJOB_NEW, SAVEJOB_ARY */
    {
    /*
     * write the whole structure to the file.
     * For a update, this is done to a new file to protect the
     * old against crashs.
     * The file is written in four parts:
     * (1) the job structure,
     * (2) the attribtes in "encoded" form,
     * (3) the attributes in the "external" form, and last
     * (4) the dependency list.
     */

    openflags = O_CREAT | O_WRONLY | O_Sync;

    /* NOTE:  create file if required */

    if (updatetype == SAVEJOB_NEW)
      fds = open(namebuf1, openflags, 0600);
    else
      fds = open(namebuf2, openflags, 0600);

    if (fds < 0)
      {
      log_err(errno, "job_save", (char *)"open for full save");

      return(-1);
      }

    for (i = 0; i < MAX_SAVE_TRIES; i++)
      {
      redo = 0; /* try to save twice */

#ifndef PBS_MOM
      lock_ss();
#endif

      if (save_struct((char *)&pjob->ji_qs, sizeof(pjob->ji_qs), fds, save_buf, &buf_remaining, sizeof(save_buf)) != PBSE_NONE)
        {
        redo++;
        }
      else if (save_attr(job_attr_def,
            pjob->ji_wattr,
            JOB_ATR_LAST,
            fds,
            save_buf,
            &buf_remaining,
            sizeof(save_buf)) != PBSE_NONE)
        {
        redo++;
        }

#ifdef PBS_MOM
      else if (save_tmsock(pjob, fds, save_buf, &buf_remaining, sizeof(save_buf)) != PBSE_NONE)
        {
        redo++;
        }

#endif  /* PBS_MOM */
      else if (write_buffer(save_buf, sizeof(save_buf) - buf_remaining, fds) != PBSE_NONE)
        {
        redo++;
        }

#ifndef PBS_MOM
      unlock_ss();
#endif

      if (redo != 0)
        {
        if (lseek(fds, (off_t)0, SEEK_SET) < 0)
          {
          log_err(errno, "job_save", (char *)"full lseek");
          }
        }
      else
        {
        break;
        }
      }  /* END for (i) */

    close(fds);

    if (i >= MAX_SAVE_TRIES)
      {
      if (updatetype == SAVEJOB_FULL)
        unlink(namebuf2);

      return(-1);
      }

    if (updatetype == SAVEJOB_FULL)
      {
      unlink(namebuf1);

      if (link(namebuf2, namebuf1) == -1)
        {
        log_event(
          PBSEVENT_ERROR | PBSEVENT_SECURITY,
          PBS_EVENTCLASS_JOB,
          pjob->ji_qs.ji_jobid,
          (char *)"Link in job_save failed");
        }
      else
        {
        unlink(namebuf2);
        }
      }

    pjob->ji_modified = 0;
    }  /* END (updatetype == SAVEJOB_QUICK) */

  return(PBSE_NONE);
  }  /* END job_save() */
Example #17
0
static int write_short(dest_t *dest, glui16 val)
{
  unsigned char buf[2];
  Write2(buf, val);
  return write_buffer(dest, buf, 2);
}
Example #18
0
void Display_sensors(void)
{
	bool	first_time = true;
		
	clear_buffer(buffer);
		
	// While BACK not pressed
	while(BUTTON1 != 0)
	{
		ReadGyros();
		ReadAcc();

		LCD_Display_Text(26,(const unsigned char*)Verdana8,37,0); 	// Gyro
		LCD_Display_Text(30,(const unsigned char*)Verdana8,77,0); 	// Acc
		//
		LCD_Display_Text(27,(const unsigned char*)Verdana8,5,13);	// Roll
		LCD_Display_Text(28,(const unsigned char*)Verdana8,5,23);	// Pitch
		LCD_Display_Text(29,(const unsigned char*)Verdana8,5,33);	// Yaw/Z
		//
		mugui_lcd_puts(itoa(gyroADC[ROLL],pBuffer,10),(const unsigned char*)Verdana8,40,13);
		mugui_lcd_puts(itoa(gyroADC[PITCH],pBuffer,10),(const unsigned char*)Verdana8,40,23);
		mugui_lcd_puts(itoa(gyroADC[YAW],pBuffer,10),(const unsigned char*)Verdana8,40,33);
		mugui_lcd_puts(itoa(accADC[ROLL],pBuffer,10),(const unsigned char*)Verdana8,80,13);
		mugui_lcd_puts(itoa(accADC[PITCH],pBuffer,10),(const unsigned char*)Verdana8,80,23);
		mugui_lcd_puts(itoa(accADC[YAW],pBuffer,10),(const unsigned char*)Verdana8,80,33);

		// Print bottom markers
		LCD_Display_Text(12, (const unsigned char*)Wingdings, 0, 57); 	// Left
		LCD_Display_Text(37, (const unsigned char*)Verdana8, 75, 55); 	// Inverted Calibrate
		LCD_Display_Text(60, (const unsigned char*)Verdana8, 108, 55); 	// Calibrate

		// Update buffer
		write_buffer(buffer);
		clear_buffer(buffer);

		if (first_time)
		{
			// Wait until finger off button
			Wait_BUTTON4();
			
			first_time = false;
		}
		
		// Normal calibrate button pressed
		if (BUTTON4 == 0)
		{
			// Wait until finger off button
			Wait_BUTTON4();
			
			// Pause until steady
			_delay_ms(250);
			
			// Calibrate sensors
			CalibrateGyrosFast();
			CalibrateAcc(NORMAL);
		}

		// Inverted calibrate button pressed
		if (BUTTON3 == 0)
		{
			// Wait until button snap dissipated
			_delay_ms(250);
			CalibrateAcc(REVERSED);
		}
	}
}
Example #19
0
static glui32 write_stackstate(dest_t *dest, int portable)
{
  glui32 res;
  glui32 lx;
  glui32 lastframe;

  /* If we're storing for the purpose of undo, we don't need to do any
     byte-swapping, because the result will only be used by this session. */
  if (!portable) {
    res = write_buffer(dest, stack, stackptr);
    if (res)
      return res;
    return 0;
  }

  /* Write a portable stack image. To do this, we have to write stack
     frames in order, bottom to top. Remember that the last word of
     every stack frame is a pointer to the beginning of that stack frame.
     (This includes the last frame, because the save opcode pushes on
     a call stub before it calls perform_save().) */

  lastframe = (glui32)(-1);
  while (1) {
    glui32 frameend, frm, frm2, frm3;
    unsigned char loctype, loccount;
    glui32 numlocals, frlen, locpos;

    /* Find the next stack frame (after the one in lastframe). Sadly,
       this requires searching the stack from the top down. We have to
       do this for *every* frame, which takes N^2 time overall. But
       save routines usually aren't nested very deep. 
       If it becomes a practical problem, we can build a stack-frame 
       array, which requires dynamic allocation. */
    for (frm = stackptr, frameend = stackptr;
         frm != 0 && (frm2 = Stk4(frm-4)) != lastframe;
         frameend = frm, frm = frm2) { };

    /* Write out the frame. */
    frm2 = frm;

    frlen = Stk4(frm2);
    frm2 += 4;
    res = write_long(dest, frlen);
    if (res)
      return res;
    locpos = Stk4(frm2);
    frm2 += 4;
    res = write_long(dest, locpos);
    if (res)
      return res;

    frm3 = frm2;

    numlocals = 0;
    while (1) {
      loctype = Stk1(frm2);
      frm2 += 1;
      loccount = Stk1(frm2);
      frm2 += 1;

      res = write_byte(dest, loctype);
      if (res)
        return res;
      res = write_byte(dest, loccount);
      if (res)
        return res;

      if (loctype == 0 && loccount == 0)
        break;

      numlocals++;
    }

    if ((numlocals & 1) == 0) {
      res = write_byte(dest, 0);
      if (res)
        return res;
      res = write_byte(dest, 0);
      if (res)
        return res;
      frm2 += 2;
    }

    if (frm2 != frm+locpos)
      fatal_error("Inconsistent stack frame during save.");

    /* Write out the locals. */
    for (lx=0; lx<numlocals; lx++) {
      loctype = Stk1(frm3);
      frm3 += 1;
      loccount = Stk1(frm3);
      frm3 += 1;
      
      if (loctype == 0 && loccount == 0)
        break;

      /* Put in up to 0, 1, or 3 bytes of padding, depending on loctype. */
      while (frm2 & (loctype-1)) {
        res = write_byte(dest, 0);
        if (res)
          return res;
        frm2 += 1;
      }

      /* Put in this set of locals. */
      switch (loctype) {

      case 1:
        do {
          res = write_byte(dest, Stk1(frm2));
          if (res)
            return res;
          frm2 += 1;
          loccount--;
        } while (loccount);
        break;

      case 2:
        do {
          res = write_short(dest, Stk2(frm2));
          if (res)
            return res;
          frm2 += 2;
          loccount--;
        } while (loccount);
        break;

      case 4:
        do {
          res = write_long(dest, Stk4(frm2));
          if (res)
            return res;
          frm2 += 4;
          loccount--;
        } while (loccount);
        break;

      }
    }

    if (frm2 != frm+frlen)
      fatal_error("Inconsistent stack frame during save.");

    while (frm2 < frameend) {
      res = write_long(dest, Stk4(frm2));
      if (res)
        return res;
      frm2 += 4;
    }

    /* Go on to the next frame. */
    if (frameend == stackptr)
      break; /* All done. */
    lastframe = frm;
  }

  return 0;
}
Example #20
0
void Display_status(void)
{
	int16_t temp, range, scale;
	uint16_t vbat_temp;
	int8_t	pos1, pos2, pos3;
	mugui_size16_t size;

	clear_buffer(buffer);

	// Display text
	LCD_Display_Text(4,(const unsigned char*)Verdana8,0,0); 	// Preset
	LCD_Display_Text(3,(const unsigned char*)Verdana8,0,11); 	// Version text
	LCD_Display_Text(5,(const unsigned char*)Verdana8,0,22); 	// RX sync
	LCD_Display_Text(6,(const unsigned char*)Verdana8,0,33); 	// Profile

	// Display menu and markers
	LCD_Display_Text(9, (const unsigned char*)Wingdings, 0, 59);// Down
	LCD_Display_Text(14,(const unsigned char*)Verdana8,10,55);	// Menu

	// Display values
	print_menu_text(0, 1, (22 + Config.MixMode), 45, 0);
	print_menu_text(0, 1, (48 + Config.RxMode), 45, 22);
	mugui_lcd_puts(itoa((Config.Flight + 1),pBuffer,10),(const unsigned char*)Verdana8,45,33);

	// Interrupt counter
	if (Config.RxMode == PWM)
	{
		LCD_Display_Text(18,(const unsigned char*)Verdana8,0,44); // Interrupt counter text
		mugui_lcd_puts(itoa(InterruptCount,pBuffer,10),(const unsigned char*)Verdana8,45,44); // Interrupt counter
	}

	// Draw battery
	drawrect(buffer, 100,4, 28, 50, 1);					// Battery body
	drawrect(buffer, 110,0, 8, 5, 1);					// Battery terminal

	vbat_temp = GetVbat();

	// Calculate battery voltage limits
	range = SystemVoltage - Config.PowerTriggerActual;
	scale = range / 50;

	// Look out for that divide-by-zero... :)
	if ((vbat_temp >= Config.PowerTriggerActual) && (scale > 0))
	{
		temp = (vbat_temp - Config.PowerTriggerActual) / scale;
	}
	else
	{
		temp = 0;
	}

	if (temp > 50) temp = 50;

	fillrect(buffer, 100,54-temp, 28, temp, 1);				// Battery filler (max is 60)

	// Display voltage
	uint8_t x_loc = 102;	// X location of voltage display
	uint8_t y_loc = 55;		// Y location of voltage display

	temp = vbat_temp/100;	// Display whole decimal part first
	mugui_text_sizestring(itoa(temp,pBuffer,10), (const unsigned char*)Verdana8, &size);
	mugui_lcd_puts(itoa(temp,pBuffer,10),(const unsigned char*)Verdana8,x_loc,y_loc);
	pos1 = size.x;

	vbat_temp = vbat_temp - (temp * 100); // Now display the parts to the right of the decimal point

	LCD_Display_Text(7,(const unsigned char*)Verdana8,(x_loc + pos1),y_loc);
	mugui_text_sizestring(".", (const unsigned char*)Verdana8, &size);
	pos3 = size.x;
	mugui_text_sizestring("0", (const unsigned char*)Verdana8, &size);
	pos2 = size.x;

	if (vbat_temp >= 10)
	{
		mugui_lcd_puts(itoa(vbat_temp,pBuffer,10),(const unsigned char*)Verdana8,(x_loc + pos1 + pos3),y_loc);
	}
	else
	{
		LCD_Display_Text(8,(const unsigned char*)Verdana8,(x_loc + pos1 + pos3),y_loc);
		mugui_lcd_puts(itoa(vbat_temp,pBuffer,10),(const unsigned char*)Verdana8,(x_loc + pos1 + pos2 + pos3),y_loc);
	}

	// Draw error messages, if any
	if (General_error != 0)
	{
		// Create message box
		fillrect(buffer, 14,8, 96, 48, 0);	// White box
		drawrect(buffer, 14,8, 96, 48, 1); 	// Outline

		// Prioritise error from top to bottom
		if((General_error & (1 << LVA_ALARM)) != 0)
		{
			LCD_Display_Text(134,(const unsigned char*)Verdana14,33,14); // Battery
			LCD_Display_Text(119,(const unsigned char*)Verdana14,46,34); // Low
		}
		else if((General_error & (1 << NO_SIGNAL)) != 0)
		{
			LCD_Display_Text(75,(const unsigned char*)Verdana14,51,13); // No
			LCD_Display_Text(76,(const unsigned char*)Verdana14,39,33); // Signal
		}
		else if((General_error & (1 << LOST_MODEL)) != 0)
		{
			LCD_Display_Text(131,(const unsigned char*)Verdana14,45,14); // Lost
			LCD_Display_Text(132,(const unsigned char*)Verdana14,40,34);// Model
		}
		else if((General_error & (1 << THROTTLE_HIGH)) != 0)
		{
			LCD_Display_Text(105,(const unsigned char*)Verdana14,28,14); // Throttle
			LCD_Display_Text(121,(const unsigned char*)Verdana14,46,34); // High
		}
	}

	// Write buffer to complete
	write_buffer(buffer);
	clear_buffer(buffer);
}
Example #21
0
void Display_status(void)
{
	int16_t temp, min, max, range, scale;
	int8_t	pos1, pos2, pos3;
	mugui_size16_t size;

	clear_buffer(buffer);

	// Display text
	LCD_Display_Text(4,(prog_uchar*)Verdana8,0,0); 		// Mode
	LCD_Display_Text(3,(prog_uchar*)Verdana8,0,11); 	// Version text
	LCD_Display_Text(5,(prog_uchar*)Verdana8,0,22); 	// Input
	LCD_Display_Text(46,(prog_uchar*)Verdana8,0,33); 	// Stability
	LCD_Display_Text(47,(prog_uchar*)Verdana8,0,44); 	// Autolevel

	// Display menu and markers
	LCD_Display_Text(9, (prog_uchar*)Wingdings, 0, 59);	// Down
	LCD_Display_Text(14,(prog_uchar*)Verdana8,10,55);	// Menu

	// Display values
	print_menu_text(0, 1, (18 + Config.RxMode), 50, 22);
	LCD_Display_Text(0,(prog_uchar*)Verdana8,50,11); 
	print_menu_text(0, 1, (22 + Config.MixMode), 33, 0);
	print_menu_text(0, 1, (101 + Stability), 50, 44);
	print_menu_text(0, 1, (101 + AutoLevel), 50, 33);

	// Draw battery
	drawrect(buffer, 100,4, 28, 50, 1);					// Battery body
	drawrect(buffer, 110,0, 8, 4, 1);					// Battery terminal

	GetVbat();

	min = Config.MinVoltage * Config.BatteryCells;		// Calculate battery voltage limits
	max = Config.MaxVoltage * Config.BatteryCells;
	range = max - min;
	scale = range / 50;

	if (vBat >= min) 
	{
		temp =(vBat - min) / scale;
	}
	else
	{
		temp = 0;
	}
	if (temp <= 0) temp = 0;
	if (temp > 50) temp = 50;

	fillrect(buffer, 100,54-temp, 28, temp, 1);				// Battery filler (max is 60)

	// Display voltage
	uint8_t x_loc = 102;	// X location of voltage display
	uint8_t y_loc = 55;		// Y location of voltage display

	temp = vBat/100;		// Display whole decimal part first
	mugui_text_sizestring(itoa(temp,pBuffer,10), (prog_uchar*)Verdana8, &size);
	mugui_lcd_puts(itoa(temp,pBuffer,10),(prog_uchar*)Verdana8,x_loc,y_loc);
	pos1 = size.x;

	vBat = vBat - (temp * 100); // Now display the parts to the right of the decimal point

	LCD_Display_Text(7,(prog_uchar*)Verdana8,(x_loc + pos1),y_loc);
	mugui_text_sizestring(".", (prog_uchar*)Verdana8, &size);
	pos3 = size.x;
	mugui_text_sizestring("0", (prog_uchar*)Verdana8, &size);
	pos2 = size.x;

	if (vBat >= 10)
	{
		mugui_lcd_puts(itoa(vBat,pBuffer,10),(prog_uchar*)Verdana8,(x_loc + pos1 + pos3),y_loc);
	}
	else
	{
		LCD_Display_Text(8,(prog_uchar*)Verdana8,(x_loc + pos1 + pos3),y_loc);
		mugui_lcd_puts(itoa(vBat,pBuffer,10),(prog_uchar*)Verdana8,(x_loc + pos1 + pos2 + pos3),y_loc);
	}

	// Draw error messages, if any
	if (General_error != 0)
	{
		// Create message box
		fillrect(buffer, 14,8, 96, 48, 0);	// White box
		drawrect(buffer, 14,8, 96, 48, 1); 	// Outline

		// Prioritise error from top to bottom
		if((General_error & (1 << SENSOR_ERROR)) != 0)
		{
			LCD_Display_Text(72,(prog_uchar*)Verdana14,35,14); // Sensor
			LCD_Display_Text(98,(prog_uchar*)Verdana14,43,34); // Error
			menu_beep(9);
		}
		else if((General_error & (1 << LOW_BATT)) != 0)
		{
			LCD_Display_Text(82,(prog_uchar*)Verdana14,33,14); 	// Battery
			LCD_Display_Text(119,(prog_uchar*)Verdana14,46,34); // Low
		}
		else if((General_error & (1 << NO_SIGNAL)) != 0)
		{
			LCD_Display_Text(75,(prog_uchar*)Verdana14,51,13); 	// No
			LCD_Display_Text(76,(prog_uchar*)Verdana14,39,33);  // Signal
			menu_beep(3);
		}
		else if((General_error & (1 << LOST_MODEL)) != 0)
		{
			LCD_Display_Text(99,(prog_uchar*)Verdana14,45,14); // Lost
			LCD_Display_Text(100,(prog_uchar*)Verdana14,40,34);// Model
		}
		else if((General_error & (1 << THROTTLE_HIGH)) != 0)
		{
			LCD_Display_Text(105,(prog_uchar*)Verdana14,28,14); // Throttle
			LCD_Display_Text(120,(prog_uchar*)Verdana14,46,34);	// High
			menu_beep(6);
		}
	}

	// Write buffer to complete
	write_buffer(buffer,1);
	clear_buffer(buffer);
}
Example #22
0
static int shm_write(lua_State *L)
{
  lua_apr_shm *object = check_shm(L, 1);
  object->last_op = &object->output.buffer;
  return write_buffer(L, &object->output);
}
Example #23
0
/*!
  @abstract Sort an unsorted BAM file based on the chromosome order
  and the leftmost position of an alignment

  @param  is_by_qname whether to sort by query name
  @param  fn       name of the file to be sorted
  @param  prefix   prefix of the temporary files (prefix.NNNN.bam are written)
  @param  fnout    name of the final output file to be written
  @param  modeout  sam_open() mode to be used to create the final output file
  @param  max_mem  approxiate maximum memory (very inaccurate)
  @return 0 for successful sorting, negative on errors

  @discussion It may create multiple temporary subalignment files
  and then merge them by calling bam_merge_core(). This function is
  NOT thread safe.
 */
int bam_sort_core_ext(int is_by_qname, const char *fn, const char *prefix, const char *fnout, const char *modeout, size_t _max_mem, int n_threads)
{
    int ret, i, n_files = 0;
    size_t mem, max_k, k, max_mem;
    bam_hdr_t *header;
    samFile *fp;
    bam1_t *b, **buf;

    if (n_threads < 2) n_threads = 1;
    g_is_by_qname = is_by_qname;
    max_k = k = 0; mem = 0;
    max_mem = _max_mem * n_threads;
    buf = NULL;
    fp = sam_open(fn, "r");
    if (fp == NULL) {
        fprintf(pysamerr, "[bam_sort_core] fail to open file %s\n", fn);
        return -1;
    }
    header = sam_hdr_read(fp);
    if (is_by_qname) change_SO(header, "queryname");
    else change_SO(header, "coordinate");
    // write sub files
    for (;;) {
        if (k == max_k) {
            size_t kk, old_max = max_k;
            max_k = max_k? max_k<<1 : 0x10000;
            buf = (bam1_t**)realloc(buf, max_k * sizeof(bam1_t*));
            for (kk = old_max; kk < max_k; ++kk) buf[kk] = NULL;
        }
        if (buf[k] == NULL) buf[k] = bam_init1();
        b = buf[k];
        if ((ret = sam_read1(fp, header, b)) < 0) break;
        if (b->l_data < b->m_data>>2) { // shrink
            b->m_data = b->l_data;
            kroundup32(b->m_data);
            b->data = (uint8_t*)realloc(b->data, b->m_data);
        }
        mem += sizeof(bam1_t) + b->m_data + sizeof(void*) + sizeof(void*); // two sizeof(void*) for the data allocated to pointer arrays
        ++k;
        if (mem >= max_mem) {
            n_files = sort_blocks(n_files, k, buf, prefix, header, n_threads);
            mem = k = 0;
        }
    }
    if (ret != -1)
        fprintf(pysamerr, "[bam_sort_core] truncated file. Continue anyway.\n");
    // write the final output
    if (n_files == 0) { // a single block
        ks_mergesort(sort, k, buf, 0);
        write_buffer(fnout, modeout, k, buf, header, n_threads);
    } else { // then merge
        char **fns;
        n_files = sort_blocks(n_files, k, buf, prefix, header, n_threads);
        fprintf(pysamerr, "[bam_sort_core] merging from %d files...\n", n_files);
        fns = (char**)calloc(n_files, sizeof(char*));
        for (i = 0; i < n_files; ++i) {
            fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
            sprintf(fns[i], "%s.%.4d.bam", prefix, i);
        }
        if (bam_merge_core2(is_by_qname, fnout, modeout, NULL, n_files, fns, MERGE_COMBINE_RG|MERGE_COMBINE_PG, NULL, n_threads) < 0) {
            // Propagate bam_merge_core2() failure; it has already emitted a
            // message explaining the failure, so no further message is needed.
            return -1;
        }
        for (i = 0; i < n_files; ++i) {
            unlink(fns[i]);
            free(fns[i]);
        }
        free(fns);
    }
    // free
    for (k = 0; k < max_k; ++k) bam_destroy1(buf[k]);
    free(buf);
    bam_hdr_destroy(header);
    sam_close(fp);
    return 0;
}
Example #24
0
void write_buffer_wrapper(int ring_no,const char* buf)
{
    write_buffer(ring_no,(uint8_t)buf[0]);
}
Example #25
0
float *CLimiter::GetNextA(const int ProcIndex) {
    float* InSignal=FetchA(jnIn);
    if (!InSignal) return NULL;
    unsigned int sample_index;
    unsigned int sample_count = m_BufferSize;
    unsigned int index_offs = 0;
    unsigned int i;
    float max_value = 0;
    float section_gain = 0;
    unsigned int run_length;
    unsigned int total_length = 0;
    float* output=AudioBuffers[ProcIndex]->Buffer;
    float* input=InSignal;

    while (total_length < sample_count)
    {
        run_length = buflen;
        if (total_length + run_length > sample_count)
            run_length = sample_count - total_length;

        while (ready_num < run_length)
        {
            //look for zero-crossings and detect a half cycle
            if (read_buffer(ringbuffer, buflen,pos, ready_num) >= 0)
            {
                index_offs = 0;
                while ((read_buffer(ringbuffer, buflen, pos, ready_num + index_offs) >= 0) &&
                        (ready_num + index_offs < run_length))
                {
                    index_offs++;
                }
            }
            else
            {
                index_offs = 0;
                while ((read_buffer(ringbuffer, buflen, pos, ready_num + index_offs) <= 0) &&
                        (ready_num + index_offs < run_length))
                {
                    index_offs++;
                }
            }

            /* search for max value in scanned halfcycle */
            max_value = 0;
            for (i = ready_num; i < ready_num + index_offs; i++)
            {
                if (fabs(read_buffer(ringbuffer, buflen, pos, i)) > max_value)
                {
                    max_value = fabs(read_buffer(ringbuffer, buflen, pos, i));
                }
            }
            if (max_value>0)
            {
                section_gain = limit_vol / max_value;
            }
            else
            {
                section_gain = 1.0;
            }
            if (max_value > limit_vol)
            {
                for (i = ready_num; i < ready_num + index_offs; i++)
                {
                    write_buffer(read_buffer(ringbuffer, buflen, pos, i) * section_gain, ringbuffer, buflen, pos, i);
                }
            }
            ready_num += index_offs;
        }

        /* push run_length values out of ringbuffer, feed with input */
        for (sample_index = 0; sample_index < run_length; sample_index++)
        {
            *(output++) = out_vol * push_buffer(*(input++), ringbuffer, buflen, &(pos));
        }
        ready_num -= run_length;
        total_length += run_length;
    }
    //*(latency) = buflen;
    return AudioBuffers[ProcIndex]->Buffer;
}
Example #26
0
/**
 * \brief write data into buffer and reset underrun flag
 */
static int play(void *data, int len, int flags) {
  if (!(flags & AOPLAY_FINAL_CHUNK))
    len -= len % ao_data.outburst;
  underrun = 0;
  return write_buffer(data, len);
}
void Display_status(void)
{
    int16_t temp;
    uint16_t vbat_temp;
    int8_t	pos1, pos2, pos3;
    mugui_size16_t size;

    clear_buffer(buffer);

    // Display text
    LCD_Display_Text(3,(const unsigned char*)Verdana8,0,0); 		// Version text
    LCD_Display_Text(5,(const unsigned char*)Verdana8,0,16); 	// RX sync
    LCD_Display_Text(6,(const unsigned char*)Verdana8,0,27); 	// Profile
    LCD_Display_Text(23,(const unsigned char*)Verdana8,88,27); 	// Pos
    LCD_Display_Text(133,(const unsigned char*)Verdana8,0,38); 	// Battery

    // Display menu and markers
    LCD_Display_Text(9, (const unsigned char*)Wingdings, 0, 59);	// Down
    LCD_Display_Text(14,(const unsigned char*)Verdana8,10,55);	// Menu

    // Display values
    print_menu_text(0, 1, (62 + Config.RxMode), 45, 16); // Rx mode
    mugui_lcd_puts(itoa(transition,pBuffer,10),(const unsigned char*)Verdana8,110,27); // Raw transition value

    if (Config.RxMode == PWM)
    {
        LCD_Display_Text(24,(const unsigned char*)Verdana8,77,38); // Interrupt counter text
        mugui_lcd_puts(itoa(InterruptCount,pBuffer,10),(const unsigned char*)Verdana8,110,38); // Interrupt counter
    }

    // Display transition point
    if (transition <= 0)
    {
        LCD_Display_Text(48,(const unsigned char*)Verdana8,45,27);
    }
    else if (transition >= 100)
    {
        LCD_Display_Text(50,(const unsigned char*)Verdana8,45,27);
    }
    else if (transition == Config.Transition_P1n)
    {
        LCD_Display_Text(49,(const unsigned char*)Verdana8,45,27);
    }
    else if (transition < Config.Transition_P1n)
    {
        LCD_Display_Text(51,(const unsigned char*)Verdana8,45,27);
    }
    else if (transition > Config.Transition_P1n)
    {
        LCD_Display_Text(52,(const unsigned char*)Verdana8,45,27);
    }

    // Display voltage
    uint8_t x_loc = 45;		// X location of voltage display
    uint8_t y_loc = 38;		// Y location of voltage display

    vbat_temp = GetVbat();
    temp = vbat_temp/100;	// Display whole decimal part first
    mugui_text_sizestring(itoa(temp,pBuffer,10), (const unsigned char*)Verdana8, &size);
    mugui_lcd_puts(itoa(temp,pBuffer,10),(const unsigned char*)Verdana8,x_loc,y_loc);
    pos1 = size.x;

    vbat_temp = vbat_temp - (temp * 100); // Now display the parts to the right of the decimal point

    LCD_Display_Text(7,(const unsigned char*)Verdana8,(x_loc + pos1),y_loc);
    mugui_text_sizestring(".", (const unsigned char*)Verdana8, &size);
    pos3 = size.x;
    mugui_text_sizestring("0", (const unsigned char*)Verdana8, &size);
    pos2 = size.x;

    if (vbat_temp >= 10)
    {
        mugui_lcd_puts(itoa(vbat_temp,pBuffer,10),(const unsigned char*)Verdana8,(x_loc + pos1 + pos3),y_loc);
    }
    else
    {
        LCD_Display_Text(8,(const unsigned char*)Verdana8,(x_loc + pos1 + pos3),y_loc);
        mugui_lcd_puts(itoa(vbat_temp,pBuffer,10),(const unsigned char*)Verdana8,(x_loc + pos1 + pos2 + pos3),y_loc);
    }

    // Display error messages
    if (General_error != 0)
    {
        // Create message box
        fillrect(buffer, 14,8, 96, 48, 0);	// White box
        drawrect(buffer, 14,8, 96, 48, 1); 	// Outline

        // Prioritise error from top to bottom
        if((General_error & (1 << LVA_ALARM)) != 0)
        {
            LCD_Display_Text(134,(const unsigned char*)Verdana14,33,14); // Battery
            LCD_Display_Text(73,(const unsigned char*)Verdana14,46,34); 	// Low
        }
        else if((General_error & (1 << NO_SIGNAL)) != 0)
        {
            LCD_Display_Text(75,(const unsigned char*)Verdana14,51,13); 	// No
            LCD_Display_Text(76,(const unsigned char*)Verdana14,39,33);  // Signal
        }
        else if((General_error & (1 << THROTTLE_HIGH)) != 0)
        {
            LCD_Display_Text(105,(const unsigned char*)Verdana14,28,14); // Throttle
            LCD_Display_Text(55,(const unsigned char*)Verdana14,46,34);	// High
        }
        else if((General_error & (1 << DISARMED)) != 0)
        {
            LCD_Display_Text(18,(const unsigned char*)Verdana14,25,24); 	// Disarmed
        }
    }

    // Write buffer to complete
    write_buffer(buffer,1);
    clear_buffer(buffer);
}
Example #28
0
bool
DPXOutput::open (const std::string &name, const ImageSpec &userspec,
                 OpenMode mode)
{
    if (mode == Create) {
        m_subimage = 0;
        if (m_subimage_specs.size() < 1) {
            m_subimage_specs.resize (1);
            m_subimage_specs[0] = userspec;
            m_subimages_to_write = 1;
        }
    } else if (mode == AppendSubimage) {
        if (m_write_pending)
            write_buffer ();
        ++m_subimage;
        if (m_subimage >= m_subimages_to_write) {
            error ("Exceeded the pre-declared number of subimages (%d)",
                   m_subimages_to_write);
            return false;
        }
        return prep_subimage (m_subimage, true);
        // Nothing else to do, the header taken care of when we opened with
        // Create.
    } else if (mode == AppendMIPLevel) {
        error ("DPX does not support MIP-maps");
        return false;
    }

    // From here out, all the heavy lifting is done for Create
    ASSERT (mode == Create);

    if (is_opened())
        close ();  // Close any already-opened file
    m_stream = new OutStream();
    if (! m_stream->Open(name.c_str ())) {
        error ("Could not open file \"%s\"", name.c_str ());
        return false;
    }
    m_dpx.SetOutStream (m_stream);
    m_dpx.Start ();
    m_subimage = 0;

    ImageSpec &m_spec (m_subimage_specs[m_subimage]); // alias the spec

    // Check for things this format doesn't support
    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
               m_spec.width, m_spec.height);
        return false;
    }

    if (m_spec.depth < 1)
        m_spec.depth = 1;
    else if (m_spec.depth > 1) {
        error ("DPX does not support volume images (depth > 1)");
        return false;
    }

    // some metadata
    std::string project = m_spec.get_string_attribute ("DocumentName", "");
    std::string copyright = m_spec.get_string_attribute ("Copyright", "");
    std::string datestr = m_spec.get_string_attribute ("DateTime", "");
    if (datestr.size () >= 19) {
        // libdpx's date/time format is pretty close to OIIO's (libdpx uses
        // %Y:%m:%d:%H:%M:%S%Z)
        // NOTE: the following code relies on the DateTime attribute being properly
        // formatted!
        // assume UTC for simplicity's sake, fix it if someone complains
        datestr[10] = ':';
        datestr.replace (19, -1, "Z");
    }

    // check if the client wants endianness reverse to native
    // assume big endian per Jeremy's request, unless little endian is
    // explicitly specified
    std::string endian = m_spec.get_string_attribute ("oiio:Endian", littleendian() ? "little" : "big");
    m_wantSwap = (littleendian() != Strutil::iequals (endian, "little"));

    m_dpx.SetFileInfo (name.c_str (),                       // filename
        datestr.c_str (),                                   // cr. date
        OIIO_INTRO_STRING,                                  // creator
        project.empty () ? NULL : project.c_str (),         // project
        copyright.empty () ? NULL : copyright.c_str (),     // copyright
        m_spec.get_int_attribute ("dpx:EncryptKey", ~0),    // encryption key
        m_wantSwap);

    // image info
    m_dpx.SetImageInfo (m_spec.width, m_spec.height);

    for (int s = 0;  s < m_subimages_to_write;  ++s) {
        prep_subimage (s, false);
        m_dpx.header.SetBitDepth (s, m_bitdepth);
        ImageSpec &spec (m_subimage_specs[s]);
        bool datasign = (spec.format == TypeDesc::INT8 ||
                         spec.format == TypeDesc::INT16);
        m_dpx.SetElement (s, m_desc, m_bitdepth, m_transfer, m_cmetr,
                          m_packing, dpx::kNone, datasign,
                          spec.get_int_attribute ("dpx:LowData", 0xFFFFFFFF),
                          spec.get_float_attribute ("dpx:LowQuantity", std::numeric_limits<float>::quiet_NaN()),
                          spec.get_int_attribute ("dpx:HighData", 0xFFFFFFFF),
                          spec.get_float_attribute ("dpx:HighQuantity", std::numeric_limits<float>::quiet_NaN()),
                          spec.get_int_attribute ("dpx:EndOfLinePadding", 0),
                          spec.get_int_attribute ("dpx:EndOfImagePadding", 0));
        std::string desc = spec.get_string_attribute ("ImageDescription", "");
        m_dpx.header.SetDescription (s, desc.c_str());
    }

    m_dpx.header.SetXScannedSize (m_spec.get_float_attribute
        ("dpx:XScannedSize", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetYScannedSize (m_spec.get_float_attribute
        ("dpx:YScannedSize", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetFramePosition (m_spec.get_int_attribute
        ("dpx:FramePosition", 0xFFFFFFFF));
    m_dpx.header.SetSequenceLength (m_spec.get_int_attribute
        ("dpx:SequenceLength", 0xFFFFFFFF));
    m_dpx.header.SetHeldCount (m_spec.get_int_attribute
        ("dpx:HeldCount", 0xFFFFFFFF));
    m_dpx.header.SetFrameRate (m_spec.get_float_attribute
        ("dpx:FrameRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetShutterAngle (m_spec.get_float_attribute
        ("dpx:ShutterAngle", std::numeric_limits<float>::quiet_NaN()));
    // FIXME: should we write the input version through or always default to 2.0?
    /*tmpstr = m_spec.get_string_attribute ("dpx:Version", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetVersion (tmpstr.c_str ());*/
    std::string tmpstr;
    tmpstr = m_spec.get_string_attribute ("dpx:Format", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetFormat (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:FrameId", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetFrameId (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:SlateInfo", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetSlateInfo (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:SourceImageFileName", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetSourceImageFileName (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:InputDevice", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetInputDevice (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:InputDeviceSerialNumber", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetInputDeviceSerialNumber (tmpstr.c_str ());
    m_dpx.header.SetInterlace (m_spec.get_int_attribute ("dpx:Interlace", 0xFF));
    m_dpx.header.SetFieldNumber (m_spec.get_int_attribute ("dpx:FieldNumber", 0xFF));
    m_dpx.header.SetHorizontalSampleRate (m_spec.get_float_attribute
        ("dpx:HorizontalSampleRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetVerticalSampleRate (m_spec.get_float_attribute
        ("dpx:VerticalSampleRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetTemporalFrameRate (m_spec.get_float_attribute
        ("dpx:TemporalFrameRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetTimeOffset (m_spec.get_float_attribute
        ("dpx:TimeOffset", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetBlackLevel (m_spec.get_float_attribute
        ("dpx:BlackLevel", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetBlackGain (m_spec.get_float_attribute
        ("dpx:BlackGain", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetBreakPoint (m_spec.get_float_attribute
        ("dpx:BreakPoint", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetWhiteLevel (m_spec.get_float_attribute
        ("dpx:WhiteLevel", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetIntegrationTimes (m_spec.get_float_attribute
        ("dpx:IntegrationTimes", std::numeric_limits<float>::quiet_NaN()));
    float aspect = m_spec.get_float_attribute ("PixelAspectRatio", 1.0f);
    int aspect_num, aspect_den;
    float_to_rational (aspect, aspect_num, aspect_den);
    m_dpx.header.SetAspectRatio (0, aspect_num);
    m_dpx.header.SetAspectRatio (1, aspect_den);
    m_dpx.header.SetXOffset ((unsigned int)std::max (0, m_spec.x));
    m_dpx.header.SetYOffset ((unsigned int)std::max (0, m_spec.y));
    m_dpx.header.SetXOriginalSize ((unsigned int)m_spec.full_width);
    m_dpx.header.SetYOriginalSize ((unsigned int)m_spec.full_height);

    static int DpxOrientations[] = { 0,
        dpx::kLeftToRightTopToBottom, dpx::kRightToLeftTopToBottom,
        dpx::kLeftToRightBottomToTop, dpx::kRightToLeftBottomToTop, 
        dpx::kTopToBottomLeftToRight, dpx::kTopToBottomRightToLeft, 
        dpx::kBottomToTopLeftToRight, dpx::kBottomToTopRightToLeft };
    int orient = m_spec.get_int_attribute ("Orientation", 0);
    orient = DpxOrientations[clamp (orient, 0, 8)];
    m_dpx.header.SetImageOrientation ((dpx::Orientation)orient);

    std::string timecode = m_spec.get_string_attribute ("dpx:TimeCode", "");
    int tmpint = m_spec.get_int_attribute ("dpx:TimeCode", ~0);
    if (timecode.size () > 0)
        m_dpx.header.SetTimeCode (timecode.c_str ());
    else if (tmpint != ~0)
        m_dpx.header.timeCode = tmpint;
    m_dpx.header.userBits = m_spec.get_int_attribute ("dpx:UserBits", ~0);
    std::string srcdate = m_spec.get_string_attribute ("dpx:SourceDateTime", "");
    if (srcdate.size () >= 19) {
        // libdpx's date/time format is pretty close to OIIO's (libdpx uses
        // %Y:%m:%d:%H:%M:%S%Z)
        // NOTE: the following code relies on the DateTime attribute being properly
        // formatted!
        // assume UTC for simplicity's sake, fix it if someone complains
        srcdate[10] = ':';
        srcdate.replace (19, -1, "Z");
        m_dpx.header.SetSourceTimeDate (srcdate.c_str ());
    }
    
    // commit!
    if (!m_dpx.WriteHeader ()) {
        error ("Failed to write DPX header");
        return false;
    }

    // user data
    ImageIOParameter *user = m_spec.find_attribute ("dpx:UserData");
    if (user && user->datasize () > 0) {
        if (user->datasize () > 1024 * 1024) {
            error ("User data block size exceeds 1 MB");
            return false;
        }
        // FIXME: write the missing libdpx code
        /*m_dpx.SetUserData (user->datasize ());
        if (!m_dpx.WriteUserData ((void *)user->data ())) {
            error ("Failed to write user data");
            return false;
        }*/
    }

    return prep_subimage (m_subimage, true);
}
int main(int argc, char const *argv[])
{
    /* Get platform */
    cl_platform_id platform;
    cl_uint num_platforms;
    cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clGetPlatformIDs' failed\n");
        exit(1);
    }

    printf("Number of platforms: %d\n", num_platforms);
    printf("platform=%p\n", platform);

    /* Get platform name */
    char platform_name[100];
    ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clGetPlatformInfo' failed\n");
        exit(1);
    }

    printf("platform.name='%s'\n\n", platform_name);

    /* Get device */
    cl_device_id device;
    cl_uint num_devices;
    ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clGetDeviceIDs' failed\n");
        exit(1);
    }

    printf("Number of devices: %d\n", num_devices);
    printf("device=%p\n", device);

    /* Get device name */
    char device_name[100];
    ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
                          device_name, NULL);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clGetDeviceInfo' failed\n");
        exit(1);
    }

    printf("device.name='%s'\n", device_name);
    printf("\n");

    /* Create a Context Object */
    cl_context context;
    context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clCreateContext' failed\n");
        exit(1);
    }

    printf("context=%p\n", context);

    /* Create a Command Queue Object*/
    cl_command_queue command_queue;
    command_queue = clCreateCommandQueue(context, device, 0, &ret);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clCreateCommandQueue' failed\n");
        exit(1);
    }

    printf("command_queue=%p\n", command_queue);
    printf("\n");

    /* Program source */
    unsigned char *source_code;
    size_t source_length;

    /* Read program from 'min_uchar16uchar16.cl' */
    source_code = read_buffer("min_uchar16uchar16.cl", &source_length);

    /* Create a program */
    cl_program program;
    program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret);

    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clCreateProgramWithSource' failed\n");
        exit(1);
    }
    printf("program=%p\n", program);

    /* Build program */
    ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
    if (ret != CL_SUCCESS )
    {
        size_t size;
        char *log;

        /* Get log size */
        clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);

        /* Allocate log and print */
        log = malloc(size);
        clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
        printf("error: call to 'clBuildProgram' failed:\n%s\n", log);

        /* Free log and exit */
        free(log);
        exit(1);
    }

    printf("program built\n");
    printf("\n");

    /* Create a Kernel Object */
    cl_kernel kernel;
    kernel = clCreateKernel(program, "min_uchar16uchar16", &ret);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clCreateKernel' failed\n");
        exit(1);
    }

    /* Create and allocate host buffers */
    size_t num_elem = 10;

    /* Create and init host side src buffer 0 */
    cl_uchar16 *src_0_host_buffer;
    src_0_host_buffer = malloc(num_elem * sizeof(cl_uchar16));
    for (int i = 0; i < num_elem; i++)
        src_0_host_buffer[i] = (cl_uchar16) {
        {
            2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
        }
    };

    /* Create and init device side src buffer 0 */
    cl_mem src_0_device_buffer;
    src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_uchar16), NULL, &ret);
    if (ret != CL_SUCCESS)
    {
        printf("error: could not create source buffer\n");
        exit(1);
    }
    ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_uchar16), src_0_host_buffer, 0, NULL, NULL);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clEnqueueWriteBuffer' failed\n");
        exit(1);
    }

    /* Create and init host side src buffer 1 */
    cl_uchar16 *src_1_host_buffer;
    src_1_host_buffer = malloc(num_elem * sizeof(cl_uchar16));
    for (int i = 0; i < num_elem; i++)
        src_1_host_buffer[i] = (cl_uchar16) {
        {
            2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
        }
    };

    /* Create and init device side src buffer 1 */
    cl_mem src_1_device_buffer;
    src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_uchar16), NULL, &ret);
    if (ret != CL_SUCCESS)
    {
        printf("error: could not create source buffer\n");
        exit(1);
    }
    ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_uchar16), src_1_host_buffer, 0, NULL, NULL);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clEnqueueWriteBuffer' failed\n");
        exit(1);
    }

    /* Create host dst buffer */
    cl_uchar16 *dst_host_buffer;
    dst_host_buffer = malloc(num_elem * sizeof(cl_uchar16));
    memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_uchar16));

    /* Create device dst buffer */
    cl_mem dst_device_buffer;
    dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_uchar16), NULL, &ret);
    if (ret != CL_SUCCESS)
    {
        printf("error: could not create dst buffer\n");
        exit(1);
    }

    /* Set kernel arguments */
    ret = CL_SUCCESS;
    ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
    ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer);
    ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clSetKernelArg' failed\n");
        exit(1);
    }

    /* Launch the kernel */
    size_t global_work_size = num_elem;
    size_t local_work_size = num_elem;
    ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
        exit(1);
    }

    /* Wait for it to finish */
    clFinish(command_queue);

    /* Read results from GPU */
    ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_uchar16), dst_host_buffer, 0, NULL, NULL);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clEnqueueReadBuffer' failed\n");
        exit(1);
    }

    /* Dump dst buffer to file */
    char dump_file[100];
    sprintf((char *)&dump_file, "%s.result", argv[0]);
    write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_uchar16));
    printf("Result dumped to %s\n", dump_file);
    /* Free host dst buffer */
    free(dst_host_buffer);

    /* Free device dst buffer */
    ret = clReleaseMemObject(dst_device_buffer);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clReleaseMemObject' failed\n");
        exit(1);
    }

    /* Free host side src buffer 0 */
    free(src_0_host_buffer);

    /* Free device side src buffer 0 */
    ret = clReleaseMemObject(src_0_device_buffer);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clReleaseMemObject' failed\n");
        exit(1);
    }

    /* Free host side src buffer 1 */
    free(src_1_host_buffer);

    /* Free device side src buffer 1 */
    ret = clReleaseMemObject(src_1_device_buffer);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clReleaseMemObject' failed\n");
        exit(1);
    }

    /* Release kernel */
    ret = clReleaseKernel(kernel);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clReleaseKernel' failed\n");
        exit(1);
    }

    /* Release program */
    ret = clReleaseProgram(program);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clReleaseProgram' failed\n");
        exit(1);
    }

    /* Release command queue */
    ret = clReleaseCommandQueue(command_queue);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clReleaseCommandQueue' failed\n");
        exit(1);
    }

    /* Release context */
    ret = clReleaseContext(context);
    if (ret != CL_SUCCESS)
    {
        printf("error: call to 'clReleaseContext' failed\n");
        exit(1);
    }

    return 0;
}
Example #30
0
static ssize_t ja_write(void *data, const void *buf, size_t size)
{
   jack_t *jd = (jack_t*)data;

   return write_buffer(jd, (const float*)buf, size);
}