ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune huggingface dataset:
ncp_del_file_or_subdir2(struct ncp_server *server,
			struct dentry *dentry)
{
	struct inode *inode = d_inode(dentry);
	__u8  volnum;
	__le32 dirent;

	if (!inode) {
		return 0xFF;	/* Any error */
	}
	volnum = NCP_FINFO(inode)->volNumber;
	dirent = NCP_FINFO(inode)->DosDirNum;
	return ncp_DeleteNSEntry(server, 1, volnum, dirent, NULL, NW_NS_DOS, cpu_to_le16(0x8006));
}
GF_Err svhd_box_write(GF_Box *s, GF_BitStream *bs)
{
	GF_Err e;
	GF_SphericalVideoInfoBox *ptr = (GF_SphericalVideoInfoBox *)s;

	e = gf_isom_full_box_write(s, bs);
	if (e) return e;
	if (ptr->string)
		gf_bs_write_data(bs, ptr->string, (u32) strlen(ptr->string));
	gf_bs_write_u8(bs, 0);
	return GF_OK;
}
static ssize_t ucma_resolve_route(struct ucma_file *file,
				  const char __user *inbuf,
				  int in_len, int out_len)
{
	struct rdma_ucm_resolve_route cmd;
	struct ucma_context *ctx;
	int ret;

	if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
		return -EFAULT;

	ctx = ucma_get_ctx_dev(file, cmd.id);
	if (IS_ERR(ctx))
		return PTR_ERR(ctx);

	ret = rdma_resolve_route(ctx->cm_id, cmd.timeout_ms);
	ucma_put_ctx(ctx);
	return ret;
}
int fieldNameSize() const {
        if (fieldNameSize_ == -1)
            fieldNameSize_ = (int)strlen(fieldName()) + 1;
        return fieldNameSize_;
    }
mptctl_event_process(MPT_ADAPTER *ioc, EventNotificationReply_t *pEvReply)
{
	u8 event;

	event = le32_to_cpu(pEvReply->Event) & 0xFF;

	dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "%s() called\n",
	    ioc->name, __func__));
	if(async_queue == NULL)
		return 1;

	/* Raise SIGIO for persistent events.
	 * TODO - this define is not in MPI spec yet,
	 * but they plan to set it to 0x21
	 */
	if (event == 0x21) {
		ioc->aen_event_read_flag=1;
		dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Raised SIGIO to application\n",
		    ioc->name));
		devtverboseprintk(ioc, printk(MYIOC_s_DEBUG_FMT
		    "Raised SIGIO to application\n", ioc->name));
		kill_fasync(&async_queue, SIGIO, POLL_IN);
		return 1;
	 }

	/* This flag is set after SIGIO was raised, and
	 * remains set until the application has read
	 * the event log via ioctl=MPTEVENTREPORT
	 */
	if(ioc->aen_event_read_flag)
		return 1;

	/* Signal only for the events that are
	 * requested for by the application
	 */
	if (ioc->events && (ioc->eventTypes & ( 1 << event))) {
		ioc->aen_event_read_flag=1;
		dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT
		    "Raised SIGIO to application\n", ioc->name));
		devtverboseprintk(ioc, printk(MYIOC_s_DEBUG_FMT
		    "Raised SIGIO to application\n", ioc->name));
		kill_fasync(&async_queue, SIGIO, POLL_IN);
	}
	return 1;
}
static enum extension_result handle_extension(const char *var,
					      const char *value,
					      const char *ext,
					      struct repository_format *data)
{
	if (!strcmp(ext, "noop-v1")) {
		return EXTENSION_OK;
	} else if (!strcmp(ext, "objectformat")) {
		int format;

		if (!value)
			return config_error_nonbool(var);
		format = hash_algo_by_name(value);
		if (format == GIT_HASH_UNKNOWN)
			return error("invalid value for 'extensions.objectformat'");
		data->hash_algo = format;
		return EXTENSION_OK;
	}
	return EXTENSION_UNKNOWN;
}
ecma_date_week_day (ecma_number_t time) /**< time value */
{
  JERRY_ASSERT (!ecma_number_is_nan (time));

  int32_t day = ecma_date_day_from_time (time);

  int week_day = (day + 4) % 7;

  return week_day >= 0 ? week_day : week_day + 7;
} /* ecma_date_week_day */
psf_close (SF_PRIVATE *psf)
{	uint32_t k ;
	int	error = 0 ;

	if (psf->codec_close)
	{	error = psf->codec_close (psf) ;
		/* To prevent it being called in psf->container_close(). */
		psf->codec_close = NULL ;
		} ;

	if (psf->container_close)
		error = psf->container_close (psf) ;

	error = psf_fclose (psf) ;
	psf_close_rsrc (psf) ;

	/* For an ISO C compliant implementation it is ok to free a NULL pointer. */
	free (psf->container_data) ;
	free (psf->codec_data) ;
	free (psf->interleave) ;
	free (psf->dither) ;
	free (psf->peak_info) ;
	free (psf->broadcast_16k) ;
	free (psf->loop_info) ;
	free (psf->instrument) ;
	free (psf->cues) ;
	free (psf->channel_map) ;
	free (psf->format_desc) ;
	free (psf->strings.storage) ;

	if (psf->wchunks.chunks)
		for (k = 0 ; k < psf->wchunks.used ; k++)
			free (psf->wchunks.chunks [k].data) ;
	free (psf->rchunks.chunks) ;
	free (psf->wchunks.chunks) ;
	free (psf->iterator) ;
	free (psf->cart_16k) ;

	memset (psf, 0, sizeof (SF_PRIVATE)) ;
	free (psf) ;

	return error ;
} /* psf_close */
void wc_ecc_del_point_h(ecc_point* p, void* heap)
{
   /* prevents free'ing null arguments */
   if (p != NULL) {
      mp_clear(p->x);
      mp_clear(p->y);
      mp_clear(p->z);
      XFREE(p, heap, DYNAMIC_TYPE_ECC);
   }
   (void)heap;
}
bson_iter_binary (const bson_iter_t *iter, /* IN */
                  bson_subtype_t *subtype, /* OUT */
                  uint32_t *binary_len,    /* OUT */
                  const uint8_t **binary)  /* OUT */
{
   bson_subtype_t backup;

   BSON_ASSERT (iter);
   BSON_ASSERT (!binary || binary_len);

   if (ITER_TYPE (iter) == BSON_TYPE_BINARY) {
      if (!subtype) {
         subtype = &backup;
      }

      *subtype = (bson_subtype_t) * (iter->raw + iter->d2);

      if (binary) {
         memcpy (binary_len, (iter->raw + iter->d1), sizeof (*binary_len));
         *binary_len = BSON_UINT32_FROM_LE (*binary_len);
         *binary = iter->raw + iter->d3;

         if (*subtype == BSON_SUBTYPE_BINARY_DEPRECATED) {
            *binary_len -= sizeof (int32_t);
            *binary += sizeof (int32_t);
         }
      }

      return;
   }

   if (binary) {
      *binary = NULL;
   }

   if (binary_len) {
      *binary_len = 0;
   }

   if (subtype) {
      *subtype = BSON_SUBTYPE_BINARY;
   }
}
int ssl_add_clienthello_use_srtp_ext(SSL *s, unsigned char *p, int *len, int maxlen)
	{
	int ct=0;
	int i;
	STACK_OF(SRTP_PROTECTION_PROFILE) *clnt=0;
	SRTP_PROTECTION_PROFILE *prof;
    
	clnt=SSL_get_srtp_profiles(s);    
	ct=sk_SRTP_PROTECTION_PROFILE_num(clnt); /* -1 if clnt == 0 */

	if(p)
		{
		if(ct==0)
			{
			SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_USE_SRTP_EXT,SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST);
			return 1;
			}

		if((2 + ct*2 + 1) > maxlen)
			{
			SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_USE_SRTP_EXT,SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG);
			return 1;
			}

                /* Add the length */
                s2n(ct * 2, p);
		for(i=0;i<ct;i++)
			{
			prof=sk_SRTP_PROTECTION_PROFILE_value(clnt,i);
			s2n(prof->id,p);
			}

                /* Add an empty use_mki value */
                *p++ = 0;
		}

	*len=2 + ct*2 + 1;
    
	return 0;
	}
static int snd_line6_impulse_period_get(struct snd_kcontrol *kcontrol,
					struct snd_ctl_elem_value *ucontrol)
{
	struct snd_line6_pcm *line6pcm = snd_kcontrol_chip(kcontrol);

	ucontrol->value.integer.value[0] = line6pcm->impulse_period;
	return 0;
}
This function decrypts the crypttext */
PHP_FUNCTION(mcrypt_module_get_supported_key_sizes)
{
	int i, count = 0;
	int *key_sizes;

	MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
	array_init(return_value);

	key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count);

	for (i = 0; i < count; i++) {
		add_index_long(return_value, i, key_sizes[i]);
	}
	mcrypt_free(key_sizes);
static void virtio_net_apply_guest_offloads(VirtIONet *n)
{
    qemu_set_offload(qemu_get_queue(n->nic)->peer,
            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_CSUM)),
            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO4)),
            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO6)),
            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_ECN)),
            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_UFO)));
}
void stop()
        {
#ifdef CROW_ENABLE_SSL
            if (ssl_used_)
            {
                if (ssl_server_) { ssl_server_->stop(); }
            }
            else
#endif
            {
                // TODO(EDev): Move these 6 lines to a method in http_server.
                std::vector<crow::websocket::connection*> websockets_to_close = websockets_;
                for (auto websocket : websockets_to_close)
                {
                    CROW_LOG_INFO << "Quitting Websocket: " << websocket;
                    websocket->close("Server Application Terminated");
                }
                if (server_) { server_->stop(); }
            }
        }
static void
Bfree(Bigint *v)
{
    if (v) {
        if (v->k > Kmax) {
            FREE(v);
            return;
        }
        ACQUIRE_DTOA_LOCK(0);
        v->next = freelist[v->k];
        freelist[v->k] = v;
        FREE_DTOA_LOCK(0);
    }
TEST_P(WasmTest, BadSignature) {
  Stats::IsolatedStoreImpl stats_store;
  Api::ApiPtr api = Api::createApiForTest(stats_store);
  Upstream::MockClusterManager cluster_manager;
  Event::DispatcherPtr dispatcher(api->allocateDispatcher());
  auto scope = Stats::ScopeSharedPtr(stats_store.createScope("wasm."));
  NiceMock<LocalInfo::MockLocalInfo> local_info;
  auto name = "";
  auto root_id = "";
  auto vm_id = "";
  auto vm_configuration = "";
  auto plugin = std::make_shared<Extensions::Common::Wasm::Plugin>(
      name, root_id, vm_id, envoy::api::v2::core::TrafficDirection::UNSPECIFIED, local_info,
      nullptr);
  auto wasm = std::make_unique<Extensions::Common::Wasm::Wasm>(
      absl::StrCat("envoy.wasm.runtime.", GetParam()), vm_id, vm_configuration, plugin, scope,
      cluster_manager, *dispatcher);
  EXPECT_NE(wasm, nullptr);
  const auto code = TestEnvironment::readFileToStringForTest(TestEnvironment::substitute(
      "{{ test_rundir }}/test/extensions/wasm/test_data/bad_signature_cpp.wasm"));
  EXPECT_FALSE(code.empty());
  EXPECT_THROW_WITH_MESSAGE(wasm->initialize(code, false),
                            Extensions::Common::Wasm::WasmVmException,
                            "Bad function signature for: proxy_onConfigure");
}
int luaD_growstack (lua_State *L, int n, int raiseerror) {
  int size = L->stacksize;
  int newsize = 2 * size;  /* tentative new size */
  if (unlikely(size > LUAI_MAXSTACK)) {  /* need more space after extra size? */
    if (raiseerror)
      luaD_throw(L, LUA_ERRERR);  /* error inside message handler */
    else return 0;
  }
  else {
    int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
    if (newsize > LUAI_MAXSTACK)  /* cannot cross the limit */
      newsize = LUAI_MAXSTACK;
    if (newsize < needed)  /* but must respect what was asked for */
      newsize = needed;
    if (unlikely(newsize > LUAI_MAXSTACK)) {  /* stack overflow? */
      /* add extra size to be able to handle the error message */
      luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
      if (raiseerror)
        luaG_runerror(L, "stack overflow");
      else return 0;
    }
  }  /* else no errors */
  return luaD_reallocstack(L, newsize, raiseerror);
}
__archive_write_close_filter(struct archive_write_filter *f)
{
	if (f->close != NULL)
		return (f->close)(f);
	if (f->next_filter != NULL)
		return (__archive_write_close_filter(f->next_filter));
	return (ARCHIVE_OK);
}
do_writekey (app_t app, ctrl_t ctrl,
             const char *keyid, unsigned int flags,
             gpg_error_t (*pincb)(void*, const char *, char **),
             void *pincb_arg,
             const unsigned char *keydata, size_t keydatalen)
{
  gpg_error_t err;
  int force = (flags & 1);
  const unsigned char *rsa_n = NULL;
  const unsigned char *rsa_e = NULL;
  size_t rsa_n_len, rsa_e_len;
  unsigned int nbits;

  (void)ctrl;
  (void)pincb;
  (void)pincb_arg;

  if (!strcmp (keyid, "$IFDAUTHKEY") && app->app_local->nks_version >= 3)
    ;
  else
    return gpg_error (GPG_ERR_INV_ID);

  if (!force && !do_readkey (app, keyid, NULL, NULL))
    return gpg_error (GPG_ERR_EEXIST);

  /* Parse the S-expression.  */
  err = get_rsa_pk_from_canon_sexp (keydata, keydatalen,
                                    &rsa_n, &rsa_n_len, &rsa_e, &rsa_e_len);
  if (err)
    goto leave;

  /* Check that the parameters match the requirements.  */
  nbits = app_help_count_bits (rsa_n, rsa_n_len);
  if (nbits != 1024)
    {
      log_error (_("RSA modulus missing or not of size %d bits\n"), 1024);
      err = gpg_error (GPG_ERR_BAD_PUBKEY);
      goto leave;
    }

  nbits = app_help_count_bits (rsa_e, rsa_e_len);
  if (nbits < 2 || nbits > 32)
    {
      log_error (_("RSA public exponent missing or larger than %d bits\n"),
                 32);
      err = gpg_error (GPG_ERR_BAD_PUBKEY);
      goto leave;
    }

/*   /\* Store them.  *\/ */
/*   err = verify_pin (app, 0, NULL, pincb, pincb_arg); */
/*   if (err) */
/*     goto leave; */

  /* Send the MSE:Store_Public_Key.  */
  err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
/*   mse = xtrymalloc (1000); */

/*   mse[0] = 0x80; /\* Algorithm reference.  *\/ */
/*   mse[1] = 1; */
/*   mse[2] = 0x17; */
/*   mse[3] = 0x84; /\* Private key reference.  *\/ */
/*   mse[4] = 1; */
/*   mse[5] = 0x77; */
/*   mse[6] = 0x7F; /\* Public key parameter.  *\/ */
/*   mse[7] = 0x49; */
/*   mse[8] = 0x81; */
/*   mse[9] = 3 + 0x80 + 2 + rsa_e_len; */
/*   mse[10] = 0x81; /\* RSA modulus of 128 byte.  *\/ */
/*   mse[11] = 0x81; */
/*   mse[12] = rsa_n_len; */
/*   memcpy (mse+12, rsa_n, rsa_n_len); */
/*   mse[10] = 0x82; /\* RSA public exponent of up to 4 bytes.  *\/ */
/*   mse[12] = rsa_e_len; */
/*   memcpy (mse+12, rsa_e, rsa_e_len); */
/*   err = iso7816_manage_security_env (app->slot, 0x81, 0xB6, */
/*                                      mse, sizeof mse); */

 leave:
  return err;
}
onig_get_callout_tag_start(regex_t* reg, int callout_num)
{
  CalloutListEntry* e = onig_reg_callout_list_at(reg, callout_num);
  CHECK_NULL_RETURN(e);
  return e->tag_start;
}
static int imap_open_mailbox_append (CONTEXT *ctx, int flags)
{
  IMAP_DATA *idata;
  char buf[LONG_STRING];
  char mailbox[LONG_STRING];
  IMAP_MBOX mx;
  int rc;

  if (imap_parse_path (ctx->path, &mx))
    return -1;

  /* in APPEND mode, we appear to hijack an existing IMAP connection -
   * ctx is brand new and mostly empty */

  if (!(idata = imap_conn_find (&(mx.account), 0)))
  {
    FREE (&mx.mbox);
    return -1;
  }

  ctx->data = idata;

  imap_fix_path (idata, mx.mbox, mailbox, sizeof (mailbox));
  if (!*mailbox)
    strfcpy (mailbox, "INBOX", sizeof (mailbox));
  FREE (&mx.mbox);

  if ((rc = imap_access (ctx->path)) == 0)
    return 0;

  if (rc == -1)
    return -1;

  snprintf (buf, sizeof (buf), _("Create %s?"), mailbox);
  if (option (OPTCONFIRMCREATE) && mutt_yesorno (buf, 1) < 1)
    return -1;

  if (imap_create_mailbox (idata, mailbox) < 0)
    return -1;

  return 0;
}
GF_Box *edts_box_new()
{
	ISOM_DECL_BOX_ALLOC(GF_EditBox, GF_ISOM_BOX_TYPE_EDTS);
	return (GF_Box *) tmp;
}
*/
static void io_uring_del_task_file(unsigned long index)
{
	struct io_uring_task *tctx = current->io_uring;
	struct io_tctx_node *node;

	if (!tctx)
		return;
	node = xa_erase(&tctx->xa, index);
	if (!node)
		return;

	WARN_ON_ONCE(current != node->task);
	WARN_ON_ONCE(list_empty(&node->ctx_node));

	mutex_lock(&node->ctx->uring_lock);
	list_del(&node->ctx_node);
	mutex_unlock(&node->ctx->uring_lock);

	if (tctx->last == node->ctx)
		tctx->last = NULL;
	kfree(node);
bool get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
  {
    *ltime= cached_time;
    return (null_value= false);
  }
bool css_has_online_children(struct cgroup_subsys_state *css)
{
	struct cgroup_subsys_state *child;
	bool ret = false;

	rcu_read_lock();
	css_for_each_child(child, css) {
		if (child->flags & CSS_ONLINE) {
			ret = true;
			break;
		}
	}
	rcu_read_unlock();
	return ret;
}
GF_Err gf_filter_new_finalize(GF_Filter *filter, const char *args, GF_FilterArgType arg_type)
{
	gf_filter_set_name(filter, NULL);

	gf_filter_parse_args(filter, args, arg_type, GF_FALSE);

	if (filter->freg->initialize) {
		GF_Err e;
		FSESS_CHECK_THREAD(filter)
		if (((arg_type==GF_FILTER_ARG_EXPLICIT_SOURCE) || (arg_type==GF_FILTER_ARG_EXPLICIT_SINK)) && !filter->orig_args) {
			filter->orig_args = (char *)args;
			e = filter->freg->initialize(filter);
			filter->orig_args = NULL;
		} else {
			e = filter->freg->initialize(filter);
		}
		if (e) return e;
	}
	if ((filter->freg->flags & GF_FS_REG_SCRIPT) && filter->freg->update_arg) {
		GF_Err e;
		gf_filter_parse_args(filter, args, arg_type, GF_TRUE);
		e = filter->freg->update_arg(filter, NULL, NULL);
		if (e) return e;
	}

	//flush all pending pid init requests
	if (filter->has_pending_pids) {
		filter->has_pending_pids=GF_FALSE;
		while (gf_fq_count(filter->pending_pids)) {
			GF_FilterPid *pid=gf_fq_pop(filter->pending_pids);
			gf_filter_pid_post_init_task(filter, pid);
		}
	}

#ifdef GPAC_HAS_QJS
	jsfs_on_filter_created(filter);
#endif
	if (filter->session->on_filter_create_destroy)
		filter->session->on_filter_create_destroy(filter->session->rt_udta, filter, GF_FALSE);
	return GF_OK;
}
BGD_DECLARE(int) gdImageColorAllocateAlpha (gdImagePtr im, int r, int g, int b, int a)
{
  int i;
  int ct = (-1);
  if (im->trueColor)
    {
      return gdTrueColorAlpha (r, g, b, a);
    }
  for (i = 0; (i < (im->colorsTotal)); i++)
    {
      if (im->open[i])
	{
	  ct = i;
	  break;
	}
    }
  if (ct == (-1))
    {
      ct = im->colorsTotal;
      if (ct == gdMaxColors)
	{
	  return -1;
	}
      im->colorsTotal++;
    }
  im->red[ct] = r;
  im->green[ct] = g;
  im->blue[ct] = b;
  im->alpha[ct] = a;
  im->open[ct] = 0;
  return ct;
}
sfe_codec_name (int format)
{
	switch (format & SF_FORMAT_SUBMASK)
	{	case SF_FORMAT_PCM_S8 : return "signed 8 bit PCM" ;
		case SF_FORMAT_PCM_16 : return "16 bit PCM" ;
		case SF_FORMAT_PCM_24 : return "24 bit PCM" ;
		case SF_FORMAT_PCM_32 : return "32 bit PCM" ;
		case SF_FORMAT_PCM_U8 : return "unsigned 8 bit PCM" ;
		case SF_FORMAT_FLOAT : return "32 bit float" ;
		case SF_FORMAT_DOUBLE : return "64 bit double" ;
		case SF_FORMAT_ULAW : return "u-law" ;
		case SF_FORMAT_ALAW : return "a-law" ;
		case SF_FORMAT_IMA_ADPCM : return "IMA ADPCM" ;
		case SF_FORMAT_MS_ADPCM : return "MS ADPCM" ;
		case SF_FORMAT_GSM610 : return "gsm610" ;
		case SF_FORMAT_VOX_ADPCM : return "Vox ADPCM" ;
		case SF_FORMAT_G721_32 : return "g721 32kbps" ;
		case SF_FORMAT_G723_24 : return "g723 24kbps" ;
		case SF_FORMAT_G723_40 : return "g723 40kbps" ;
		case SF_FORMAT_DWVW_12 : return "12 bit DWVW" ;
		case SF_FORMAT_DWVW_16 : return "16 bit DWVW" ;
		case SF_FORMAT_DWVW_24 : return "14 bit DWVW" ;
		case SF_FORMAT_DWVW_N : return "DWVW" ;
		case SF_FORMAT_DPCM_8 : return "8 bit DPCM" ;
		case SF_FORMAT_DPCM_16 : return "16 bit DPCM" ;
		case SF_FORMAT_VORBIS : return "Vorbis" ;
		case SF_FORMAT_ALAC_16 : return "16 bit ALAC" ;
		case SF_FORMAT_ALAC_20 : return "20 bit ALAC" ;
		case SF_FORMAT_ALAC_24 : return "24 bit ALAC" ;
		case SF_FORMAT_ALAC_32 : return "32 bit ALAC" ;
		default : break ;
		} ;
	return "unknown" ;
} /* sfe_codec_name */
void Http2Session::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) {
  HandleScope handle_scope(env()->isolate());
  Context::Scope context_scope(env()->context());
  Http2Scope h2scope(this);
  CHECK_NOT_NULL(stream_);
  Debug(this, "receiving %d bytes", nread);

  // Only pass data on if nread > 0
  if (nread <= 0) {
    free(buf_.base);
    if (nread < 0) {
      PassReadErrorToPreviousListener(nread);
    }
    return;
  }

  uv_buf_t buf = buf_;

  statistics_.data_received += nread;

  if (UNLIKELY(stream_buf_offset_ > 0)) {
    // This is a very unlikely case, and should only happen if the ReadStart()
    // call in OnStreamAfterWrite() immediately provides data. If that does
    // happen, we concatenate the data we received with the already-stored
    // pending input data, slicing off the already processed part.
    char* new_buf = Malloc(stream_buf_.len - stream_buf_offset_ + nread);
    memcpy(new_buf,
           stream_buf_.base + stream_buf_offset_,
           stream_buf_.len - stream_buf_offset_);
    memcpy(new_buf + stream_buf_.len - stream_buf_offset_,
           buf.base,
           nread);
    free(buf.base);
    nread = stream_buf_.len - stream_buf_offset_ + nread;
    buf = uv_buf_init(new_buf, nread);
    stream_buf_offset_ = 0;
    stream_buf_ab_.Reset();

    // We have now fully processed the stream_buf_ input chunk (by moving the
    // remaining part into buf, which will be accounted for below).
    DecrementCurrentSessionMemory(stream_buf_.len);
  }

  // Shrink to the actual amount of used data.
  buf.base = Realloc(buf.base, nread);
  IncrementCurrentSessionMemory(nread);

  // Remember the current buffer, so that OnDataChunkReceived knows the
  // offset of a DATA frame's data into the socket read buffer.
  stream_buf_ = uv_buf_init(buf.base, nread);

  // Verify that currently: There is memory allocated into which
  // the data has been read, and that memory buffer is at least as large
  // as the amount of data we have read, but we have not yet made an
  // ArrayBuffer out of it.
  CHECK_LE(static_cast<size_t>(nread), stream_buf_.len);

  Isolate* isolate = env()->isolate();

  // Store this so we can create an ArrayBuffer for read data from it.
  // DATA frames will be emitted as slices of that ArrayBuffer to avoid having
  // to copy memory.
  stream_buf_allocation_ = buf;

  ssize_t ret = ConsumeHTTP2Data();

  if (UNLIKELY(ret < 0)) {
    Debug(this, "fatal error receiving data: %d", ret);
    Local<Value> arg = Integer::New(isolate, ret);
    MakeCallback(env()->error_string(), 1, &arg);
    return;
  }

  MaybeStopReading();
}
gst_qtdemux_stream_send_initial_gap_segments (GstQTDemux * demux,
    QtDemuxStream * stream)
{
  gint i;

  /* Push any initial gap segments before proceeding to the
   * 'real' data */
  for (i = 0; i < stream->n_segments; i++) {
    gst_qtdemux_activate_segment (demux, stream, i, stream->time_position);

    if (QTSEGMENT_IS_EMPTY (&stream->segments[i])) {
      gst_qtdemux_send_gap_for_segment (demux, stream, i,
          stream->time_position);
    } else {
      /* Only support empty segment at the beginning followed by
       * one non-empty segment, this was checked when parsing the
       * edts atom, arriving here is unexpected */
      g_assert (i + 1 == stream->n_segments);
      break;
    }
  }
}
int main(int argc, char* argv[])
{
    if (argc != 6)
    {
        usage();
    }

    char* infilename = argv[1];
    char* outfilename = argv[2];
    int width = QUtil::string_to_int(argv[3]);
    int height = QUtil::string_to_int(argv[4]);
    char* colorspace = argv[5];
    J_COLOR_SPACE cs =
        ((strcmp(colorspace, "rgb") == 0) ? JCS_RGB :
         (strcmp(colorspace, "cmyk") == 0) ? JCS_CMYK :
         (strcmp(colorspace, "gray") == 0) ? JCS_GRAYSCALE :
         JCS_UNKNOWN);
    int components = 0;
    switch (cs)
    {
      case JCS_RGB:
        components = 3;
        break;
      case JCS_CMYK:
        components = 4;
        break;
      case JCS_GRAYSCALE:
        components = 1;
        break;
      default:
        usage();
        break;
    }

    FILE* infile = QUtil::safe_fopen(infilename, "rb");
    FILE* outfile = QUtil::safe_fopen(outfilename, "wb");
    Pl_StdioFile out("stdout", outfile);
    unsigned char buf[100];
    bool done = false;
    Callback callback;
    Pl_DCT dct("dct", &out, width, height, components, cs, &callback);
    while (! done)
    {
	size_t len = fread(buf, 1, sizeof(buf), infile);
	if (len <= 0)
	{
	    done = true;
	}
	else
	{
	    dct.write(buf, len);
	}
    }
    dct.finish();
    if (! callback.called)
    {
        std::cout << "Callback was not called" << std::endl;
    }
    fclose(infile);
    fclose(outfile);
    return 0;
}