Example #1
0
static ssize_t misc_write(struct file *filp, const char __user * buf,
			size_t count, loff_t *ppos)
{
	struct io_device *iod = (struct io_device *)filp->private_data;
	int frame_len = 0;
	char frame_header_buf[sizeof(struct raw_hdr)];
	struct sk_buff *skb;

	/* TODO - check here flow control for only raw data */

	/* VIA OTA update framming routine*/
	if (iod->format == IPC_UPDATE)
		return io_dev_modem_update_write(iod, buf, count);

	frame_len = count + SIZE_OF_HDLC_START + get_header_size(iod)
				+ SIZE_OF_HDLC_END;
	skb = alloc_skb(frame_len, GFP_ATOMIC);
	if (!skb) {
		pr_err("[MODEM_IF] fail alloc skb (%d)\n", __LINE__);
		return -ENOMEM;
	}

	switch (iod->format) {
	case IPC_BOOT:
	case IPC_RAMDUMP:
		if (copy_from_user(skb_put(skb, count), buf, count) != 0)
			return -EFAULT;
		break;

	case IPC_RFS:
		memcpy(skb_put(skb, SIZE_OF_HDLC_START), hdlc_start,
				SIZE_OF_HDLC_START);
		if (copy_from_user(skb_put(skb, count), buf, count) != 0)
			return -EFAULT;
		memcpy(skb_put(skb, SIZE_OF_HDLC_END), hdlc_end,
					SIZE_OF_HDLC_END);
		break;

	default:
		memcpy(skb_put(skb, SIZE_OF_HDLC_START), hdlc_start,
				SIZE_OF_HDLC_START);
		memcpy(skb_put(skb, get_header_size(iod)),
			get_header(iod, count, frame_header_buf),
			get_header_size(iod));
		if (copy_from_user(skb_put(skb, count), buf, count) != 0)
			return -EFAULT;
		memcpy(skb_put(skb, SIZE_OF_HDLC_END), hdlc_end,
					SIZE_OF_HDLC_END);
		break;
	}

	/* send data with sk_buff, link device will put sk_buff
	 * into the specific sk_buff_q and run work-q to send data
	 */
	return iod->link->send(iod->link, iod, skb);
}
char ImageReader::get_header_byte(int index)
{
	if ( index < get_header_size() )
		return this->header[index];
	else
		return 0;
}
static OSMPBF__BlobHeader *read_blob_header(FILE *input)
{
  void *buffer;
  size_t length = get_header_size(input);
  OSMPBF__BlobHeader *header = NULL;

  if(length < 1 || length > MAX_BLOB_HEADER_SIZE)
  {
    if(feof(input))
      return NULL;
    else
      rb_raise(rb_eIOError, "Invalid blob header size");
  }

  if(!(buffer = malloc(length)))
    rb_raise(rb_eNoMemError, "Unable to allocate memory for the blob header");

  if(!fread(buffer, length, 1, input))
  {
    free(buffer);
    rb_raise(rb_eIOError, "Unable to read the blob header");
  }

  header = osmpbf__blob_header__unpack(NULL, length, buffer);

  free(buffer);

  if(header == NULL)
    rb_raise(rb_eIOError, "Unable to unpack the blob header");

  return header;
}
Example #4
0
// -----------------------------------------------------------------------------
void BIndexNode::init(				// init a new node, which not exist
	int level,							// level (depth) in b-tree
	BTree* btree)						// b-tree of this node
{
	btree_ = btree;					// init <btree_>
	level_ = (char) level;			// init <level_>

	num_entries_ = 0;				// init <num_entries_>
	left_sibling_ = -1;				// init <left_sibling_>
	right_sibling_ = -1;				// init <right_sibling_>
	dirty_ = true;					// init <dirty_>

									// init <capacity_>
	int b_length = btree_->file_->get_blocklength();
	capacity_ = (b_length - get_header_size()) / get_entry_size();
	if (capacity_ < 50) {			// ensure at least 50 entries
		printf("capacity = %d\n", capacity_);
		error("BIndexNode::init() capacity too small.\n", true);
	}

	key_ = new float[capacity_];	// init <key_>
	for (int i = 0; i < capacity_; i++) {
		key_[i] = MINREAL;
	}
	son_ = new int[capacity_];		// init <son_>
	for (int i = 0; i < capacity_; i++) {
		son_[i] = -1;
	}

	char* blk = new char[b_length];	// init <block_>, get new addr
	block_ = btree_->file_->append_block(blk);
	delete[] blk; blk = NULL;
}
// (virtual)
bool AdlibSfxDecoder::initialize(
    const void* raw_data,
    int raw_size,
    int dst_rate)
{
    if (!AdlibDecoder::initialize(
        raw_data,
        raw_size,
        dst_rate))
    {
        return false;
    }

    reader_.initialize(raw_data, raw_size);

    int sfx_length = bstone::Endian::le(reader_.read_s32());

    if (sfx_length <= 0)
        return false;

    if ((sfx_length + get_header_size()) >= raw_size)
        return false;

    // Skip priority.
    reader_.skip(2);

    instrument_.m_char = reader_.read_u8();
    instrument_.c_char = reader_.read_u8();
    instrument_.m_scale = reader_.read_u8();
    instrument_.c_scale = reader_.read_u8();
    instrument_.m_attack = reader_.read_u8();
    instrument_.c_attack = reader_.read_u8();
    instrument_.m_sus = reader_.read_u8();
    instrument_.c_sus = reader_.read_u8();
    instrument_.m_wave = reader_.read_u8();
    instrument_.c_wave = reader_.read_u8();

    // Skip nConn, voice, mode and 3 unused octets
    reader_.skip(6);

    if (instrument_.m_sus == 0 && instrument_.c_sus == 0)
        return false;

    hf_ = reader_.read_u8();
    hf_ = ((hf_ & 7) << 2) | 0x20;

    initialize_instrument();

    command_index_ = 0;
    commands_count_ = sfx_length;
    samples_per_tick_ = emulator_.get_sample_rate() / get_tick_rate();
    set_dst_length_in_samples(samples_per_tick_ * sfx_length);
    remains_count_ = 0;

    set_is_initialized(true);

    return true;
}
Example #6
0
/* remove hdlc header and store IPC header */
static int rx_hdlc_head_check(struct io_device *iod, char *buf, unsigned rest)
{
	struct header_data *hdr = &iod->h_data;
	int head_size = get_header_size(iod);
	int done_len = 0;
	int len = 0;

	/* first frame, remove start header 7F */
	if (!hdr->start) {
		len = rx_hdlc_head_start_check(buf);
		if (len < 0) {
			pr_err("[MODEM_IF] Wrong HDLC start: 0x%x\n", *buf);
			return len; /*Wrong hdlc start*/
		}

		pr_debug("[MODEM_IF] check len : %d, rest : %d (%d)\n", len,
					rest, __LINE__);

		/* set the start flag of current packet */
		hdr->start = HDLC_START;
		hdr->len = 0;

		/* debug print */
		switch (iod->format) {
		case IPC_FMT:
		case IPC_RAW:
		case IPC_MULTI_RAW:
		case IPC_RFS:
			/* TODO: print buf...  */
			break;

		case IPC_CMD:
		case IPC_BOOT:
		case IPC_RAMDUMP:
		default:
			break;
		}
		buf += len;
		done_len += len;
		rest -= len; /* rest, call by value */
	}

	pr_debug("[MODEM_IF] check len : %d, rest : %d (%d)\n", len, rest,
				__LINE__);

	/* store the IPC header to iod priv */
	if (hdr->len < head_size) {
		len = min(rest, head_size - hdr->len);
		memcpy(hdr->hdr + hdr->len, buf, len);
		hdr->len += len;
		done_len += len;
	}

	pr_debug("[MODEM_IF] check done_len : %d, rest : %d (%d)\n", done_len,
				rest, __LINE__);
	return done_len;
}
static int test_02_incorrect_payload_type(uint32_t data)
{
    bool failed = false;
    bass_return_code result = BASS_RC_ERROR_UNKNOWN;
    bass_payload_type_t correct_payload_type = BASS_PL_TYPE_X_LOADER;
    bass_payload_type_t payload_type = BASS_PL_TYPE_TAPP;
    bass_hash_type_t hashtype = BASS_APP_SHA256_HASH;
    size_t i = 0;
    size_t ehash_size = SHA256_HASH_SIZE;
    uint8_t ehash[SHA256_HASH_SIZE];
    uint32_t payload_size = 0;
    uint32_t payload_offset = 0;

    (void)data;

    dprintf(INFO, "Starting test\n");
    memset(&ehash, 0, sizeof(ehash));

    /*
     * We use the correct payload_type when getting the expected hash from
     * verify signed header, since the purpose of this test case is to test if
     * bass_app_test_check_payload_hash is working as it should.
     */
    result = get_ehash(signed_payload, signed_payload_size,
                       correct_payload_type, ehash);
    if (result != BASS_RC_SUCCESS) {
        dprintf(ERROR, "failed to getting ehash\n");
        return result;
    }

    payload_offset = get_header_size(signed_payload);
    payload_size = get_payload_size(signed_payload);

    for (i = payload_type;
         (i <= BASS_PL_TYPE_FRAC) && (i != correct_payload_type);
         ++i) {
        result = bass_check_payload_hash(&hashtype,
                                     &payload_type,
                                     (void *)(signed_payload + payload_offset),
                                     payload_size,
                                     ehash,
                                     ehash_size);

        if (result == BASS_RC_SUCCESS) {
            dprintf(ERROR, "incorrectly got a successfull result when "
                    "checking payload hash using payload_type: %d\n", i);
            failed = true;
        }
    }

    return failed ? BASS_RC_FAILURE : BASS_RC_SUCCESS;
}
// (virtual)
bool AdlibSfxDecoder::reset()
{
    if (!AdlibDecoder::reset())
        return false;

    initialize_instrument();

    command_index_ = 0;
    remains_count_ = 0;

    reader_.set_position(get_header_size());

    return true;
}
Example #9
0
// -----------------------------------------------------------------------------
void BLeafNode::init_restore(		// load an exist node from disk to init
	BTree* btree,						// b-tree of this node
	int block)							// addr of disk for this node
{
	btree_ = btree;					// init <btree_>
	block_ = block;					// init <block_>
	dirty_ = false;					// init <dirty_>

									// get block length
	int b_length = btree_->file_->get_blocklength();

	// -------------------------------------------------------------------------
	//  Init <capacity_keys> and calc key size
	// -------------------------------------------------------------------------
	int key_size = get_key_size(b_length);
									// init <key>
	key_ = new float[capacity_keys_];
	for (int i = 0; i < capacity_keys_; i++) {
		key_[i] = MINREAL;
	}
									// calc header size
	int header_size = get_header_size();
									// calc entry size
	int entry_size = get_entry_size();	
									// init <capacity>
	capacity_ = (b_length - header_size - key_size) / entry_size;
	if (capacity_ < 100) {			// at least 100 entries
		printf("capacity = %d\n", capacity_);
		error("BLeafNode::init_store capacity too small.\n", true);
	}
	id_ = new int[capacity_];		// init <id>
	for (int i = 0; i < capacity_; i++) {
		id_[i] = -1;
	}

	// -------------------------------------------------------------------------
	//  Read the buffer <blk> to init <level_>, <num_entries_>, <left_sibling_>,
	//  <right_sibling_>, <num_keys_> <key_> and <id_>
	// -------------------------------------------------------------------------
	char* blk = new char[b_length];
	btree_->file_->read_block(blk, block);
	read_from_buffer(blk);

	delete[] blk; blk = NULL;
}
Example #10
0
// -----------------------------------------------------------------------------
void BLeafNode::init(				// init a new node, which not exist
	int level,							// level (depth) in b-tree
	BTree* btree)						// b-tree of this node
{
	btree_ = btree;					// init <btree_>
	level_ = (char) level;			// init <level_>

	num_entries_ = 0;				// init <num_entries_>
	num_keys_ = 0;					// init <num_keys_>
	left_sibling_ = -1;				// init <left_sibling_>
	right_sibling_ = -1;				// init <right_sibling_>
	dirty_ = true;					// init <dirty_>

									// get block length
	int b_length = btree_->file_->get_blocklength();

	// -------------------------------------------------------------------------
	//  Init <capacity_keys_> and calc key size
	// -------------------------------------------------------------------------
	int key_size = get_key_size(b_length);
									// init <key>
	key_ = new float[capacity_keys_];
	for (int i = 0; i < capacity_keys_; i++) {
		key_[i] = MINREAL;
	}
									// calc header size
	int header_size = get_header_size();
									// calc entry size
	int entry_size = get_entry_size();	
									// init <capacity>
	capacity_ = (b_length - header_size - key_size) / entry_size;
	if (capacity_ < 100) {			// at least 100 entries
		printf("capacity = %d\n", capacity_);
		error("BLeafNode::init capacity too small.\n", true);
	}
	id_ = new int[capacity_];		// init <id>
	for (int i = 0; i < capacity_; i++) {
		id_[i] = -1;
	}

	char* blk = new char[b_length];	// init <block>
	block_ = btree_->file_->append_block(blk);
	delete[] blk; blk = NULL;
}
void* xvfb_interface_getScreenshot( xvfb_interface* xvfb )
{
   // take a snapshot of the Xvfb output
   memcpy( xvfb->target_memory, xvfb->source_memmap, xvfb->input_size );

   // perform sanity checks on the snapshot to verify if it is corrupted (happens in rare cases)
   XWDFileHeader* header = ( XWDFileHeader* )xvfb->target_memory;

   unsigned int header_size = get_header_size( header );

   if( header_size != xvfb->header_size )
   {
      printf( "ERROR: Header size incorrect: (expected: %u bytes, actual: %u bytes )!  Is the input file corrupt?\n", xvfb->header_size, header_size );

      fflush( NULL );

      return NULL;
   }

   unsigned int width = readValue( &header->pixmap_width );
   unsigned int height = readValue( &header->pixmap_height );

   if ( width != xvfb->image_width )
   {
      printf( "ERROR: Image width in header is incorrect (corrupt input?)\n" );

      fflush( NULL );

      return NULL;
   }

   if ( height != xvfb->image_height )
   {
      printf( "ERROR: Image height in header is incorrect (corrupt input?)\n" );

      fflush( NULL );

      return NULL;
   }

   return xvfb->target_memory + header_size;
}
static int test_01_normal_payload_check(uint32_t data)
{
    bass_return_code result = BASS_RC_ERROR_UNKNOWN;
    bass_payload_type_t payload_type = BASS_PL_TYPE_X_LOADER;
    bass_hash_type_t hashtype = BASS_APP_SHA256_HASH;

    size_t ehash_size = SHA256_HASH_SIZE;
    uint8_t ehash[SHA256_HASH_SIZE];
    uint32_t payload_size = 0;
    uint32_t payload_offset = 0;

    (void)data;

    dprintf(INFO, "Starting test\n");
    memset(&ehash, 0, sizeof(ehash));

    result = get_ehash(signed_payload, signed_payload_size, payload_type,
                       ehash);
    if (result != BASS_RC_SUCCESS) {
        dprintf(ERROR, "failed to getting ehash\n");
        return result;
    }

    payload_offset = get_header_size(signed_payload);
    payload_size = get_payload_size(signed_payload);

    result = bass_check_payload_hash(&hashtype,
                                     &payload_type,
                                     (void *)(signed_payload + payload_offset),
                                     payload_size,
                                     ehash,
                                     ehash_size);

    if (result != BASS_RC_SUCCESS) {
        dprintf(ERROR, "failed checking payload hash\n");
        return result;
    }

    return result;
}
Example #13
0
// -----------------------------------------------------------------------------
void BIndexNode::init_restore(		// load an exist node from disk to init
	BTree* btree,						// b-tree of this node
	int block)							// addr of disk for this node
{
	btree_ = btree;					// init <btree_>
	block_ = block;					// init <block_>
	dirty_ = false;					// init <dirty_>

									// get block length
	int b_len = btree_->file_->get_blocklength();

									// init <capacity_>
	capacity_ = (b_len - get_header_size()) / get_entry_size();
	if (capacity_ < 50) {			// at least 50 entries
		printf("capacity = %d\n", capacity_);
		error("BIndexNode::init_restore capacity too small.\n", true);
	}

	key_ = new float[capacity_];	// init <key_>
	for (int i = 0; i < capacity_; i++) {
		key_[i] = MINREAL;
	}
	son_ = new int[capacity_];		// init <son_>
	for (int i = 0; i < capacity_; i++) {
		son_[i] = -1;
	}

	// -------------------------------------------------------------------------
	//  Read the buffer <blk> to init <level_>, <num_entries_>, <left_sibling_>,
	//  <right_sibling_>, <key_> and <son_>.
	// -------------------------------------------------------------------------
	char* blk = new char[b_len];
	btree_->file_->read_block(blk, block);
	read_from_buffer(blk);

	delete[] blk; blk = NULL;
}
static int test_03_modified_payload(uint32_t data)
{
    bool failed = false;
    bass_return_code result = BASS_RC_ERROR_UNKNOWN;
    bass_payload_type_t payload_type = BASS_PL_TYPE_X_LOADER;
    bass_hash_type_t hashtype = BASS_APP_SHA256_HASH;
    size_t ehash_size = SHA256_HASH_SIZE;
    uint8_t ehash[SHA256_HASH_SIZE];
    uint8_t *modified_payload = NULL;
    uint32_t payload_size = 0;
    uint32_t payload_offset = 0;

    (void)data;

    dprintf(INFO, "Starting test\n");
    memset(&ehash, 0, sizeof(ehash));

    result = get_ehash(signed_payload, signed_payload_size, payload_type,
                       ehash);
    if (result != BASS_RC_SUCCESS) {
        dprintf(ERROR, "failed to getting ehash\n");
        return result;
    }

    payload_offset = get_header_size(signed_payload);
    payload_size = get_payload_size(signed_payload);

    modified_payload = malloc(sizeof(uint8_t) * payload_size);
    if (!modified_payload) {
        return BASS_RC_FAILURE;
    }

    memcpy(modified_payload, signed_payload + payload_offset, payload_size);

    /*
     * Set the first 48 bytes to 0xFF (which is ok in in the payloads used in
     * this file, any number is good as long as it isn't greater than payload
     * size).
     * */
    memset(modified_payload, 0xFF, 48);

    result = bass_check_payload_hash(&hashtype,
                                 &payload_type,
                                 (void *)(modified_payload),
                                 payload_size,
                                 ehash,
                                 ehash_size);

    if (result == BASS_RC_SUCCESS) {
        dump_buffer("Expected hash", ehash, ehash_size);
        dump_buffer("Correct payload", signed_payload + payload_offset,
                    payload_size);
        dump_buffer("modified_payload", modified_payload, payload_size);

        dprintf(ERROR, "incorrectly got a successfull result when checking "
                "payload hash using modified payload\n");
        failed = true;
    }

    free(modified_payload);
    /*
     * Not that we expect this to fail internally, but to the function calling
     * this function it should be BASS_RC_SUCCESS test case went as expected.
     */
    return failed ? BASS_RC_FAILURE : BASS_RC_SUCCESS;
}
Example #15
0
/* alloc skb and copy dat to skb */
static int rx_hdlc_data_check(struct io_device *iod, char *buf, unsigned rest)
{
	struct header_data *hdr = &iod->h_data;
	struct sk_buff *skb = iod->skb_recv;
	int head_size = get_header_size(iod);
	int data_size = get_hdlc_size(iod, hdr->hdr) - head_size;
	int alloc_size = min(data_size, MAX_RXDATA_SIZE);
	int len;
	int done_len = 0;
	int rest_len = data_size - hdr->flag_len;
	struct sk_buff *skb_new;

	pr_debug("[MODEM_IF] head_size : %d, data_size : %d (%d)\n", head_size,
				data_size, __LINE__);

	/* first payload data - alloc skb */
	if (!skb) {
		switch (iod->format) {
		case IPC_RFS:
			alloc_size = min(data_size, (int)rest) + head_size;
			alloc_size = min(alloc_size, MAX_RXDATA_SIZE);
			skb = alloc_skb(alloc_size, GFP_ATOMIC);
			if (unlikely(!skb))
				return -ENOMEM;
			/* copy the RFS haeder to skb->data */
			memcpy(skb_put(skb, head_size), hdr->hdr, head_size);
			break;

		case IPC_MULTI_RAW:
			if (iod->net_typ == UMTS_NETWORK)
				skb = alloc_skb(alloc_size, GFP_ATOMIC);
			else
				skb = alloc_skb(alloc_size +
					sizeof(struct ethhdr), GFP_ATOMIC);
			if (unlikely(!skb))
				return -ENOMEM;

			if (iod->net_typ != UMTS_NETWORK)
				skb_reserve(skb, sizeof(struct ethhdr));
			break;

		default:
			skb = alloc_skb(alloc_size, GFP_ATOMIC);
			if (unlikely(!skb))
				return -ENOMEM;
			break;
		}
		iod->skb_recv = skb;
	}

	/* if recv packet size is larger than user space */
	while ((rest_len > MAX_RXDATA_SIZE) && (rest > 0)) {
		len = MAX_RXDATA_SIZE - skb->len;
		len = min(len, (int)rest);
		len = min(len, rest_len);
		memcpy(skb_put(skb, len), buf, len);
		buf += len;
		done_len += len;
		rest -= len;
		rest_len -= len;

		if (!rest_len)
			break;

		rx_iodev_skb(iod);
		iod->skb_recv =  NULL;

		alloc_size = min(rest_len, MAX_RXDATA_SIZE);
		skb_new = alloc_skb(alloc_size, GFP_ATOMIC);
		if (unlikely(!skb_new))
			return -ENOMEM;
		skb = iod->skb_recv = skb_new;
	}

	/* copy data to skb */
	len = min(rest, alloc_size - skb->len);
	len = min(len, rest_len);
	pr_debug("[MODEM_IF] rest : %d, alloc_size : %d , len : %d (%d)\n",
				rest, alloc_size, skb->len, __LINE__);

	memcpy(skb_put(skb, len), buf, len);
	done_len += len;
	hdr->flag_len += done_len;

	return done_len;
}
xvfb_interface* xvfb_interface_init( char* pathToFrameBuffer )
{
   xvfb_interface* interface = ( xvfb_interface* )malloc( sizeof( xvfb_interface ) );

   memset( interface, 0, sizeof( xvfb_interface ) );  // ++paranoia

   FILE* input_file = fopen( pathToFrameBuffer, "r" );

   if ( NULL == input_file )
   {
      free( interface );

      printf( "Could not open file: %s: %s\n", pathToFrameBuffer, strerror( errno ) );

      return NULL;
   }

   int input_fd = fileno( input_file );

   struct stat file_info;

   fstat( input_fd, &file_info );  // get the input_size of the Xvfb output file

   size_t file_size = file_info.st_size;

   // MAP_PRIVATE since we don't want to commit the changes back to the file and source_mem_map is cheap ;^}

   void* memory = mmap( NULL, file_size, PROT_READ, MAP_PRIVATE, input_fd, 0 );

   if ( ( ( void* )-1 ) == memory )
   {
      printf( "Could not mmap source xwd input file: %s\n", strerror( errno ) );

      fclose( input_file );
      free( interface );

      return NULL;
   }

   interface->source_memmap = memory;
   interface->xwd_file = input_file;
   interface->input_size = file_size;

   interface->target_memory = malloc( file_size );

   if ( NULL == interface->target_memory )
   {
      printf( "Failed to allocate %u bytes to duplicate virtual XWindows frame buffer\n", file_size );

      munmap( memory, file_size );
      fclose( input_file );
      free( interface );

      return NULL;
   }

   // record some values from the header, to allow us to check for corrupt frames later

   XWDFileHeader* header = ( XWDFileHeader* )interface->source_memmap;

   interface->header_size = get_header_size( header );

   interface->xwdfilehdr_size = readValue( &header->header_size );

   interface->xwdfile_version = readValue( &header->file_version );

   interface->image_width = readValue( &header->pixmap_width );
   interface->image_height = readValue( &header->pixmap_height );

   interface->bits_per_pixel = readValue( &header->bits_per_pixel );

   interface->ncolors_hdr = readValue( &header->ncolors );

   interface->colormap_size = sizeof( XWDColor ) * interface->ncolors_hdr;

   return interface;
}
Example #17
0
static uint8_t *avf_chunkise(struct chunkiser_ctx *s, int id, int *size, uint64_t *ts, void **attr, int *attr_size)
{
  AVPacket pkt;
  AVRational new_tb;
  int res;
  uint8_t **data;
  int header_size;
  int *frames;
  int *chunksize;
  int frames_max;
  uint8_t *frame_pos;
  uint8_t *ret;

  res = av_read_frame(s->s, &pkt);
  if (res < 0) {
    if (s->loop) {
      if (input_stream_rewind(s) >= 0) {
        *size = 0;
        *ts = s->last_ts;

        return NULL;
      }
    }
    fprintf(stderr, "AVPacket read failed: %d!!!\n", res);
    *size = -1;

    return NULL;
  }
  if ((s->streams & (1ULL << pkt.stream_index)) == 0) {
    *size = 0;
    *ts = s->last_ts;
    av_free_packet(&pkt);

    return NULL;
  }
  if (s->bsf[pkt.stream_index]) {
    AVPacket new_pkt= pkt;
    int res;

    res = av_bitstream_filter_filter(s->bsf[pkt.stream_index],
                                     s->s->streams[pkt.stream_index]->codec,
                                     NULL, &new_pkt.data, &new_pkt.size,
                                     pkt.data, pkt.size, pkt.flags & AV_PKT_FLAG_KEY);
    if(res > 0){
      av_free_packet(&pkt);
      new_pkt.destruct= av_destruct_packet;
    } else if(res < 0){
      fprintf(stderr, "%s failed for stream %d, codec %d: ",
                      s->bsf[pkt.stream_index]->filter->name,
                      pkt.stream_index,
                      s->s->streams[pkt.stream_index]->codec->codec_id);
      fprintf(stderr, "%d\n", res);
      *size = 0;

      return NULL;
    }
    pkt= new_pkt;
  }

  switch (s->s->streams[pkt.stream_index]->codec->codec_type) {
    case AVMEDIA_TYPE_VIDEO:
      frames = &s->v_frames;
      data = &s->v_data;
      chunksize = &s->v_size;
      frames_max = s->v_frames_max;
      break;
    case AVMEDIA_TYPE_AUDIO:
      frames = &s->a_frames;
      data = &s->a_data;
      chunksize = &s->a_size;
      frames_max = s->a_frames_max;
      break;
    default:
      /* Cannot arrive here... */
      fprintf(stderr, "Internal chunkiser error!\n");
      exit(-1);
  }

  header_size = get_header_size(s->s->streams[pkt.stream_index]);
  if (!*frames) {
    *chunksize = pkt.size + header_size + FRAME_HEADER_SIZE;
    *data = malloc(*chunksize);
    // we will fill the header at the end
  } else {
    *chunksize += pkt.size + FRAME_HEADER_SIZE;
    *data = realloc(*data, *chunksize);
  }

  if (*data == NULL) {
    *size = -1;
    av_free_packet(&pkt);

    return NULL;
  }

  new_tb = get_new_tb(s->s->streams[pkt.stream_index]);
  frame_pos = *data + *chunksize - pkt.size - FRAME_HEADER_SIZE;
  frame_header_fill(frame_pos, pkt.size, &pkt, s->s->streams[pkt.stream_index], new_tb, s->base_ts);
  memcpy(frame_pos + FRAME_HEADER_SIZE, pkt.data, pkt.size);
  (*frames)++;

  *ts = av_rescale_q(pkt.dts, s->s->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
  //dprintf("pkt.dts=%ld TS1=%lu" , pkt.dts, *ts);
  *ts += s->base_ts;
  //dprintf(" TS2=%lu\n",*ts);
  s->last_ts = *ts;
  av_free_packet(&pkt);

  if (*frames == frames_max) {
    header_fill(*data, s->s->streams[pkt.stream_index]);
    (*data)[header_size - 1] = *frames;
    ret = *data;
    *size = *chunksize;
    *frames = 0;
    *data = NULL;
    *chunksize = 0;
  } else {
    *size = 0;
    ret = NULL;
  }

  return ret;
}