bool PM_io_parser<PMDEC>::read_hedge(Halfedge_handle e)
{ // syntax: index { opposite, prev, next, vertex, face, mark }
  int n, eo, epr, ene, v, f; bool m;
  if ( !(in >> n) ||
       !check_sep("{") ||
       !(in >> eo) || !check_sep(",") ||
       !(in >> epr) || !check_sep(",") ||
       !(in >> ene) || !check_sep(",") ||
       !(in >> v) || !check_sep(",") ||
       !(in >> f) || !check_sep(",") ||
       !(in >> m) || !check_sep("}") )
    return false;
  CGAL_assertion_msg
     (eo >= 0 || (std::size_t) eo < en || epr >= 0 || (std::size_t) epr < en || ene >= 0 || (std::size_t) ene < en ||
      v >= 0 || (std::size_t) v < vn || f >= 0 || (std::size_t) f < fn ,
      "wrong index in read_hedge");

  // precond: objects exist!
  CGAL_assertion(EI[e->opposite()]);
  e->set_prev(Halfedge_of[epr]);
  e->set_next(Halfedge_of[ene]);
  e->set_vertex(Vertex_of[v]);
  e->set_face(Face_of[f]);
  mark(e) = m;
  return true;
}


unsigned int vp9_sub_pixel_variance ## W ## x ## H ## _c ( const uint8_t * src , int src_stride , int xoffset , int yoffset , const uint8_t * dst , int dst_stride , unsigned int * sse ) {
 uint16_t fdata3 [ ( H + 1 ) * W ] ;
 uint8_t temp2 [ H * W ] ;
 var_filter_block2d_bil_first_pass ( src , fdata3 , src_stride , 1 , H + 1 , W , BILINEAR_FILTERS_2TAP ( xoffset ) ) ;
 var_filter_block2d_bil_second_pass ( fdata3 , temp2 , W , W , H , W , BILINEAR_FILTERS_2TAP ( yoffset ) ) ;
 return vp9_variance ## W ## x ## H ## _c ( temp2 , W , dst , dst_stride , sse ) ;
 \ }
 # define SUBPIX_AVG_VAR ( W , H ) unsigned int vp9_sub_pixel_avg_variance ## W ## x ## H ## _c ( const uint8_t * src , int src_stride , int xoffset , int yoffset , const uint8_t * dst , int dst_stride , unsigned int * sse , const uint8_t * second_pred ) {
 uint16_t fdata3 [ ( H + 1 ) * W ] ;
 uint8_t temp2 [ H * W ] ;
 DECLARE_ALIGNED_ARRAY ( 16 , uint8_t , temp3 , H * W ) ;
 var_filter_block2d_bil_first_pass ( src , fdata3 , src_stride , 1 , H + 1 , W , BILINEAR_FILTERS_2TAP ( xoffset ) ) ;
 var_filter_block2d_bil_second_pass ( fdata3 , temp2 , W , W , H , W , BILINEAR_FILTERS_2TAP ( yoffset ) ) ;
 vp9_comp_avg_pred ( temp3 , second_pred , W , H , temp2 , W ) ;
 return vp9_variance ## W ## x ## H ## _c ( temp3 , W , dst , dst_stride , sse ) ;
 \ }
 void vp9_get16x16var_c ( const uint8_t * src_ptr , int source_stride , const uint8_t * ref_ptr , int ref_stride , unsigned int * sse , int * sum ) {
 variance ( src_ptr , source_stride , ref_ptr , ref_stride , 16 , 16 , sse , sum ) ;
 }
 void vp9_get8x8var_c ( const uint8_t * src_ptr , int source_stride , const uint8_t * ref_ptr , int ref_stride , unsigned int * sse , int * sum ) {
 variance ( src_ptr , source_stride , ref_ptr , ref_stride , 8 , 8 , sse , sum ) ;
 }
 unsigned int vp9_mse16x16_c ( const uint8_t * src , int src_stride , const uint8_t * ref , int ref_stride , unsigned int * sse ) {
 int sum ;
 variance ( src , src_stride , ref , ref_stride , 16 , 16 , sse , & sum ) ;
 return * sse ;
 }
 unsigned int vp9_mse16x8_c ( const uint8_t * src , int src_stride , const uint8_t * ref , int ref_stride , unsigned int * sse ) {
 int sum ;
 variance ( src , src_stride , ref , ref_stride , 16 , 8 , sse , & sum ) ;
 return * sse ;
 }
 unsigned int vp9_mse8x16_c ( const uint8_t * src , int src_stride , const uint8_t * ref , int ref_stride , unsigned int * sse ) {
 int sum ;
 variance ( src , src_stride , ref , ref_stride , 8 , 16 , sse , & sum ) ;
 return * sse ;
 }
 unsigned int vp9_mse8x8_c ( const uint8_t * src , int src_stride , const uint8_t * ref , int ref_stride , unsigned int * sse ) {
 int sum ;
 variance ( src , src_stride , ref , ref_stride , 8 , 8 , sse , & sum ) ;
 return * sse ;
 }
 VAR ( 4 , 4 ) SUBPIX_VAR ( 4 , 4 ) SUBPIX_AVG_VAR ( 4 , 4 ) VAR ( 4 , 8 ) SUBPIX_VAR ( 4 , 8 ) SUBPIX_AVG_VAR ( 4 , 8 ) VAR ( 8 , 4 ) SUBPIX_VAR ( 8 , 4 ) SUBPIX_AVG_VAR ( 8 , 4 ) VAR ( 8 , 8 ) SUBPIX_VAR ( 8 , 8 ) SUBPIX_AVG_VAR ( 8 , 8 ) VAR ( 8 , 16 ) SUBPIX_VAR ( 8 , 16 ) SUBPIX_AVG_VAR ( 8 , 16 ) VAR ( 16 , 8 ) SUBPIX_VAR ( 16 , 8 ) SUBPIX_AVG_VAR ( 16 , 8 ) VAR ( 16 , 16 ) SUBPIX_VAR ( 16 , 16 ) SUBPIX_AVG_VAR ( 16 , 16 ) VAR ( 16 , 32 ) SUBPIX_VAR ( 16 , 32 ) SUBPIX_AVG_VAR ( 16 , 32 ) VAR ( 32 , 16 ) SUBPIX_VAR ( 32 , 16 )


static int parse_read_interval(const char *interval_spec, ReadInterval *interval) { int ret = 0; char *next, *p, *spec = av_strdup(interval_spec); if (!spec) return AVERROR(ENOMEM); if (!*spec) { av_log(NULL, AV_LOG_ERROR, "Invalid empty interval specification\n"); ret = AVERROR(EINVAL); goto end; } p = spec; next = strchr(spec, '%'); if (next) *next++ = 0; /* parse first part */ if (*p) { interval->has_start = 1; if (*p == '+') { interval->start_is_offset = 1; p++; } else { interval->start_is_offset = 0; } ret = av_parse_time(&interval->start, p, 1); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Invalid interval start specification '%s'\n", p); goto end; } } else { interval->has_start = 0; } /* parse second part */ p = next; if (p && *p) { int64_t us; interval->has_end = 1; if (*p == '+') { interval->end_is_offset = 1; p++; } else { interval->end_is_offset = 0; } if (interval->end_is_offset && *p == '#') { long long int lli; char *tail; interval->duration_frames = 1; p++; lli = strtoll(p, &tail, 10); if (*tail || lli < 0) { av_log(NULL, AV_LOG_ERROR, "Invalid or negative value '%s' for duration number of frames\n", p); goto end; } interval->end = lli; } else { ret = av_parse_time(&us, p, 1); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Invalid interval end/duration specification '%s'\n", p); goto end; } interval->end = us; } } else { interval->has_end = 0; } end: av_free(spec); return ret; }


  void Compute(OpKernelContext *ctx) override {
    // (0) validations
    const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape,
        *b_shape, *thresh_t;

    OP_REQUIRES_OK(ctx, ctx->input("a_indices", &a_indices));
    OP_REQUIRES_OK(ctx, ctx->input("b_indices", &b_indices));
    OP_REQUIRES(ctx,
                TensorShapeUtils::IsMatrix(a_indices->shape()) &&
                    TensorShapeUtils::IsMatrix(b_indices->shape()),
                errors::InvalidArgument(
                    "Input indices should be matrices but received shapes: ",
                    a_indices->shape().DebugString(), " and ",
                    b_indices->shape().DebugString()));
    const int64 a_nnz = a_indices->dim_size(0);
    const int64 b_nnz = b_indices->dim_size(0);

    OP_REQUIRES_OK(ctx, ctx->input("a_values", &a_values_t));
    OP_REQUIRES_OK(ctx, ctx->input("b_values", &b_values_t));

    OP_REQUIRES(ctx,
                TensorShapeUtils::IsVector(a_values_t->shape()) &&
                    TensorShapeUtils::IsVector(b_values_t->shape()),
                errors::InvalidArgument(
                    "Input values should be vectors but received shapes: ",
                    a_values_t->shape().DebugString(), " and ",
                    b_values_t->shape().DebugString()));
    auto a_values = ctx->input(1).vec<T>();
    auto b_values = ctx->input(4).vec<T>();
    OP_REQUIRES(
        ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,
        errors::InvalidArgument("Expected ", a_nnz, " and ", b_nnz,
                                " non-empty input values, got ",
                                a_values.size(), " and ", b_values.size()));

    OP_REQUIRES_OK(ctx, ctx->input("a_shape", &a_shape));
    OP_REQUIRES_OK(ctx, ctx->input("b_shape", &b_shape));
    OP_REQUIRES(ctx,
                TensorShapeUtils::IsVector(a_shape->shape()) &&
                    TensorShapeUtils::IsVector(b_shape->shape()),
                errors::InvalidArgument(
                    "Input shapes should be a vector but received shapes ",
                    a_shape->shape().DebugString(), " and ",
                    b_shape->shape().DebugString()));
    OP_REQUIRES(
        ctx, a_shape->IsSameSize(*b_shape),
        errors::InvalidArgument(
            "Operands do not have the same ranks; got shapes: ",
            a_shape->SummarizeValue(10), " and ", b_shape->SummarizeValue(10)));
    const auto a_shape_flat = a_shape->flat<int64>();
    const auto b_shape_flat = b_shape->flat<int64>();
    for (int i = 0; i < a_shape->NumElements(); ++i) {
      OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i),
                  errors::InvalidArgument(
                      "Operands' shapes do not match: got ", a_shape_flat(i),
                      " and ", b_shape_flat(i), " for dimension ", i));
    }

    OP_REQUIRES_OK(ctx, ctx->input("thresh", &thresh_t));
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()),
                errors::InvalidArgument(
                    "The magnitude threshold must be a scalar: got shape ",
                    thresh_t->shape().DebugString()));
    // std::abs() so that it works for complex{64,128} values as well
    const Treal thresh = thresh_t->scalar<Treal>()();

    // (1) do a pass over inputs, and append values and indices to vectors
    auto a_indices_mat = a_indices->matrix<int64>();
    auto b_indices_mat = b_indices->matrix<int64>();
    std::vector<std::pair<bool, int64>> entries_to_copy;  // from_a?, idx
    entries_to_copy.reserve(a_nnz + b_nnz);
    std::vector<T> out_values;
    const int num_dims = a_shape->dim_size(0);

    // The input and output sparse tensors are assumed to be ordered along
    // increasing dimension number.
    int64 i = 0, j = 0;
    T s;
    while (i < a_nnz && j < b_nnz) {
      switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j,
                                         num_dims)) {
        case -1:
          entries_to_copy.emplace_back(true, i);
          out_values.push_back(a_values(i));
          ++i;
          break;
        case 0:
          s = a_values(i) + b_values(j);
          if (thresh <= std::abs(s)) {
            entries_to_copy.emplace_back(true, i);
            out_values.push_back(s);
          }
          ++i;
          ++j;
          break;
        case 1:
          entries_to_copy.emplace_back(false, j);
          out_values.push_back(b_values(j));
          ++j;
          break;
      }
    }

#define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A)     \
  while (IDX < A_OR_B##_nnz) {                  \
    entries_to_copy.emplace_back(IS_A, IDX);    \
    out_values.push_back(A_OR_B##_values(IDX)); \
    ++IDX;                                      \
  }

    // at most one of these calls appends new values
    HANDLE_LEFTOVERS(a, i, true);
    HANDLE_LEFTOVERS(b, j, false);
#undef HANDLE_LEFTOVERS

    // (2) allocate and fill output tensors
    const int64 sum_nnz = out_values.size();
    Tensor *out_indices_t, *out_values_t;
    OP_REQUIRES_OK(ctx,
                   ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),
                                        &out_indices_t));
    OP_REQUIRES_OK(
        ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t));
    auto out_indices_mat = out_indices_t->matrix<int64>();
    auto out_values_flat = out_values_t->vec<T>();

    for (i = 0; i < sum_nnz; ++i) {
      const bool from_a = entries_to_copy[i].first;
      const int64 idx = entries_to_copy[i].second;
      out_indices_mat.chip<0>(i) =
          from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);
    }
    if (sum_nnz > 0) {
      std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0));
    }
    ctx->set_output(2, *a_shape);
  }


static inline void openOptimized(sqlite3*& db) {
  sqlite3_open(":memory:", &db);

  std::string settings;
  for (const auto& setting : kMemoryDBSettings) {
    settings += "PRAGMA " + setting.first + "=" + setting.second + "; ";
  }
  sqlite3_exec(db, settings.c_str(), nullptr, nullptr, nullptr);

  // Register function extensions.
  registerMathExtensions(db);
#if !defined(FREEBSD)
  registerStringExtensions(db);
#endif
#if !defined(SKIP_CARVER)
  registerOperationExtensions(db);
#endif
  registerFilesystemExtensions(db);
  registerHashingExtensions(db);
  registerEncodingExtensions(db);
}


CreateSchemaCommand(CreateSchemaStmt *stmt, const char *queryString,
					int stmt_location, int stmt_len)
{
	const char *schemaName = stmt->schemaname;
	Oid			namespaceId;
	OverrideSearchPath *overridePath;
	List	   *parsetree_list;
	ListCell   *parsetree_item;
	Oid			owner_uid;
	Oid			saved_uid;
	int			save_sec_context;
	AclResult	aclresult;
	ObjectAddress address;

	GetUserIdAndSecContext(&saved_uid, &save_sec_context);

	/*
	 * Who is supposed to own the new schema?
	 */
	if (stmt->authrole)
		owner_uid = get_rolespec_oid(stmt->authrole, false);
	else
		owner_uid = saved_uid;

	/* fill schema name with the user name if not specified */
	if (!schemaName)
	{
		HeapTuple	tuple;

		tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(owner_uid));
		if (!HeapTupleIsValid(tuple))
			elog(ERROR, "cache lookup failed for role %u", owner_uid);
		schemaName =
			pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
		ReleaseSysCache(tuple);
	}

	/*
	 * To create a schema, must have schema-create privilege on the current
	 * database and must be able to become the target role (this does not
	 * imply that the target role itself must have create-schema privilege).
	 * The latter provision guards against "giveaway" attacks.  Note that a
	 * superuser will always have both of these privileges a fortiori.
	 */
	aclresult = pg_database_aclcheck(MyDatabaseId, saved_uid, ACL_CREATE);
	if (aclresult != ACLCHECK_OK)
		aclcheck_error(aclresult, OBJECT_DATABASE,
					   get_database_name(MyDatabaseId));

	check_is_member_of_role(saved_uid, owner_uid);

	/* Additional check to protect reserved schema names */
	if (!allowSystemTableMods && IsReservedName(schemaName))
		ereport(ERROR,
				(errcode(ERRCODE_RESERVED_NAME),
				 errmsg("unacceptable schema name \"%s\"", schemaName),
				 errdetail("The prefix \"pg_\" is reserved for system schemas.")));

	/*
	 * If if_not_exists was given and the schema already exists, bail out.
	 * (Note: we needn't check this when not if_not_exists, because
	 * NamespaceCreate will complain anyway.)  We could do this before making
	 * the permissions checks, but since CREATE TABLE IF NOT EXISTS makes its
	 * creation-permission check first, we do likewise.
	 */
	if (stmt->if_not_exists &&
		SearchSysCacheExists1(NAMESPACENAME, PointerGetDatum(schemaName)))
	{
		ereport(NOTICE,
				(errcode(ERRCODE_DUPLICATE_SCHEMA),
				 errmsg("schema \"%s\" already exists, skipping",
						schemaName)));
		return InvalidOid;
	}

	/*
	 * If the requested authorization is different from the current user,
	 * temporarily set the current user so that the object(s) will be created
	 * with the correct ownership.
	 *
	 * (The setting will be restored at the end of this routine, or in case of
	 * error, transaction abort will clean things up.)
	 */
	if (saved_uid != owner_uid)
		SetUserIdAndSecContext(owner_uid,
							   save_sec_context | SECURITY_LOCAL_USERID_CHANGE);

	/* Create the schema's namespace */
	namespaceId = NamespaceCreate(schemaName, owner_uid, false);

	/* Advance cmd counter to make the namespace visible */
	CommandCounterIncrement();

	/*
	 * Temporarily make the new namespace be the front of the search path, as
	 * well as the default creation target namespace.  This will be undone at
	 * the end of this routine, or upon error.
	 */
	overridePath = GetOverrideSearchPath(CurrentMemoryContext);
	overridePath->schemas = lcons_oid(namespaceId, overridePath->schemas);
	/* XXX should we clear overridePath->useTemp? */
	PushOverrideSearchPath(overridePath);

	/*
	 * Report the new schema to possibly interested event triggers.  Note we
	 * must do this here and not in ProcessUtilitySlow because otherwise the
	 * objects created below are reported before the schema, which would be
	 * wrong.
	 */
	ObjectAddressSet(address, NamespaceRelationId, namespaceId);
	EventTriggerCollectSimpleCommand(address, InvalidObjectAddress,
									 (Node *) stmt);

	/*
	 * Examine the list of commands embedded in the CREATE SCHEMA command, and
	 * reorganize them into a sequentially executable order with no forward
	 * references.  Note that the result is still a list of raw parsetrees ---
	 * we cannot, in general, run parse analysis on one statement until we
	 * have actually executed the prior ones.
	 */
	parsetree_list = transformCreateSchemaStmt(stmt);

	/*
	 * Execute each command contained in the CREATE SCHEMA.  Since the grammar
	 * allows only utility commands in CREATE SCHEMA, there is no need to pass
	 * them through parse_analyze() or the rewriter; we can just hand them
	 * straight to ProcessUtility.
	 */
	foreach(parsetree_item, parsetree_list)
	{
		Node	   *stmt = (Node *) lfirst(parsetree_item);
		PlannedStmt *wrapper;

		/* need to make a wrapper PlannedStmt */
		wrapper = makeNode(PlannedStmt);
		wrapper->commandType = CMD_UTILITY;
		wrapper->canSetTag = false;
		wrapper->utilityStmt = stmt;
		wrapper->stmt_location = stmt_location;
		wrapper->stmt_len = stmt_len;

		/* do this step */
		ProcessUtility(wrapper,
					   queryString,
					   PROCESS_UTILITY_SUBCOMMAND,
					   NULL,
					   NULL,
					   None_Receiver,
					   NULL);

		/* make sure later steps can see the object created here */
		CommandCounterIncrement();
	}

	/* Reset search path to normal state */
	PopOverrideSearchPath();

	/* Reset current user and security context */
	SetUserIdAndSecContext(saved_uid, save_sec_context);

	return namespaceId;
}


static int decode_tsw1(GetByteContext *gb, uint8_t *frame, int width, int height) { const uint8_t *frame_start = frame; const uint8_t *frame_end = frame + width * height; int mask = 0x10000, bitbuf = 0; int v, count, segments; unsigned offset; segments = bytestream2_get_le32(gb); offset = bytestream2_get_le32(gb); if (segments == 0 && offset == frame_end - frame) return 0; // skip frame if (frame_end - frame <= offset) return AVERROR_INVALIDDATA; frame += offset; while (segments--) { if (bytestream2_get_bytes_left(gb) < 2) return AVERROR_INVALIDDATA; if (mask == 0x10000) { bitbuf = bytestream2_get_le16u(gb); mask = 1; } if (frame_end - frame < 2) return AVERROR_INVALIDDATA; if (bitbuf & mask) { v = bytestream2_get_le16(gb); offset = (v & 0x1FFF) << 1; count = ((v >> 13) + 2) << 1; if (frame - frame_start < offset || frame_end - frame < count) return AVERROR_INVALIDDATA; av_memcpy_backptr(frame, offset, count); frame += count; } else { *frame++ = bytestream2_get_byte(gb); *frame++ = bytestream2_get_byte(gb); } mask <<= 1; } return 0; }


const char * TSConfigDirGet ( void ) {
 static std : : string sysconfdir = RecConfigReadConfigDir ( ) ;
 return sysconfdir . c_str ( ) ;
 }


static void usb_ehci_pci_finalize ( Object * obj ) {
 EHCIPCIState * i = PCI_EHCI ( obj ) ;
 EHCIState * s = & i -> ehci ;
 usb_ehci_finalize ( s ) ;
 }


void ff_er_add_slice(MpegEncContext *s, int startx, int starty, int endx, int endy, int status){ const int start_i= clip(startx + starty * s->mb_width , 0, s->mb_num-1); const int end_i = clip(endx + endy * s->mb_width , 0, s->mb_num); const int start_xy= s->mb_index2xy[start_i]; const int end_xy = s->mb_index2xy[end_i]; int mask= -1; if(!s->error_resilience) return; mask &= ~VP_START; if(status & (AC_ERROR|AC_END)){ mask &= ~(AC_ERROR|AC_END); s->error_count -= end_i - start_i + 1; if(status & (DC_ERROR|DC_END)){ mask &= ~(DC_ERROR|DC_END); s->error_count -= end_i - start_i + 1; if(status & (MV_ERROR|MV_END)){ mask &= ~(MV_ERROR|MV_END); s->error_count -= end_i - start_i + 1; if(status & (AC_ERROR|DC_ERROR|MV_ERROR)) s->error_count= INT_MAX; if(mask == ~0x7F){ memset(&s->error_status_table[start_xy], 0, (end_xy - start_xy) * sizeof(uint8_t)); }else{ int i; for(i=start_xy; i<end_xy; i++){ s->error_status_table[ i ] &= mask; if(end_i == s->mb_num) s->error_count= INT_MAX; else{ s->error_status_table[end_xy] &= mask; s->error_status_table[end_xy] |= status; s->error_status_table[start_xy] |= VP_START; if(start_xy > 0 && s->avctx->thread_count <= 1 && s->avctx->skip_top*s->mb_width < start_i){ int prev_status= s->error_status_table[ s->mb_index2xy[start_i - 1] ]; prev_status &= ~ VP_START; if(prev_status != (MV_END|DC_END|AC_END)) s->error_count= INT_MAX;


void fz_set_default_output_intent ( fz_context * ctx , fz_default_colorspaces * default_cs , fz_colorspace * cs ) {
 fz_drop_colorspace ( ctx , default_cs -> oi ) ;
 default_cs -> oi = fz_keep_colorspace ( ctx , cs ) ;
 switch ( cs -> n ) {
 case 1 : if ( default_cs -> gray == fz_device_gray ( ctx ) ) {
 fz_drop_colorspace ( ctx , default_cs -> gray ) ;
 default_cs -> gray = fz_keep_colorspace ( ctx , cs ) ;
 }
 break ;
 case 3 : if ( default_cs -> rgb == fz_device_rgb ( ctx ) ) {
 fz_drop_colorspace ( ctx , default_cs -> rgb ) ;
 default_cs -> rgb = fz_keep_colorspace ( ctx , cs ) ;
 }
 break ;
 case 4 : if ( default_cs -> cmyk == fz_device_cmyk ( ctx ) ) {
 fz_drop_colorspace ( ctx , default_cs -> cmyk ) ;
 default_cs -> cmyk = fz_keep_colorspace ( ctx , cs ) ;
 }
 break ;
 }
 }


static void usage(void)
{
    fprintf(stderr, "Usage: %s [OPTIONS]\n", progname);
    fprintf(stderr, "A tool to reconstruct mailboxes.\n");
    fprintf(stderr, "\n");

    fprintf(stderr, "-C <config-file>   use <config-file> instead of config from imapd.conf");
    fprintf(stderr, "-p <partition>     use this indicated partition for search\n");
    fprintf(stderr, "-d                 check mailboxes database and insert missing entries\n");
    fprintf(stderr, "-x                 do not import metadata, create new\n");
    fprintf(stderr, "-r                 recursively reconstruct\n");
    fprintf(stderr, "-f                 examine filesystem underneath the mailbox\n");
    fprintf(stderr, "-s                 don't stat underlying files\n");
    fprintf(stderr, "-q                 run quietly\n");
    fprintf(stderr, "-n                 do not make changes\n");
    fprintf(stderr, "-G                 force re-parsing (checks GUID correctness)\n");
    fprintf(stderr, "-R                 perform UID upgrade operation on GUID mismatched files\n");
    fprintf(stderr, "-U                 use this if there are corrupt message files in spool\n");
    fprintf(stderr, "                   WARNING: this option deletes corrupted message files permanently\n");
    fprintf(stderr, "-o                 ignore odd files in mailbox disk directories\n");
    fprintf(stderr, "-O                 delete odd files (unlike -o)\n");
    fprintf(stderr, "-M                 prefer mailboxes.db over cyrus.header\n");
    fprintf(stderr, "-V <version>       Change the cyrus.index minor version to the version specified\n");
    fprintf(stderr, "-u                 give usernames instead of mailbox prefixes\n");

    fprintf(stderr, "\n");

    exit(EX_USAGE);
}


IN_PROC_BROWSER_TEST_F ( ProfileBrowserTest , URLFetcherUsingMainContextDuringIncognitoTeardown ) {
 Browser * incognito_browser = OpenURLOffTheRecord ( browser ( ) -> profile ( ) , GURL ( "about:blank" ) ) ;
 RunURLFetcherActiveDuringIncognitoTeardownTest ( incognito_browser , incognito_browser -> profile ( ) -> GetRequestContext ( ) ) ;
 }


  void Compute(OpKernelContext* ctx) override {
    const Tensor* x_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->input("x", &x_tensor));

    const Tensor* cs_prev_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->input("cs_prev", &cs_prev_tensor));

    const Tensor* h_prev_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->input("h_prev", &h_prev_tensor));

    const Tensor* w_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->input("w", &w_tensor));

    const Tensor* wci_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->input("wci", &wci_tensor));

    const Tensor* wcf_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->input("wcf", &wcf_tensor));

    const Tensor* wco_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->input("wco", &wco_tensor));

    const Tensor* b_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->input("b", &b_tensor));

    const int64_t batch_size = x_tensor->dim_size(0);
    const int64_t input_size = x_tensor->dim_size(1);
    const int64_t cell_size = cs_prev_tensor->dim_size(1);

    // Sanity checks for our input shapes.
    OP_REQUIRES(ctx, cs_prev_tensor->dim_size(0) == batch_size,
                errors::InvalidArgument("cs_prev.dims(0) != batch_size: ",
                                        cs_prev_tensor->dim_size(0), " vs. ",
                                        batch_size));
    OP_REQUIRES(ctx, cs_prev_tensor->dim_size(1) == cell_size,
                errors::InvalidArgument("cs_prev.dims(1) != cell_size: ",
                                        cs_prev_tensor->dim_size(1), " vs. ",
                                        cell_size));

    OP_REQUIRES(ctx, h_prev_tensor->dim_size(0) == batch_size,
                errors::InvalidArgument("h_prev.dims(0) != batch_size: ",
                                        h_prev_tensor->dim_size(0), " vs. ",
                                        batch_size));
    OP_REQUIRES(ctx, h_prev_tensor->dim_size(1) == cell_size,
                errors::InvalidArgument(
                    "h_prev.dims(1) != cell_size: ", h_prev_tensor->dim_size(1),
                    " vs. ", cell_size));

    OP_REQUIRES(ctx, w_tensor->dim_size(0) == input_size + cell_size,
                errors::InvalidArgument(
                    "w.dim_size(0) != input_size + cell_size: ",
                    w_tensor->dim_size(0), " vs. ", input_size + cell_size));
    OP_REQUIRES(ctx, w_tensor->dim_size(1) == cell_size * 4,
                errors::InvalidArgument(
                    "w.dim_size(1) != cell_size * 4: ", w_tensor->dim_size(1),
                    " vs. ", cell_size * 4));

    OP_REQUIRES(ctx, b_tensor->dim_size(0) == cell_size * 4,
                errors::InvalidArgument(
                    "b.dim_size(0) != cell_size * 4: ", b_tensor->dim_size(0),
                    " vs. ", cell_size * 4));

    // Allocate our output tensors.
    Tensor* i_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(
                            {"h_prev"}, "i",
                            TensorShape({batch_size, cell_size}), &i_tensor));

    Tensor* cs_tensor = nullptr;
    OP_REQUIRES_OK(
        ctx, ctx->allocate_output("cs", TensorShape({batch_size, cell_size}),
                                  &cs_tensor));

    Tensor* f_tensor = nullptr;
    OP_REQUIRES_OK(
        ctx, ctx->allocate_output("f", TensorShape({batch_size, cell_size}),
                                  &f_tensor));

    Tensor* o_tensor = nullptr;
    OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(
                            {"cs_prev"}, "o",
                            TensorShape({batch_size, cell_size}), &o_tensor));

    Tensor* ci_tensor = nullptr;
    OP_REQUIRES_OK(
        ctx, ctx->allocate_output("ci", TensorShape({batch_size, cell_size}),
                                  &ci_tensor));

    Tensor* co_tensor = nullptr;
    OP_REQUIRES_OK(
        ctx, ctx->allocate_output("co", TensorShape({batch_size, cell_size}),
                                  &co_tensor));

    Tensor* h_tensor = nullptr;
    OP_REQUIRES_OK(
        ctx, ctx->allocate_output("h", TensorShape({batch_size, cell_size}),
                                  &h_tensor));

    // Allocate our temp tensors.
    Tensor xh_tensor;
    OP_REQUIRES_OK(ctx, ctx->allocate_temp(
                            DataTypeToEnum<T>::v(),
                            TensorShape({batch_size, input_size + cell_size}),
                            &xh_tensor));

    Tensor gates_tensor;
    OP_REQUIRES_OK(ctx,
                   ctx->allocate_temp(DataTypeToEnum<T>::v(),
                                      TensorShape({batch_size, cell_size * 4}),
                                      &gates_tensor));

    const Device& device = ctx->eigen_device<Device>();

    functor::LSTMBlockCellFprop<Device, T, USE_CUBLAS, gate_layout>(
        batch_size, input_size, cell_size)(
        ctx, device, forget_bias_, cell_clip_, use_peephole_,
        x_tensor->matrix<T>(), cs_prev_tensor->matrix<T>(),
        h_prev_tensor->matrix<T>(), w_tensor->matrix<T>(), wci_tensor->vec<T>(),
        wcf_tensor->vec<T>(), wco_tensor->vec<T>(), b_tensor->vec<T>(),
        xh_tensor.matrix<T>(), i_tensor->matrix<T>(), cs_tensor->matrix<T>(),
        f_tensor->matrix<T>(), o_tensor->matrix<T>(), ci_tensor->matrix<T>(),
        co_tensor->matrix<T>(), gates_tensor.matrix<T>(),
        h_tensor->matrix<T>());
  }


static int sub2video_prepare(InputStream *ist) { AVFormatContext *avf = input_files[ist->file_index]->ctx; int i, w, h; /* Compute the size of the canvas for the subtitles stream. If the subtitles codec has set a size, use it. Otherwise use the maximum dimensions of the video streams in the same file. */ w = ist->dec_ctx->width; h = ist->dec_ctx->height; if (!(w && h)) { for (i = 0; i < avf->nb_streams; i++) { if (avf->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { w = FFMAX(w, avf->streams[i]->codec->width); h = FFMAX(h, avf->streams[i]->codec->height); } } if (!(w && h)) { w = FFMAX(w, 720); h = FFMAX(h, 576); } av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h); } ist->sub2video.w = ist->dec_ctx->width = ist->resample_width = w; ist->sub2video.h = ist->dec_ctx->height = ist->resample_height = h; /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the palettes for all rectangles are identical or compatible */ ist->resample_pix_fmt = ist->dec_ctx->pix_fmt = AV_PIX_FMT_RGB32; ist->sub2video.frame = av_frame_alloc(); if (!ist->sub2video.frame) return AVERROR(ENOMEM); ist->sub2video.last_pts = INT64_MIN; return 0; }


SPL_METHOD ( SplFileInfo , getExtension ) {
 spl_filesystem_object * intern = ( spl_filesystem_object * ) zend_object_store_get_object ( getThis ( ) TSRMLS_CC ) ;
 char * fname = NULL ;
 const char * p ;
 size_t flen ;
 int path_len , idx ;
 if ( zend_parse_parameters_none ( ) == FAILURE ) {
 return ;
 }
 spl_filesystem_object_get_path ( intern , & path_len TSRMLS_CC ) ;
 if ( path_len && path_len < intern -> file_name_len ) {
 fname = intern -> file_name + path_len + 1 ;
 flen = intern -> file_name_len - ( path_len + 1 ) ;
 }
 else {
 fname = intern -> file_name ;
 flen = intern -> file_name_len ;
 }
 php_basename ( fname , flen , NULL , 0 , & fname , & flen TSRMLS_CC ) ;
 p = zend_memrchr ( fname , '.' , flen ) ;
 if ( p ) {
 idx = p - fname ;
 RETVAL_STRINGL ( fname + idx + 1 , flen - idx - 1 , 1 ) ;
 efree ( fname ) ;
 return ;
 }
 else {
 if ( fname ) {
 efree ( fname ) ;
 }
 RETURN_EMPTY_STRING ( ) ;
 }
 }


size_t srvstr_get_path_req(TALLOC_CTX *mem_ctx, struct smb_request *req,
				 char **pp_dest, const char *src, int flags,
				 NTSTATUS *err)
{
	ssize_t bufrem = smbreq_bufrem(req, src);

	if (bufrem < 0) {
		*err = NT_STATUS_INVALID_PARAMETER;
		return 0;
	}

	if (req->posix_pathnames) {
		return srvstr_get_path_internal(mem_ctx,
				(const char *)req->inbuf,
				req->flags2,
				pp_dest,
				src,
				bufrem,
				flags,
				true,
				err);
	} else {
		return srvstr_get_path_internal(mem_ctx,
				(const char *)req->inbuf,
				req->flags2,
				pp_dest,
				src,
				bufrem,
				flags,
				false,
				err);
	}
}


static void set_sel_time(IPMIBmcSim *ibs, uint8_t *cmd, unsigned int cmd_len, uint8_t *rsp, unsigned int *rsp_len, unsigned int max_rsp_len) { uint32_t val; struct ipmi_time now; IPMI_CHECK_CMD_LEN(6); val = cmd[2] | (cmd[3] << 8) | (cmd[4] << 16) | (cmd[5] << 24); ipmi_gettime(&now); ibs->sel.time_offset = now.tv_sec - ((long) val); }


const char *print_wrid(int wrid) { if (wrid >= RDMA_WRID_RECV_CONTROL) { return wrid_desc[RDMA_WRID_RECV_CONTROL]; } return wrid_desc[wrid]; }


GF_Err gp_rtp_builder_do_vvc(GP_RTPPacketizer *builder, u8 *nalu, u32 nalu_size, u8 IsAUEnd, u32 FullAUSize)
{
	u32 do_flush, bytesLeft, size;

	do_flush = 0;
	if (!nalu) do_flush = 1;
	else if (builder->sl_header.accessUnitStartFlag) do_flush = 1;
	/*we must NOT fragment a NALU*/
	else if (builder->bytesInPacket + nalu_size + 4 >= builder->Path_MTU) do_flush = 2; //2 bytes PayloadHdr for AP + 2 bytes NAL size
	/*aggregation is disabled*/
	else if (! (builder->flags & GP_RTP_PCK_USE_MULTI) ) do_flush = 2;

	if (builder->bytesInPacket && do_flush) {
		builder->rtp_header.Marker = (do_flush==1) ? 1 : 0;
		/*insert payload_hdr in case of AP*/
		if (strlen(builder->hevc_payload_hdr)) {
			builder->OnData(builder->cbk_obj, (char *)builder->hevc_payload_hdr, 2, GF_TRUE);
			memset(builder->hevc_payload_hdr, 0, 2);
		}
		builder->OnPacketDone(builder->cbk_obj, &builder->rtp_header);
		builder->bytesInPacket = 0;
	}

	if (!nalu) return GF_OK;

	/*need a new RTP packet*/
	if (!builder->bytesInPacket) {
		builder->rtp_header.PayloadType = builder->PayloadType;
		builder->rtp_header.TimeStamp = (u32) builder->sl_header.compositionTimeStamp;
		builder->rtp_header.SequenceNumber += 1;
		builder->OnNewPacket(builder->cbk_obj, &builder->rtp_header);
	}

	/*at this point we're sure the NALU fits in current packet OR must be splitted*/
	/*check that we should use single NALU packet mode or aggreation packets mode*/
	if (builder->bytesInPacket+nalu_size+4 < builder->Path_MTU) {
		Bool use_AP = (builder->flags & GP_RTP_PCK_USE_MULTI) ? GF_TRUE : GF_FALSE;
		/*if this is the AU end and no NALU in packet, go for single NALU packet mode*/
		if (IsAUEnd && !builder->bytesInPacket) use_AP = GF_FALSE;

		if (use_AP) {
			char nal_s[2];
			/*declare PayloadHdr for AP*/
			if (!builder->bytesInPacket) {
				//copy everything, reassign type (byte 1 bits 8-3)
				builder->hevc_payload_hdr[0] = nalu[0];
				builder->hevc_payload_hdr[1] = (RTP_VVC_AGG_NAL << 3) | (nalu[1] & 0x7);
			}
			else {
				/*F bit of AP is 0 if the F bit of each aggreated NALU is 0; otherwise its must be 1*/
				/*LayerId and TID must be the lowest value of LayerId and TID of all aggreated NALU*/
				u8 cur_LayerId, cur_TID, new_LayerId, new_TID;

				builder->hevc_payload_hdr[0] |= (nalu[0] & 0x80);
				cur_LayerId = (builder->hevc_payload_hdr[0] & 0x3F);
				new_LayerId = (nalu[0] & 0x3F);
				if (cur_LayerId > new_LayerId) {
					builder->hevc_payload_hdr[0] = (builder->hevc_payload_hdr[0] & 0xC0) | new_LayerId;
				}
				cur_TID = builder->hevc_payload_hdr[1] & 0x3;
				new_TID = nalu[1] & 0x3;
				if (cur_TID > new_TID) {
					builder->hevc_payload_hdr[1] = (builder->hevc_payload_hdr[1] & 0xF8) | new_TID;
				}
			}

			/*add NALU size*/
			nal_s[0] = nalu_size>>8;
			nal_s[1] = nalu_size&0x00ff;
			builder->OnData(builder->cbk_obj, (char *)nal_s, 2, GF_FALSE);
			builder->bytesInPacket += 2;
		}
		/*add data*/
		if (builder->OnDataReference)
			builder->OnDataReference(builder->cbk_obj, nalu_size, 0);
		else
			builder->OnData(builder->cbk_obj, nalu, nalu_size, GF_FALSE);

		builder->bytesInPacket += nalu_size;

		if (IsAUEnd) {
			builder->rtp_header.Marker = 1;
			if (strlen(builder->hevc_payload_hdr)) {
				builder->OnData(builder->cbk_obj, (char *)builder->hevc_payload_hdr, 2, GF_TRUE);
				memset(builder->hevc_payload_hdr, 0, 2);
			}
			builder->OnPacketDone(builder->cbk_obj, &builder->rtp_header);
			builder->bytesInPacket = 0;
		}
	}
	/*fragmentation unit*/
	else {
		u32 offset;
		u8 payload_hdr[2];
		u8 shdr;

		assert(nalu_size + 4 >=builder->Path_MTU);
		assert(!builder->bytesInPacket);

		/*FU payload doesn't have the NAL hdr (2 bytes*/
		bytesLeft = nalu_size - 2;
		offset = 2;
		while (bytesLeft) {
			u8 nut;

			if (3 + bytesLeft > builder->Path_MTU) {
				size = builder->Path_MTU - 3;
			} else {
				size = bytesLeft;
			}

			/*declare PayloadHdr for FU*/
			memset(payload_hdr, 0, 2);
			/*copy everything and assign type*/
			payload_hdr[0] = nalu[0];
			payload_hdr[1] = (((u32) RTP_VVC_FRAG_NAL) << 3) | (nalu[1] & 0x7);
			builder->OnData(builder->cbk_obj, (char *)payload_hdr, 2, GF_FALSE);

			nut = nalu[1] >> 3;
			/*declare FU header*/
			shdr = 0;
			/*assign type*/
			shdr |= nut;
			/*start bit*/
			if (offset==2) shdr |= 0x80;
			/*end bit*/
			else if (size == bytesLeft) {
				shdr |= 0x40;
				//VCL, last packet of picture, set P bit
				if (nut <= GF_VVC_NALU_SLICE_GDR) {
					shdr |= 0x20;
				}
			}

			builder->OnData(builder->cbk_obj, &shdr, 1, GF_FALSE);

			/*add data*/
			if (builder->OnDataReference)
				builder->OnDataReference(builder->cbk_obj, size, offset);
			else
				builder->OnData(builder->cbk_obj, nalu+offset, size, GF_FALSE);

			offset += size;
			bytesLeft -= size;

			/*flush no matter what (FUs cannot be agreggated)*/
			builder->rtp_header.Marker = (IsAUEnd && !bytesLeft) ? 1 : 0;
			builder->OnPacketDone(builder->cbk_obj, &builder->rtp_header);
			builder->bytesInPacket = 0;

			if (bytesLeft) {
				builder->rtp_header.PayloadType = builder->PayloadType;
				builder->rtp_header.TimeStamp = (u32) builder->sl_header.compositionTimeStamp;
				builder->rtp_header.SequenceNumber += 1;
				builder->OnNewPacket(builder->cbk_obj, &builder->rtp_header);
			}
		}
	}
	return GF_OK;
}


IN_PROC_BROWSER_TEST_F ( MediaStreamPermissionTest , TestDenyingUserMediaIncognito ) {
 content : : WebContents * tab_contents = LoadTestPageInIncognitoTab ( ) ;
 GetUserMediaAndDeny ( tab_contents ) ;
 }


static GF_Err nhmldmx_send_sample(GF_Filter *filter, GF_NHMLDmxCtx *ctx)
{
	GF_XMLNode *node, *childnode;
	u64 sample_duration = 0;
	char szMediaTemp[GF_MAX_PATH], szXmlFrom[1000], szXmlTo[1000];
	char *szSubSampleName = ctx->is_dims ? "DIMSSubUnit" : "NHNTSubSample";

	while ((node = (GF_XMLNode *) gf_list_enum(ctx->root->content, &ctx->current_child_idx))) {
		u8 *data;
		GF_FilterPacket *pck;
		u32 j, dims_flags;
		GF_FilterSAPType sap_type;
		GF_XMLAttribute *att;
		u64 dts=0;
		GF_Err e=GF_OK;
		s32 cts_offset;
		u64 offset=0, byte_offset = GF_FILTER_NO_BO;
		u32 nb_subsamples = 0;
		Bool redundant_rap, append, has_subbs, first_subsample_is_first = GF_FALSE;
		u32 compress_type;
		char *base_data = NULL;
		if (node->type) continue;
		if (stricmp(node->name, ctx->is_dims ? "DIMSUnit" : "NHNTSample") ) continue;

		strcpy(szMediaTemp, "");
		strcpy(szXmlFrom, "");
		strcpy(szXmlTo, "");

		/*by default handle all samples as contiguous*/
		ctx->samp_buffer_size = 0;
		dims_flags = 0;
		append = GF_FALSE;
		compress_type = ctx->compress_type;
		sample_duration = 0;
		redundant_rap = 0;
		sap_type = ctx->has_sap ? GF_FILTER_SAP_NONE : GF_FILTER_SAP_1;

		cts_offset = 0;
		if (ctx->last_dts != GF_FILTER_NO_TS)
			dts = ctx->last_dts;
		else
			dts = 0;

		ctx->sample_num++;

		j=0;
		while ( (att = (GF_XMLAttribute *)gf_list_enum(node->attributes, &j))) {
			if (!stricmp(att->name, "DTS") || !stricmp(att->name, "time")) {
				u32 h, m, s, ms;
				u64 dst_val;
				if (strchr(att->value, ':') && sscanf(att->value, "%u:%u:%u.%u", &h, &m, &s, &ms) == 4) {
					dts = (u64) ( (Double) ( ((h*3600.0 + m*60.0 + s)*1000 + ms) / 1000.0) * ctx->timescale );
				} else if (sscanf(att->value, ""LLU, &dst_val)==1) {
					dts = dst_val;
				}
			}
			else if (!stricmp(att->name, "CTSOffset")) cts_offset = atoi(att->value);
			else if (!stricmp(att->name, "isRAP") ) {
				sap_type = (!stricmp(att->value, "yes")) ? GF_FILTER_SAP_1 : GF_FILTER_SAP_NONE;
			}
			else if (!stricmp(att->name, "isSyncShadow")) redundant_rap = !stricmp(att->value, "yes") ? 1 : 0;
			else if (!stricmp(att->name, "SAPType") ) sap_type = atoi(att->value);
			else if (!stricmp(att->name, "mediaOffset")) offset = (s64) atof(att->value) ;
			else if (!stricmp(att->name, "dataLength")) ctx->samp_buffer_size = atoi(att->value);
			else if (!stricmp(att->name, "mediaFile")) {
				if (!strncmp(att->value, "data:", 5)) {
					char *base = strstr(att->value, "base64,");
					if (!base) {
						GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[NHMLDmx] Data encoding scheme not recognized in sample %d - skipping\n", ctx->sample_num));
					} else {
						base_data = att->value;
					}
				} else {
					char *url = gf_url_concatenate(ctx->src_url, att->value);
					strcpy(szMediaTemp, url ? url : att->value);
					if (url) gf_free(url);
				}
			}
			else if (!stricmp(att->name, "xmlFrom")) strcpy(szXmlFrom, att->value);
			else if (!stricmp(att->name, "xmlTo")) strcpy(szXmlTo, att->value);
			/*DIMS flags*/
			else if (!stricmp(att->name, "is-Scene") && !stricmp(att->value, "yes"))
				dims_flags |= GF_DIMS_UNIT_S;
			else if (!stricmp(att->name, "is-RAP") && !stricmp(att->value, "yes")) {
				dims_flags |= GF_DIMS_UNIT_M;
				sap_type = GF_FILTER_SAP_1;
			}
			else if (!stricmp(att->name, "is-redundant") && !stricmp(att->value, "yes"))
				dims_flags |= GF_DIMS_UNIT_I;
			else if (!stricmp(att->name, "redundant-exit") && !stricmp(att->value, "yes"))
				dims_flags |= GF_DIMS_UNIT_D;
			else if (!stricmp(att->name, "priority") && !stricmp(att->value, "high"))
				dims_flags |= GF_DIMS_UNIT_P;
			else if (!stricmp(att->name, "compress") && !stricmp(att->value, "yes"))
				dims_flags |= GF_DIMS_UNIT_C;
			else if (!stricmp(att->name, "duration") )
				sscanf(att->value, ""LLU, &sample_duration);
		}
		if (sap_type==GF_FILTER_SAP_1)
			dims_flags |= GF_DIMS_UNIT_M;

		if (ctx->is_dims)
			compress_type = (dims_flags & GF_DIMS_UNIT_C) ? 2 : 0 ;

		if (ctx->is_img) sample_duration = ctx->duration.den;

		has_subbs = GF_FALSE;
		j=0;
		while ((childnode = (GF_XMLNode *) gf_list_enum(node->content, &j))) {
			if (childnode->type) continue;
			if (!stricmp(childnode->name, "BS")) {
				has_subbs = GF_TRUE;
				break;
			}
		}

		if (strlen(szXmlFrom) && strlen(szXmlTo)) {
			char *xml_file;
			if (strlen(szMediaTemp)) xml_file = szMediaTemp;
			else xml_file = ctx->szMedia;
			ctx->samp_buffer_size = 0;
			e = nhml_sample_from_xml(ctx, xml_file, szXmlFrom, szXmlTo);
		} else if (ctx->is_dims && !strlen(szMediaTemp)) {

			char *content = gf_xml_dom_serialize(node, GF_TRUE, GF_FALSE);

			ctx->samp_buffer_size = 3 + (u32) strlen(content);
			if (ctx->samp_buffer_alloc < ctx->samp_buffer_size) {
				ctx->samp_buffer_alloc = ctx->samp_buffer_size;
				ctx->samp_buffer = gf_realloc(ctx->samp_buffer, ctx->samp_buffer_size);
			}
			nhml_get_bs(&ctx->bs_w, ctx->samp_buffer, ctx->samp_buffer_size, GF_BITSTREAM_WRITE);
			gf_bs_write_u16(ctx->bs_w, ctx->samp_buffer_size - 2);
			gf_bs_write_u8(ctx->bs_w, (u8) dims_flags);
			gf_bs_write_data(ctx->bs_w, content, (ctx->samp_buffer_size - 3));
			gf_free(content);

			/*same DIMS unit*/
			if (ctx->last_dts == dts)
				append = GF_TRUE;

		} else if (has_subbs) {
			gf_bs_reassign_buffer(ctx->bs_w, ctx->samp_buffer, ctx->samp_buffer_alloc);
			gf_xml_parse_bit_sequence_bs(node, ctx->src_url, ctx->bs_w);
			gf_bs_get_content(ctx->bs_w, &ctx->samp_buffer, &ctx->samp_buffer_size);
			if (ctx->samp_buffer_size > ctx->samp_buffer_alloc)
				ctx->samp_buffer_alloc = ctx->samp_buffer_size;

		} else if (base_data) {
			char *start = strchr(base_data, ',');
			if (start) {
				u32 len = (u32)strlen(start+1);
				if (len > ctx->samp_buffer_alloc) {
					ctx->samp_buffer_alloc = len;
					ctx->samp_buffer = gf_realloc(ctx->samp_buffer, sizeof(char)*ctx->samp_buffer_alloc);
				}
				ctx->samp_buffer_size = gf_base64_decode(start, len, ctx->samp_buffer, ctx->samp_buffer_alloc);
			}
		} else {
			Bool close = GF_FALSE;
			FILE *f = ctx->mdia;

			j = 0;
			while ((childnode = (GF_XMLNode *)gf_list_enum(node->content, &j))) {
				if (childnode->type) continue;
				if (!stricmp(childnode->name, szSubSampleName)) {
					nb_subsamples++;
				}
			}

			if (strlen(szMediaTemp)) {
				f = gf_fopen(szMediaTemp, "rb");
				if (!f) {
					GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[NHMLDmx] import failure in sample %d: file %s not found", ctx->sample_num, close ? szMediaTemp : ctx->szMedia));
					return GF_NON_COMPLIANT_BITSTREAM;
				}
				close = GF_TRUE;
				if (offset) gf_fseek(f, offset, SEEK_SET);
				//when using dedicated source files per samples, we don't allow for data reference yet
			} else {
				if (!offset) offset = ctx->media_done;
				byte_offset = offset;
			}

			if (f) {
				if (!ctx->samp_buffer_size) {
					u64 ssize = gf_fsize(f);
					assert(ssize < 0x80000000);
					ctx->samp_buffer_size = (u32) ssize;
				}
				gf_fseek(f, offset, SEEK_SET);

				if (ctx->is_dims) {
					u32 read;
					if (ctx->samp_buffer_size + 3 > ctx->samp_buffer_alloc) {
						ctx->samp_buffer_alloc = ctx->samp_buffer_size + 3;
						ctx->samp_buffer = (char*)gf_realloc(ctx->samp_buffer, sizeof(char) * ctx->samp_buffer_alloc);
					}
					nhml_get_bs(&ctx->bs_w, ctx->samp_buffer, ctx->samp_buffer_alloc, GF_BITSTREAM_WRITE);
					gf_bs_write_u16(ctx->bs_w, ctx->samp_buffer_size+1);
					gf_bs_write_u8(ctx->bs_w, (u8) dims_flags);
					read = (u32) gf_fread( ctx->samp_buffer + 3, ctx->samp_buffer_size, f);
					if (ctx->samp_buffer_size != read) {
						GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[NHMLDmx] Failed to fully read sample %d: dataLength %d read %d\n", ctx->sample_num, ctx->samp_buffer_size, read));
					}
					ctx->samp_buffer_size += 3;

					/*same DIMS unit*/
					if (ctx->last_dts == dts)
						append = GF_TRUE;
				} else {
					u32 read;
					if (ctx->samp_buffer_alloc < ctx->samp_buffer_size) {
						ctx->samp_buffer_alloc = ctx->samp_buffer_size;
						ctx->samp_buffer = (char*)gf_realloc(ctx->samp_buffer, sizeof(char) * ctx->samp_buffer_alloc);
					}
					read = (u32) gf_fread(ctx->samp_buffer, ctx->samp_buffer_size, f);
					if (ctx->samp_buffer_size != read) {
						GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[NHMLDmx] Failed to fully read sample %d: dataLength %d read %d\n", ctx->sample_num, ctx->samp_buffer_size, read));
					}
				}
				if (close) gf_fclose(f);
			} else if (!nb_subsamples) {
				GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[NHMLDmx] No media file associated with sample %d!\n", ctx->sample_num));
				e = GF_URL_ERROR;
			}
		}

		if (e) return e;

		//override DIMS flags
		if (ctx->is_dims) {
			if (strstr(ctx->samp_buffer + 3, "svg ")) dims_flags |= GF_DIMS_UNIT_S;
			if (dims_flags & GF_DIMS_UNIT_S) dims_flags |= GF_DIMS_UNIT_P;
			ctx->samp_buffer[2] = dims_flags;
		}

		if (compress_type) {
#ifndef GPAC_DISABLE_ZLIB
			e = compress_sample_data(ctx, compress_type, ctx->use_dict ? &ctx->dictionary : NULL, ctx->is_dims ? 3 : 0);
			if (e) return e;

			if (ctx->is_dims) {
				nhml_get_bs(&ctx->bs_w, ctx->samp_buffer, ctx->samp_buffer_size, GF_BITSTREAM_WRITE);
				gf_bs_write_u16(ctx->bs_w, ctx->samp_buffer_size-2);
			}
#else
			GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[NHMLDmx] Error: your version of GPAC was compiled with no libz support. Abort."));
			return GF_NOT_SUPPORTED;
#endif
		}

		if (ctx->is_dims && (ctx->samp_buffer_size > 0xFFFF)) {
			GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[NHMLDmx] DIMS import failure: sample %d data is too long - maximum size allowed: 65532 bytes", ctx->sample_num));
			return GF_NON_COMPLIANT_BITSTREAM;
		}
		if (ctx->samp_buffer_size) {
			pck = gf_filter_pck_new_alloc(ctx->opid, ctx->samp_buffer_size, &data);
			if (!pck) return GF_OUT_OF_MEM;

			memcpy(data, ctx->samp_buffer, ctx->samp_buffer_size);
			gf_filter_pck_set_framing(pck, append ? GF_FALSE : GF_TRUE, nb_subsamples ? GF_FALSE : GF_TRUE);
			if (!append) {
				gf_filter_pck_set_sap(pck, sap_type);
				gf_filter_pck_set_dts(pck, dts);
				gf_filter_pck_set_cts(pck, dts+cts_offset);
				if (redundant_rap && !ctx->is_dims) gf_filter_pck_set_dependency_flags(pck, 0x1);

				if (sample_duration || ctx->dts_inc)
					gf_filter_pck_set_duration(pck, sample_duration ? (u32) sample_duration : ctx->dts_inc);

				if (byte_offset != GF_FILTER_NO_BO)
					gf_filter_pck_set_byte_offset(pck, byte_offset);

				if (ctx->in_seek) {
					if (dts+cts_offset >= ctx->start_range * ctx->timescale)
						ctx->in_seek = GF_FALSE;
					else
						gf_filter_pck_set_seek_flag(pck, GF_TRUE);
				}
			}
			gf_filter_pck_send(pck);
		} else {
			first_subsample_is_first = GF_TRUE;
		}

		if (nb_subsamples) {
			if (ctx->samp_buffer_alloc<14*nb_subsamples) {
				ctx->samp_buffer_alloc = 14*nb_subsamples;
				ctx->samp_buffer = gf_realloc(ctx->samp_buffer, ctx->samp_buffer_alloc);
			}
			assert(ctx->samp_buffer);
			nhml_get_bs(&ctx->bs_w, ctx->samp_buffer, ctx->samp_buffer_alloc, GF_BITSTREAM_WRITE);
		}

		j = 0;
		while (!append && nb_subsamples && (childnode = (GF_XMLNode *)gf_list_enum(node->content, &j))) {
			if (childnode->type) continue;
			if (!stricmp(childnode->name, szSubSampleName)) {
				u32 k = 0;
				while ((att = (GF_XMLAttribute *)gf_list_enum(childnode->attributes, &k))) {
					if (!stricmp(att->name, "mediaFile")) {
						u64 subsMediaFileSize = 0;
						FILE *f = NULL;
						char *sub_file_url = gf_url_concatenate(ctx->src_url, att->value);
						if (sub_file_url) {
							f = gf_fopen(sub_file_url, "rb");
							gf_free(sub_file_url);
						}

						if (!f) {
							GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[NHMLDmx] Error: mediaFile \"%s\" not found for subsample in sample %d. Abort.\n", att->value, ctx->sample_num));
							return GF_URL_ERROR;
						}
						subsMediaFileSize = gf_fsize(f);
						assert(subsMediaFileSize < 0x80000000);

						//send continuation frame
						pck = gf_filter_pck_new_alloc(ctx->opid, (u32) subsMediaFileSize, &data);
						if (!pck) {
							gf_fclose(f);
							return GF_OUT_OF_MEM;
						}
						subsMediaFileSize = (u32) gf_fread(data, (u32) subsMediaFileSize, f);
						gf_fclose(f);

						nb_subsamples--;
						if (first_subsample_is_first) {
							gf_filter_pck_set_framing(pck, GF_TRUE, nb_subsamples ? GF_FALSE : GF_TRUE);

							gf_filter_pck_set_sap(pck, sap_type);
							gf_filter_pck_set_dts(pck, dts);
							gf_filter_pck_set_cts(pck, dts+cts_offset);
							if (redundant_rap && !ctx->is_dims) gf_filter_pck_set_dependency_flags(pck, 0x1);

							if (sample_duration || ctx->dts_inc)
								gf_filter_pck_set_duration(pck, sample_duration ? (u32) sample_duration : ctx->dts_inc);

							if (ctx->in_seek) {
								if (dts+cts_offset >= ctx->start_range * ctx->timescale)
									ctx->in_seek = GF_FALSE;
								else
									gf_filter_pck_set_seek_flag(pck, GF_TRUE);
							}

							first_subsample_is_first = GF_FALSE;
						} else {
							gf_filter_pck_set_framing(pck, GF_FALSE, nb_subsamples ? GF_FALSE : GF_TRUE);
						}

						gf_bs_write_u32(ctx->bs_w, 0); //flags
						gf_bs_write_u32(ctx->bs_w, (u32) subsMediaFileSize);
						gf_bs_write_u32(ctx->bs_w, 0); //reserved
						gf_bs_write_u8(ctx->bs_w, 0); //priority
						gf_bs_write_u8(ctx->bs_w, 0); //discardable

						if (!nb_subsamples) {
							u32 subs_size = (u32) gf_bs_get_position(ctx->bs_w);
							gf_filter_pck_set_property(pck, GF_PROP_PCK_SUBS, &PROP_DATA(ctx->samp_buffer, subs_size) );
						}

						gf_filter_pck_send(pck);
					}
				}
			}
		}

		ctx->last_dts = dts;

		if (sample_duration)
			ctx->last_dts += sample_duration;
		else
			ctx->last_dts += ctx->dts_inc;
		ctx->media_done += ctx->samp_buffer_size;

		if (gf_filter_pid_would_block(ctx->opid))
			return GF_OK;
	}
	ctx->parsing_state = 2;
	return GF_OK;


static void decode_mb_p ( AVSContext * h , enum cavs_mb mb_type ) {
 GetBitContext * gb = & h -> gb ;
 int ref [ 4 ] ;
 ff_cavs_init_mb ( h ) ;
 switch ( mb_type ) {
 case P_SKIP : ff_cavs_mv ( h , MV_FWD_X0 , MV_FWD_C2 , MV_PRED_PSKIP , BLK_16X16 , 0 ) ;
 break ;
 case P_16X16 : ref [ 0 ] = h -> ref_flag ? 0 : get_bits1 ( gb ) ;
 ff_cavs_mv ( h , MV_FWD_X0 , MV_FWD_C2 , MV_PRED_MEDIAN , BLK_16X16 , ref [ 0 ] ) ;
 break ;
 case P_16X8 : ref [ 0 ] = h -> ref_flag ? 0 : get_bits1 ( gb ) ;
 ref [ 2 ] = h -> ref_flag ? 0 : get_bits1 ( gb ) ;
 ff_cavs_mv ( h , MV_FWD_X0 , MV_FWD_C2 , MV_PRED_TOP , BLK_16X8 , ref [ 0 ] ) ;
 ff_cavs_mv ( h , MV_FWD_X2 , MV_FWD_A1 , MV_PRED_LEFT , BLK_16X8 , ref [ 2 ] ) ;
 break ;
 case P_8X16 : ref [ 0 ] = h -> ref_flag ? 0 : get_bits1 ( gb ) ;
 ref [ 1 ] = h -> ref_flag ? 0 : get_bits1 ( gb ) ;
 ff_cavs_mv ( h , MV_FWD_X0 , MV_FWD_B3 , MV_PRED_LEFT , BLK_8X16 , ref [ 0 ] ) ;
 ff_cavs_mv ( h , MV_FWD_X1 , MV_FWD_C2 , MV_PRED_TOPRIGHT , BLK_8X16 , ref [ 1 ] ) ;
 break ;
 case P_8X8 : ref [ 0 ] = h -> ref_flag ? 0 : get_bits1 ( gb ) ;
 ref [ 1 ] = h -> ref_flag ? 0 : get_bits1 ( gb ) ;
 ref [ 2 ] = h -> ref_flag ? 0 : get_bits1 ( gb ) ;
 ref [ 3 ] = h -> ref_flag ? 0 : get_bits1 ( gb ) ;
 ff_cavs_mv ( h , MV_FWD_X0 , MV_FWD_B3 , MV_PRED_MEDIAN , BLK_8X8 , ref [ 0 ] ) ;
 ff_cavs_mv ( h , MV_FWD_X1 , MV_FWD_C2 , MV_PRED_MEDIAN , BLK_8X8 , ref [ 1 ] ) ;
 ff_cavs_mv ( h , MV_FWD_X2 , MV_FWD_X1 , MV_PRED_MEDIAN , BLK_8X8 , ref [ 2 ] ) ;
 ff_cavs_mv ( h , MV_FWD_X3 , MV_FWD_X0 , MV_PRED_MEDIAN , BLK_8X8 , ref [ 3 ] ) ;
 }
 ff_cavs_inter ( h , mb_type ) ;
 set_intra_mode_default ( h ) ;
 store_mvs ( h ) ;
 if ( mb_type != P_SKIP ) decode_residual_inter ( h ) ;
 ff_cavs_filter ( h , mb_type ) ;
 h -> col_type_base [ h -> mbidx ] = mb_type ;
 }


static av_cold int pcm_encode_close(AVCodecContext *avctx) { av_freep(&avctx->coded_frame); return 0; }


static int dissect_h225_InfoRequestResponse ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h225_InfoRequestResponse , InfoRequestResponse_sequence ) ;
 return offset ;
 }


static int scsi_write_data(SCSIDevice *d, uint32_t tag) { SCSIGenericState *s = DO_UPCAST(SCSIGenericState, qdev, d); SCSIGenericReq *r; int ret; DPRINTF("scsi_write_data 0x%x\n", tag); r = scsi_find_request(s, tag); if (!r) { BADF("Bad write tag 0x%x\n", tag); /* ??? This is the wrong error. */ scsi_command_complete(r, -EINVAL); return 0; } if (r->len == 0) { r->len = r->buflen; scsi_req_data(&r->req, r->len); return 0; } ret = execute_command(s->bs, r, SG_DXFER_TO_DEV, scsi_write_complete); if (ret == -1) { scsi_command_complete(r, -EINVAL); return 1; } return 0; }


main(int argc, char **argv)
{
	const char *safepath = "/bin:/sbin:/usr/bin:/usr/sbin:"
	    "/usr/local/bin:/usr/local/sbin";
	const char *confpath = NULL;
	char *shargv[] = { NULL, NULL };
	char *sh;
	const char *p;
	const char *cmd;
	char cmdline[LINE_MAX];
	struct passwd mypwstore, targpwstore;
	struct passwd *mypw, *targpw;
	const struct rule *rule;
	uid_t uid;
	uid_t target = 0;
	gid_t groups[NGROUPS_MAX + 1];
	int ngroups;
	int i, ch, rv;
	int sflag = 0;
	int nflag = 0;
	char cwdpath[PATH_MAX];
	const char *cwd;
	char **envp;

	setprogname("doas");

	closefrom(STDERR_FILENO + 1);

	uid = getuid();

	while ((ch = getopt(argc, argv, "+C:Lnsu:")) != -1) {
		switch (ch) {
		case 'C':
			confpath = optarg;
			break;
		case 'L':
#if defined(USE_TIMESTAMP)
			exit(timestamp_clear() == -1);
#else
			exit(0);
#endif
		case 'u':
			if (parseuid(optarg, &target) != 0)
				errx(1, "unknown user");
			break;
		case 'n':
			nflag = 1;
			break;
		case 's':
			sflag = 1;
			break;
		default:
			usage();
			break;
		}
	}
	argv += optind;
	argc -= optind;

	if (confpath) {
		if (sflag)
			usage();
	} else if ((!sflag && !argc) || (sflag && argc))
		usage();

	rv = mygetpwuid_r(uid, &mypwstore, &mypw);
	if (rv != 0)
		err(1, "getpwuid_r failed");
	if (mypw == NULL)
		errx(1, "no passwd entry for self");
	ngroups = getgroups(NGROUPS_MAX, groups);
	if (ngroups == -1)
		err(1, "can't get groups");
	groups[ngroups++] = getgid();

	if (sflag) {
		sh = getenv("SHELL");
		if (sh == NULL || *sh == '\0') {
			shargv[0] = mypw->pw_shell;
		} else
			shargv[0] = sh;
		argv = shargv;
		argc = 1;
	}

	if (confpath) {
		checkconfig(confpath, argc, argv, uid, groups, ngroups,
		    target);
		exit(1);	/* fail safe */
	}

	if (geteuid())
		errx(1, "not installed setuid");

	parseconfig(DOAS_CONF, 1);

	/* cmdline is used only for logging, no need to abort on truncate */
	(void)strlcpy(cmdline, argv[0], sizeof(cmdline));
	for (i = 1; i < argc; i++) {
		if (strlcat(cmdline, " ", sizeof(cmdline)) >= sizeof(cmdline))
			break;
		if (strlcat(cmdline, argv[i], sizeof(cmdline)) >= sizeof(cmdline))
			break;
	}

	cmd = argv[0];
	if (!permit(uid, groups, ngroups, &rule, target, cmd,
	    (const char **)argv + 1)) {
		syslog(LOG_AUTHPRIV | LOG_NOTICE,
		    "command not permitted for %s: %s", mypw->pw_name, cmdline);
		errc(1, EPERM, NULL);
	}

#if defined(USE_SHADOW)
	if (!(rule->options & NOPASS)) {
		if (nflag)
			errx(1, "Authorization required");

		shadowauth(mypw->pw_name, rule->options & PERSIST);
	}
#elif !defined(USE_PAM)
	/* no authentication provider, only allow NOPASS rules */
	(void) nflag;
	if (!(rule->options & NOPASS))
		errx(1, "Authorization required");
#endif

	if ((p = getenv("PATH")) != NULL)
		formerpath = strdup(p);
	if (formerpath == NULL)
		formerpath = "";

	if (rule->cmd) {
		if (setenv("PATH", safepath, 1) == -1)
			err(1, "failed to set PATH '%s'", safepath);
	}

	rv = mygetpwuid_r(target, &targpwstore, &targpw);
	if (rv != 0)
		err(1, "getpwuid_r failed");
	if (targpw == NULL)
		errx(1, "no passwd entry for target");

#if defined(USE_PAM)
	pamauth(targpw->pw_name, mypw->pw_name, !nflag, rule->options & NOPASS,
	    rule->options & PERSIST);
#endif

#ifdef HAVE_LOGIN_CAP_H
	if (setusercontext(NULL, targpw, target, LOGIN_SETGROUP |
	    LOGIN_SETPRIORITY | LOGIN_SETRESOURCES | LOGIN_SETUMASK |
	    LOGIN_SETUSER) != 0)
		errx(1, "failed to set user context for target");
#else
	if (setresgid(targpw->pw_gid, targpw->pw_gid, targpw->pw_gid) != 0)
		err(1, "setresgid");
	if (initgroups(targpw->pw_name, targpw->pw_gid) != 0)
		err(1, "initgroups");
	if (setresuid(target, target, target) != 0)
		err(1, "setresuid");
#endif

	if (getcwd(cwdpath, sizeof(cwdpath)) == NULL)
		cwd = "(failed)";
	else
		cwd = cwdpath;

	if (!(rule->options & NOLOG)) {
		syslog(LOG_AUTHPRIV | LOG_INFO,
		    "%s ran command %s as %s from %s",
		    mypw->pw_name, cmdline, targpw->pw_name, cwd);
	}

	envp = prepenv(rule, mypw, targpw);

	/* setusercontext set path for the next process, so reset it for us */
	if (rule->cmd) {
		if (setenv("PATH", safepath, 1) == -1)
			err(1, "failed to set PATH '%s'", safepath);
	} else {
		if (setenv("PATH", formerpath, 1) == -1)
			err(1, "failed to set PATH '%s'", formerpath);
	}
	execvpe(cmd, argv, envp);
	if (errno == ENOENT)
		errx(1, "%s: command not found", cmd);
	err(1, "%s", cmd);
}


static int segment_end(AVFormatContext *oc, int write_trailer) { int ret = 0; av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */ if (write_trailer) av_write_trailer(oc); avio_close(oc->pb); return ret; }


static int ratecontrol_1pass(SnowContext *s, AVFrame *pict) { /* estimate the frame's complexity as a sum of weighted dwt coefs. * FIXME we know exact mv bits at this point, * but ratecontrol isn't set up to include them. */ uint32_t coef_sum= 0; int level, orientation, delta_qlog; for(level=0; level<s->spatial_decomposition_count; level++){ for(orientation=level ? 1 : 0; orientation<4; orientation++){ SubBand *b= &s->plane[0].band[level][orientation]; DWTELEM *buf= b->buf; const int w= b->width; const int h= b->height; const int stride= b->stride; const int qlog= clip(2*QROOT + b->qlog, 0, QROOT*16); const int qmul= qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT); const int qdiv= (1<<16)/qmul; int x, y; if(orientation==0) decorrelate(s, b, buf, stride, 1, 0); for(y=0; y<h; y++) for(x=0; x<w; x++) coef_sum+= abs(buf[x+y*stride]) * qdiv >> 16; if(orientation==0) correlate(s, b, buf, stride, 1, 0); } } /* ugly, ratecontrol just takes a sqrt again */ coef_sum = (uint64_t)coef_sum * coef_sum >> 16; assert(coef_sum < INT_MAX); if(pict->pict_type == I_TYPE){ s->m.current_picture.mb_var_sum= coef_sum; s->m.current_picture.mc_mb_var_sum= 0; }else{ s->m.current_picture.mc_mb_var_sum= coef_sum; s->m.current_picture.mb_var_sum= 0; } pict->quality= ff_rate_estimate_qscale(&s->m, 1); if (pict->quality < 0) return -1; s->lambda= pict->quality * 3/2; delta_qlog= qscale2qlog(pict->quality) - s->qlog; s->qlog+= delta_qlog; return delta_qlog; }


static inline void mix_3f_2r_to_dolby(AC3DecodeContext *ctx) { int i; float (*output)[256] = ctx->audio_block.block_output; for (i = 0; i < 256; i++) { output[1][i] += (output[2][i] - output[4][i] - output[5][i]); output[2][i] += (output[3][i] + output[4][i] + output[5][i]); } memset(output[3], 0, sizeof(output[3])); memset(output[4], 0, sizeof(output[4])); memset(output[5], 0, sizeof(output[5])); }


static std::string GetBaseFilename(const std::string &filepath) {
  auto idx = filepath.find_last_of("/\\");
  if (idx != std::string::npos)
    return filepath.substr(idx + 1);
  return filepath;
}


size_t estimate_size(const std::vector<RE*> &res)
{
    std::vector<StackItem> stack;

    const size_t nre = res.size();
    DASSERT(nre > 0);
    size_t size = nre - 1;

    for (size_t i = 0; i < nre; ++i) {
        size += estimate_re_size(res[i], stack) + 1;
    }

    return size;
}


static void simple_string(void) { int i; struct { const char *encoded; const char *decoded; } test_cases[] = { { "\"hello world\"", "hello world" }, { "\"the quick brown fox jumped over the fence\"", "the quick brown fox jumped over the fence" }, {} }; for (i = 0; test_cases[i].encoded; i++) { QObject *obj; QString *str; obj = qobject_from_json(test_cases[i].encoded, NULL); str = qobject_to_qstring(obj); g_assert(str); g_assert(strcmp(qstring_get_str(str), test_cases[i].decoded) == 0); str = qobject_to_json(obj); g_assert(strcmp(qstring_get_str(str), test_cases[i].encoded) == 0); qobject_decref(obj); QDECREF(str); } }


static char * value_string ( char * buf , int buf_size , struct unit_value uv ) {
 double vald ;
 long long int vali ;
 int show_float = 0 ;
 if ( uv . unit == unit_second_str ) {
 vald = uv . val . d ;
 show_float = 1 ;
 }
 else {
 vald = vali = uv . val . i ;
 }
 if ( uv . unit == unit_second_str && use_value_sexagesimal_format ) {
 double secs ;
 int hours , mins ;
 secs = vald ;
 mins = ( int ) secs / 60 ;
 secs = secs - mins * 60 ;
 hours = mins / 60 ;
 mins %= 60 ;
 snprintf ( buf , buf_size , "%d:%02d:%09.6f" , hours , mins , secs ) ;
 }
 else {
 const char * prefix_string = "" ;
 if ( use_value_prefix && vald > 1 ) {
 long long int index ;
 if ( uv . unit == unit_byte_str && use_byte_value_binary_prefix ) {
 index = ( long long int ) ( log2 ( vald ) ) / 10 ;
 index = av_clip ( index , 0 , FF_ARRAY_ELEMS ( si_prefixes ) - 1 ) ;
 vald /= si_prefixes [ index ] . bin_val ;
 prefix_string = si_prefixes [ index ] . bin_str ;
 }
 else {
 index = ( long long int ) ( log10 ( vald ) ) / 3 ;
 index = av_clip ( index , 0 , FF_ARRAY_ELEMS ( si_prefixes ) - 1 ) ;
 vald /= si_prefixes [ index ] . dec_val ;
 prefix_string = si_prefixes [ index ] . dec_str ;
 }
 vali = vald ;
 }
 if ( show_float || ( use_value_prefix && vald != ( long long int ) vald ) ) snprintf ( buf , buf_size , "%f" , vald ) ;
 else snprintf ( buf , buf_size , "%lld" , vali ) ;
 av_strlcatf ( buf , buf_size , "%s%s%s" , * prefix_string || show_value_unit ? " " : "" , prefix_string , show_value_unit ? uv . unit : "" ) ;
 }
 return buf ;
 }


nfa_t::nfa_t(const RESpec &spec)
    : max_size(estimate_size(spec.res))
    , size(0)
    , states(new nfa_state_t[max_size])
    , charset(spec.charset)
    , rules(spec.rules)
    , tags(spec.tags)
    , root(NULL)
    , ncores(0)
{
    const size_t nre = spec.res.size();

    if (nre == 0) return;

    for (size_t i = 0; i < nre; ++i) {
        rtn_ctx_t ctx = {spec.opts, *this, i};

        nfa_state_t *s = &states[size++];
        s->make_fin(i);
        s = re_to_nfa(ctx, spec.res[i], s);

        if (root) {
            nfa_state_t *t = &states[size++];
            t->make_alt(i, root, s);
            root = t;
        } else {
            root = s;
        }
    }

    // In-degree and topological index are used by POSIX disambiguation;
    // the number of core states is used for both POSIX and leftmost.
    ncores = stats(root);
}


bool TensorSliceReader::CopySliceData(const string& name,
                                      const TensorSlice& slice, T* data) const {
  std::vector<std::pair<TensorSlice, string>> details;
  const TensorSliceSet* tss;
  {
    mutex_lock l(mu_);
    tss = FindTensorSlice(name, slice, &details);
    if (!tss && !all_shards_loaded_) {
      VLOG(1) << "Did not find slice in preferred shard, loading all shards."
              << name << ": " << slice.DebugString();
      LoadAllShards();
      tss = FindTensorSlice(name, slice, &details);
    }
    if (!tss) {
      // No such tensor
      return false;
    }
  }
  // We have the data -- copy it over.
  string value;
  for (const auto& x : details) {
    const TensorSlice& slice_s = x.first;
    const string& fname = x.second;
    int idx = gtl::FindWithDefault(fname_to_index_, fname, -1);
    CHECK_GE(idx, 0) << "Failed to find the index for filename " << fname;
    // We read a record in the corresponding sstable
    const string key = EncodeTensorNameSlice(name, slice_s);
    if (!sss_[idx]->Get(key, &value)) {
      VLOG(1) << "Failed to seek to the record for tensor " << name
              << ", slice " << slice_s.DebugString()
              << ": computed key = " << key;
      return false;
    }
    SavedTensorSlices sts;
    if (!ParseProtoUnlimited(&sts, value)) {
      VLOG(1) << "Failed to parse the record for tensor " << name << ", slice "
              << slice_s.DebugString() << ": computed key = " << key;
      return false;
    }
    CopyDataFromTensorSliceToTensorSlice(
        tss->shape(), slice_s, slice,
        checkpoint::TensorProtoData<T>(sts.data().data()), data);
  }
  return true;
}


static struct matrix build_lut_matrix ( struct lutType * lut ) {
 struct matrix result ;
 if ( lut ) {
 result . m [ 0 ] [ 0 ] = s15Fixed16Number_to_float ( lut -> e00 ) ;
 result . m [ 0 ] [ 1 ] = s15Fixed16Number_to_float ( lut -> e01 ) ;
 result . m [ 0 ] [ 2 ] = s15Fixed16Number_to_float ( lut -> e02 ) ;
 result . m [ 1 ] [ 0 ] = s15Fixed16Number_to_float ( lut -> e10 ) ;
 result . m [ 1 ] [ 1 ] = s15Fixed16Number_to_float ( lut -> e11 ) ;
 result . m [ 1 ] [ 2 ] = s15Fixed16Number_to_float ( lut -> e12 ) ;
 result . m [ 2 ] [ 0 ] = s15Fixed16Number_to_float ( lut -> e20 ) ;
 result . m [ 2 ] [ 1 ] = s15Fixed16Number_to_float ( lut -> e21 ) ;
 result . m [ 2 ] [ 2 ] = s15Fixed16Number_to_float ( lut -> e22 ) ;
 result . invalid = false ;
 }
 else {
 memset ( & result , 0 , sizeof ( struct matrix ) ) ;
 result . invalid = true ;
 }
 return result ;
 }


void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque) { int i, found; WaitObjects *w = &wait_objects; found = 0; for (i = 0; i < w->num; i++) { if (w->events[i] == handle) found = 1; if (found) { w->events[i] = w->events[i + 1]; w->func[i] = w->func[i + 1]; w->opaque[i] = w->opaque[i + 1]; } } if (found) w->num--; }


static void s390_msi_ctrl_write(void *opaque, hwaddr addr, uint64_t data, unsigned int size) { S390PCIBusDevice *pbdev; uint32_t io_int_word; uint32_t fid = data >> ZPCI_MSI_VEC_BITS; uint32_t vec = data & ZPCI_MSI_VEC_MASK; uint64_t ind_bit; uint32_t sum_bit; uint32_t e = 0; DPRINTF("write_msix data 0x%" PRIx64 " fid %d vec 0x%x\n", data, fid, vec); pbdev = s390_pci_find_dev_by_fid(fid); if (!pbdev) { e |= (vec << ERR_EVENT_MVN_OFFSET); s390_pci_generate_error_event(ERR_EVENT_NOMSI, 0, fid, addr, e); return; } if (!(pbdev->fh & FH_MASK_ENABLE)) { return; } ind_bit = pbdev->routes.adapter.ind_offset; sum_bit = pbdev->routes.adapter.summary_offset; set_ind_atomic(pbdev->routes.adapter.ind_addr + (ind_bit + vec) / 8, 0x80 >> ((ind_bit + vec) % 8)); if (!set_ind_atomic(pbdev->routes.adapter.summary_addr + sum_bit / 8, 0x80 >> (sum_bit % 8))) { io_int_word = (pbdev->isc << 27) | IO_INT_WORD_AI; s390_io_interrupt(0, 0, 0, io_int_word); } }


proto_item * proto_tree_add_bytes_item ( proto_tree * tree , int hfindex , tvbuff_t * tvb , const gint start , gint length , const guint encoding , GByteArray * retval , gint * endoff , gint * err ) {
 field_info * new_fi ;
 GByteArray * bytes = retval ;
 GByteArray * created_bytes = NULL ;
 gint saved_err = 0 ;
 guint32 n = 0 ;
 header_field_info * hfinfo ;
 gboolean generate = ( bytes || tree ) ? TRUE : FALSE ;
 PROTO_REGISTRAR_GET_NTH ( hfindex , hfinfo ) ;
 DISSECTOR_ASSERT_HINT ( hfinfo != NULL , "Not passed hfi!" ) ;
 DISSECTOR_ASSERT_HINT ( validate_proto_tree_add_bytes_ftype ( hfinfo -> type ) , "Called proto_tree_add_bytes_item but not a bytes-based FT_XXX type" ) ;
 if ( length < - 1 || length == 0 ) {
 REPORT_DISSECTOR_BUG ( wmem_strdup_printf ( wmem_packet_scope ( ) , "Invalid length %d passed to proto_tree_add_bytes_item for %s" , length , ftype_name ( hfinfo -> type ) ) ) ;
 }
 if ( encoding & ENC_STR_NUM ) {
 REPORT_DISSECTOR_BUG ( "Decoding number strings for byte arrays is not supported" ) ;
 }
 if ( generate && ( encoding & ENC_STR_HEX ) ) {
 if ( hfinfo -> type == FT_UINT_BYTES ) {
 REPORT_DISSECTOR_BUG ( "proto_tree_add_bytes_item called for " "FT_UINT_BYTES type, but as ENC_STR_HEX" ) ;
 }
 if ( ! bytes ) {
 bytes = created_bytes = g_byte_array_new ( ) ;
 }
 bytes = tvb_get_string_bytes ( tvb , start , length , encoding , bytes , endoff ) ;
 saved_err = errno ;
 }
 else if ( generate ) {
 tvb_ensure_bytes_exist ( tvb , start , length ) ;
 if ( ! bytes ) {
 bytes = created_bytes = g_byte_array_new ( ) ;
 }
 if ( hfinfo -> type == FT_UINT_BYTES ) {
 n = length ;
 length = get_uint_value ( tree , tvb , start , n , encoding ) ;
 g_byte_array_append ( bytes , tvb_get_ptr ( tvb , start + n , length ) , length ) ;
 }
 else if ( length > 0 ) {
 g_byte_array_append ( bytes , tvb_get_ptr ( tvb , start , length ) , length ) ;
 }
 if ( endoff ) * endoff = start + n + length ;
 }
 if ( err ) * err = saved_err ;
 CHECK_FOR_NULL_TREE_AND_FREE ( tree , {
 if ( created_bytes ) g_byte_array_free ( created_bytes , TRUE ) ;
 created_bytes = NULL ;
 bytes = NULL ;
 }
 ) ;
 TRY_TO_FAKE_THIS_ITEM_OR_FREE ( tree , hfinfo -> id , hfinfo , {
 if ( created_bytes ) g_byte_array_free ( created_bytes , TRUE ) ;
 created_bytes = NULL ;
 bytes = NULL ;
 }
 ) ;
 new_fi = new_field_info ( tree , hfinfo , tvb , start , n + length ) ;
 if ( encoding & ENC_STRING ) {
 if ( saved_err == ERANGE ) expert_add_info ( NULL , tree , & ei_number_string_decoding_erange_error ) ;
 else if ( ! bytes || saved_err != 0 ) expert_add_info ( NULL , tree , & ei_number_string_decoding_failed_error ) ;
 if ( bytes ) proto_tree_set_bytes_gbytearray ( new_fi , bytes ) ;
 else proto_tree_set_bytes ( new_fi , NULL , 0 ) ;
 if ( created_bytes ) g_byte_array_free ( created_bytes , TRUE ) ;
 }
 else {
 proto_tree_set_bytes_tvb ( new_fi , tvb , start + n , length ) ;
 FI_SET_FLAG ( new_fi , ( encoding & ENC_LITTLE_ENDIAN ) ? FI_LITTLE_ENDIAN : FI_BIG_ENDIAN ) ;
 }
 return proto_tree_add_node ( tree , new_fi ) ;
 }


void pci_register_bar(PCIDevice *pci_dev, int region_num, pcibus_t size, int type, PCIMapIORegionFunc *map_func) { PCIIORegion *r; uint32_t addr; uint64_t wmask; if ((unsigned int)region_num >= PCI_NUM_REGIONS) return; if (size & (size-1)) { fprintf(stderr, "ERROR: PCI region size must be pow2 " "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size); exit(1); } r = &pci_dev->io_regions[region_num]; r->addr = PCI_BAR_UNMAPPED; r->size = size; r->filtered_size = size; r->type = type; r->map_func = map_func; wmask = ~(size - 1); addr = pci_bar(pci_dev, region_num); if (region_num == PCI_ROM_SLOT) { /* ROM enable bit is writeable */ wmask |= PCI_ROM_ADDRESS_ENABLE; } pci_set_long(pci_dev->config + addr, type); if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) && r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) { pci_set_quad(pci_dev->wmask + addr, wmask); pci_set_quad(pci_dev->cmask + addr, ~0ULL); } else { pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff); pci_set_long(pci_dev->cmask + addr, 0xffffffff); } }


int nft_parse_register_store(const struct nft_ctx *ctx,
			     const struct nlattr *attr, u8 *dreg,
			     const struct nft_data *data,
			     enum nft_data_types type, unsigned int len)
{
	int err;
	u32 reg;

	reg = nft_parse_register(attr);
	err = nft_validate_register_store(ctx, reg, data, type, len);
	if (err < 0)
		return err;

	*dreg = reg;
	return 0;
}


afs_int32 SPR_NameToID ( struct rx_call * call , namelist * aname , idlist * aid ) {
 afs_int32 code ;
 code = nameToID ( call , aname , aid ) ;
 osi_auditU ( call , PTS_NmToIdEvent , code , AUD_END ) ;
 ViceLog ( 125 , ( "PTS_NameToID: code %d\n" , code ) ) ;
 return code ;
 }


static int compare_floats(const float *a, const float *b, int len, float max_diff) { int i; for (i = 0; i < len; i++) { if (fabsf(a[i] - b[i]) > max_diff) { av_log(NULL, AV_LOG_ERROR, "%d: %- .12f - %- .12f = % .12g\n", i, a[i], b[i], a[i] - b[i]); return -1; } } return 0; }


static bool contain_nonstrict_functions_checker ( Oid func_id , void * context ) {
 return ! func_strict ( func_id ) ;
 }


static int dissect_h225_SecurityServiceMode ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_choice ( tvb , offset , actx , tree , hf_index , ett_h225_SecurityServiceMode , SecurityServiceMode_choice , NULL ) ;
 return offset ;
 }


TEST_F ( TemplateURLTest , GenerateKeyword ) {
 std : : string accept_languages = "en,ru" ;
 ASSERT_EQ ( ASCIIToUTF16 ( "foo" ) , TemplateURL : : GenerateKeyword ( GURL ( "http://foo" ) , accept_languages ) ) ;
 ASSERT_EQ ( ASCIIToUTF16 ( "foo" ) , TemplateURL : : GenerateKeyword ( GURL ( "http://www.foo" ) , accept_languages ) ) ;
 ASSERT_EQ ( ASCIIToUTF16 ( "blah" ) , TemplateURL : : GenerateKeyword ( GURL ( "http://blah/" ) , accept_languages ) ) ;
 ASSERT_EQ ( ASCIIToUTF16 ( "www" ) , TemplateURL : : GenerateKeyword ( GURL ( "http://www." ) , accept_languages ) ) ;
 ASSERT_EQ ( base : : UTF8ToUTF16 ( "\xd0\xb0\xd0\xb1\xd0\xb2" ) , TemplateURL : : GenerateKeyword ( GURL ( "http://xn--80acd" ) , accept_languages ) ) ;
 }


static void sbr_qmf_deint_neg_c ( float * v , const float * src ) {
 const union av_intfloat32 * si = ( const union av_intfloat32 * ) src ;
 union av_intfloat32 * vi = ( union av_intfloat32 * ) v ;
 int i ;
 for ( i = 0 ;
 i < 32 ;
 i ++ ) {
 vi [ i ] . i = si [ 63 - 2 * i ] . i ;
 vi [ 63 - i ] . i = si [ 63 - 2 * i - 1 ] . i ^ ( 1U << 31 ) ;
 }
 }


nand_write(void *opaque, target_phys_addr_t addr, uint64_t value, unsigned size) { struct nand_state_t *s = opaque; int rdy; DNAND(printf("%s addr=%x v=%x\n", __func__, addr, (unsigned)value)); nand_setpins(s->nand, s->cle, s->ale, s->ce, 1, 0); nand_setio(s->nand, value); nand_getpins(s->nand, &rdy); s->rdy = rdy; }


babel_packet_examin(const unsigned char *packet, int packetlen)
{
    unsigned i = 0, bodylen;
    const unsigned char *message;
    unsigned char type, len;

    if(packetlen < 4 || packet[0] != 42 || packet[1] != 2)
        return 1;
    DO_NTOHS(bodylen, packet + 2);
    while (i < bodylen){
        message = packet + 4 + i;
        type = message[0];
        if(type == MESSAGE_PAD1) {
            i++;
            continue;
        }
        if(i + 1 > bodylen) {
            debugf(BABEL_DEBUG_COMMON,"Received truncated message.");
            return 1;
        }
        len = message[1];
        if(i + len > bodylen) {
            debugf(BABEL_DEBUG_COMMON,"Received truncated message.");
            return 1;
        }
        /* not Pad1 */
        if(type <= MESSAGE_MAX && tlv_min_length[type] && len < tlv_min_length[type]) {
            debugf(BABEL_DEBUG_COMMON,"Undersized %u TLV", type);
            return 1;
        }
        i += len + 2;
    }
    return 0;
}


parse_hello_subtlv(const unsigned char *a, int alen,
                   unsigned int *hello_send_us)
{
    int type, len, i = 0, ret = 0;

    while(i < alen) {
        type = a[0];
        if(type == SUBTLV_PAD1) {
            i++;
            continue;
        }

        if(i + 1 > alen) {
            flog_err(EC_BABEL_PACKET,
		      "Received truncated sub-TLV on Hello message.");
            return -1;
        }
        len = a[i + 1];
        if(i + len > alen) {
            flog_err(EC_BABEL_PACKET,
		      "Received truncated sub-TLV on Hello message.");
            return -1;
        }

        if(type == SUBTLV_PADN) {
            /* Nothing to do. */
        } else if(type == SUBTLV_TIMESTAMP) {
            if(len >= 4) {
                DO_NTOHL(*hello_send_us, a + i + 2);
                ret = 1;
            } else {
                flog_err(EC_BABEL_PACKET,
			  "Received incorrect RTT sub-TLV on Hello message.");
            }
        } else {
            debugf(BABEL_DEBUG_COMMON,
                   "Received unknown Hello sub-TLV type %d.", type);
        }

        i += len + 2;
    }
    return ret;
}


void slurmctld_req ( slurm_msg_t * msg , connection_arg_t * arg ) {
 DEF_TIMERS ;
 int i , rpc_type_index = - 1 , rpc_user_index = - 1 ;
 uint32_t rpc_uid ;
 if ( arg && ( arg -> newsockfd >= 0 ) ) fd_set_nonblocking ( arg -> newsockfd ) ;
 # ifndef NDEBUG if ( ( msg -> flags & SLURM_DROP_PRIV ) ) drop_priv = true ;
 # endif rpc_uid = ( uint32_t ) g_slurm_auth_get_uid ( msg -> auth_cred , slurmctld_config . auth_info ) ;
 if ( g_slurm_auth_errno ( msg -> auth_cred ) != SLURM_SUCCESS ) {
 error ( "Bad authentication: %s" , g_slurm_auth_errstr ( g_slurm_auth_errno ( msg -> auth_cred ) ) ) ;
 return ;
 }
 slurm_mutex_lock ( & rpc_mutex ) ;
 if ( rpc_type_size == 0 ) {
 rpc_type_size = 100 ;
 rpc_type_id = xmalloc ( sizeof ( uint16_t ) * rpc_type_size ) ;
 rpc_type_cnt = xmalloc ( sizeof ( uint32_t ) * rpc_type_size ) ;
 rpc_type_time = xmalloc ( sizeof ( uint64_t ) * rpc_type_size ) ;
 }
 for ( i = 0 ;
 i < rpc_type_size ;
 i ++ ) {
 if ( rpc_type_id [ i ] == 0 ) rpc_type_id [ i ] = msg -> msg_type ;
 else if ( rpc_type_id [ i ] != msg -> msg_type ) continue ;
 rpc_type_index = i ;
 break ;
 }
 if ( rpc_user_size == 0 ) {
 rpc_user_size = 200 ;
 rpc_user_id = xmalloc ( sizeof ( uint32_t ) * rpc_user_size ) ;
 rpc_user_cnt = xmalloc ( sizeof ( uint32_t ) * rpc_user_size ) ;
 rpc_user_time = xmalloc ( sizeof ( uint64_t ) * rpc_user_size ) ;
 }
 for ( i = 0 ;
 i < rpc_user_size ;
 i ++ ) {
 if ( ( rpc_user_id [ i ] == 0 ) && ( i != 0 ) ) rpc_user_id [ i ] = rpc_uid ;
 else if ( rpc_user_id [ i ] != rpc_uid ) continue ;
 rpc_user_index = i ;
 break ;
 }
 slurm_mutex_unlock ( & rpc_mutex ) ;
 START_TIMER ;
 if ( slurmctld_conf . debug_flags & DEBUG_FLAG_PROTOCOL ) {
 char * p = rpc_num2string ( msg -> msg_type ) ;
 if ( msg -> conn ) {
 info ( "%s: received opcode %s from persist conn on (%s)%s" , __func__ , p , msg -> conn -> cluster_name , msg -> conn -> rem_host ) ;
 }
 else if ( arg ) {
 char inetbuf [ 64 ] ;
 slurm_print_slurm_addr ( & arg -> cli_addr , inetbuf , sizeof ( inetbuf ) ) ;
 info ( "%s: received opcode %s from %s" , __func__ , p , inetbuf ) ;
 }
 else {
 error ( "%s: No arg given and this doesn't appear to be a persistent connection, this should never happen" , __func__ ) ;
 }
 }
 switch ( msg -> msg_type ) {
 case REQUEST_RESOURCE_ALLOCATION : _slurm_rpc_allocate_resources ( msg ) ;
 break ;
 case REQUEST_JOB_PACK_ALLOCATION : _slurm_rpc_allocate_pack ( msg ) ;
 break ;
 case REQUEST_BUILD_INFO : _slurm_rpc_dump_conf ( msg ) ;
 break ;
 case REQUEST_JOB_INFO : _slurm_rpc_dump_jobs ( msg ) ;
 break ;
 case REQUEST_JOB_USER_INFO : _slurm_rpc_dump_jobs_user ( msg ) ;
 break ;
 case REQUEST_JOB_INFO_SINGLE : _slurm_rpc_dump_job_single ( msg ) ;
 break ;
 case REQUEST_BATCH_SCRIPT : _slurm_rpc_dump_batch_script ( msg ) ;
 break ;
 case REQUEST_SHARE_INFO : _slurm_rpc_get_shares ( msg ) ;
 break ;
 case REQUEST_PRIORITY_FACTORS : _slurm_rpc_get_priority_factors ( msg ) ;
 break ;
 case REQUEST_JOB_END_TIME : _slurm_rpc_end_time ( msg ) ;
 break ;
 case REQUEST_FED_INFO : _slurm_rpc_get_fed ( msg ) ;
 break ;
 case REQUEST_FRONT_END_INFO : _slurm_rpc_dump_front_end ( msg ) ;
 break ;
 case REQUEST_NODE_INFO : _slurm_rpc_dump_nodes ( msg ) ;
 break ;
 case REQUEST_NODE_INFO_SINGLE : _slurm_rpc_dump_node_single ( msg ) ;
 break ;
 case REQUEST_PARTITION_INFO : _slurm_rpc_dump_partitions ( msg ) ;
 break ;
 case MESSAGE_EPILOG_COMPLETE : i = 0 ;
 _slurm_rpc_epilog_complete ( msg , ( bool * ) & i , 0 ) ;
 break ;
 case REQUEST_CANCEL_JOB_STEP : _slurm_rpc_job_step_kill ( rpc_uid , msg ) ;
 break ;
 case REQUEST_COMPLETE_JOB_ALLOCATION : _slurm_rpc_complete_job_allocation ( msg ) ;
 break ;
 case REQUEST_COMPLETE_PROLOG : _slurm_rpc_complete_prolog ( msg ) ;
 break ;
 case REQUEST_COMPLETE_BATCH_JOB : case REQUEST_COMPLETE_BATCH_SCRIPT : i = 0 ;
 _slurm_rpc_complete_batch_script ( msg , ( bool * ) & i , 0 ) ;
 break ;
 case REQUEST_JOB_STEP_CREATE : _slurm_rpc_job_step_create ( msg ) ;
 break ;
 case REQUEST_JOB_STEP_INFO : _slurm_rpc_job_step_get_info ( msg ) ;
 break ;
 case REQUEST_JOB_WILL_RUN : _slurm_rpc_job_will_run ( msg ) ;
 break ;
 case REQUEST_SIB_JOB_LOCK : _slurm_rpc_sib_job_lock ( rpc_uid , msg ) ;
 break ;
 case REQUEST_SIB_JOB_UNLOCK : _slurm_rpc_sib_job_unlock ( rpc_uid , msg ) ;
 break ;
 case REQUEST_CTLD_MULT_MSG : _proc_multi_msg ( rpc_uid , msg ) ;
 break ;
 case MESSAGE_NODE_REGISTRATION_STATUS : _slurm_rpc_node_registration ( msg , 0 ) ;
 break ;
 case REQUEST_JOB_ALLOCATION_INFO : case DEFUNCT_REQUEST_JOB_ALLOCATION_INFO_LITE : _slurm_rpc_job_alloc_info ( msg ) ;
 break ;
 case REQUEST_JOB_PACK_ALLOC_INFO : _slurm_rpc_job_pack_alloc_info ( msg ) ;
 break ;
 case REQUEST_JOB_SBCAST_CRED : _slurm_rpc_job_sbcast_cred ( msg ) ;
 break ;
 case REQUEST_PING : _slurm_rpc_ping ( msg ) ;
 break ;
 case REQUEST_RECONFIGURE : _slurm_rpc_reconfigure_controller ( msg ) ;
 break ;
 case REQUEST_CONTROL : _slurm_rpc_shutdown_controller ( msg ) ;
 break ;
 case REQUEST_TAKEOVER : _slurm_rpc_takeover ( msg ) ;
 break ;
 case REQUEST_SHUTDOWN : _slurm_rpc_shutdown_controller ( msg ) ;
 break ;
 case REQUEST_SHUTDOWN_IMMEDIATE : _slurm_rpc_shutdown_controller_immediate ( msg ) ;
 break ;
 case REQUEST_SUBMIT_BATCH_JOB : _slurm_rpc_submit_batch_job ( msg ) ;
 break ;
 case REQUEST_SUBMIT_BATCH_JOB_PACK : _slurm_rpc_submit_batch_pack_job ( msg ) ;
 break ;
 case REQUEST_UPDATE_FRONT_END : _slurm_rpc_update_front_end ( msg ) ;
 break ;
 case REQUEST_UPDATE_JOB : _slurm_rpc_update_job ( msg ) ;
 break ;
 case REQUEST_UPDATE_NODE : _slurm_rpc_update_node ( msg ) ;
 break ;
 case REQUEST_UPDATE_LAYOUT : _slurm_rpc_update_layout ( msg ) ;
 break ;
 case REQUEST_CREATE_PARTITION : case REQUEST_UPDATE_PARTITION : _slurm_rpc_update_partition ( msg ) ;
 break ;
 case REQUEST_UPDATE_POWERCAP : _slurm_rpc_update_powercap ( msg ) ;
 break ;
 case REQUEST_DELETE_PARTITION : _slurm_rpc_delete_partition ( msg ) ;
 break ;
 case REQUEST_CREATE_RESERVATION : _slurm_rpc_resv_create ( msg ) ;
 break ;
 case REQUEST_UPDATE_RESERVATION : _slurm_rpc_resv_update ( msg ) ;
 break ;
 case REQUEST_DELETE_RESERVATION : _slurm_rpc_resv_delete ( msg ) ;
 break ;
 case REQUEST_UPDATE_BLOCK : _slurm_rpc_update_block ( msg ) ;
 break ;
 case REQUEST_RESERVATION_INFO : _slurm_rpc_resv_show ( msg ) ;
 break ;
 case REQUEST_LAYOUT_INFO : _slurm_rpc_layout_show ( msg ) ;
 break ;
 case REQUEST_NODE_REGISTRATION_STATUS : error ( "slurmctld is talking with itself. " "SlurmctldPort == SlurmdPort" ) ;
 slurm_send_rc_msg ( msg , EINVAL ) ;
 break ;
 case REQUEST_CHECKPOINT : _slurm_rpc_checkpoint ( msg ) ;
 break ;
 case REQUEST_CHECKPOINT_COMP : _slurm_rpc_checkpoint_comp ( msg ) ;
 break ;
 case REQUEST_CHECKPOINT_TASK_COMP : _slurm_rpc_checkpoint_task_comp ( msg ) ;
 break ;
 case REQUEST_SUSPEND : _slurm_rpc_suspend ( msg ) ;
 break ;
 case REQUEST_TOP_JOB : _slurm_rpc_top_job ( msg ) ;
 break ;
 case REQUEST_JOB_REQUEUE : _slurm_rpc_requeue ( msg ) ;
 break ;
 case REQUEST_JOB_READY : _slurm_rpc_job_ready ( msg ) ;
 break ;
 case REQUEST_BLOCK_INFO : _slurm_rpc_block_info ( msg ) ;
 break ;
 case REQUEST_BURST_BUFFER_INFO : _slurm_rpc_burst_buffer_info ( msg ) ;
 break ;
 case REQUEST_STEP_COMPLETE : _slurm_rpc_step_complete ( msg , 0 ) ;
 break ;
 case REQUEST_STEP_LAYOUT : _slurm_rpc_step_layout ( msg ) ;
 break ;
 case REQUEST_UPDATE_JOB_STEP : _slurm_rpc_step_update ( msg ) ;
 break ;
 case REQUEST_TRIGGER_SET : _slurm_rpc_trigger_set ( msg ) ;
 break ;
 case REQUEST_TRIGGER_GET : _slurm_rpc_trigger_get ( msg ) ;
 break ;
 case REQUEST_TRIGGER_CLEAR : _slurm_rpc_trigger_clear ( msg ) ;
 break ;
 case REQUEST_TRIGGER_PULL : _slurm_rpc_trigger_pull ( msg ) ;
 break ;
 case REQUEST_JOB_NOTIFY : _slurm_rpc_job_notify ( msg ) ;
 break ;
 case REQUEST_SET_DEBUG_FLAGS : _slurm_rpc_set_debug_flags ( msg ) ;
 break ;
 case REQUEST_SET_DEBUG_LEVEL : _slurm_rpc_set_debug_level ( msg ) ;
 break ;
 case REQUEST_SET_SCHEDLOG_LEVEL : _slurm_rpc_set_schedlog_level ( msg ) ;
 break ;
 case ACCOUNTING_UPDATE_MSG : _slurm_rpc_accounting_update_msg ( msg ) ;
 break ;
 case ACCOUNTING_FIRST_REG : _slurm_rpc_accounting_first_reg ( msg ) ;
 break ;
 case ACCOUNTING_REGISTER_CTLD : _slurm_rpc_accounting_register_ctld ( msg ) ;
 break ;
 case REQUEST_TOPO_INFO : _slurm_rpc_get_topo ( msg ) ;
 break ;
 case REQUEST_POWERCAP_INFO : _slurm_rpc_get_powercap ( msg ) ;
 break ;
 case REQUEST_SPANK_ENVIRONMENT : _slurm_rpc_dump_spank ( msg ) ;
 break ;
 case REQUEST_REBOOT_NODES : _slurm_rpc_reboot_nodes ( msg ) ;
 break ;
 case REQUEST_STATS_INFO : _slurm_rpc_dump_stats ( msg ) ;
 break ;
 case REQUEST_LICENSE_INFO : _slurm_rpc_dump_licenses ( msg ) ;
 break ;
 case REQUEST_KILL_JOB : _slurm_rpc_kill_job ( msg ) ;
 break ;
 case MESSAGE_COMPOSITE : _slurm_rpc_composite_msg ( msg ) ;
 break ;
 case REQUEST_ASSOC_MGR_INFO : _slurm_rpc_assoc_mgr_info ( msg ) ;
 break ;
 case REQUEST_PERSIST_INIT : if ( msg -> conn ) error ( "We already have a persistent connect, this should never happen" ) ;
 _slurm_rpc_persist_init ( msg , arg ) ;
 break ;
 case REQUEST_EVENT_LOG : _slurm_rpc_event_log ( msg ) ;
 break ;
 case REQUEST_SET_FS_DAMPENING_FACTOR : _slurm_rpc_set_fs_dampening_factor ( msg ) ;
 break ;
 default : error ( "invalid RPC msg_type=%u" , msg -> msg_type ) ;
 slurm_send_rc_msg ( msg , EINVAL ) ;
 break ;
 }
 END_TIMER ;
 slurm_mutex_lock ( & rpc_mutex ) ;
 if ( rpc_type_index >= 0 ) {
 rpc_type_cnt [ rpc_type_index ] ++ ;
 rpc_type_time [ rpc_type_index ] += DELTA_TIMER ;
 }
 if ( rpc_user_index >= 0 ) {
 rpc_user_cnt [ rpc_user_index ] ++ ;
 rpc_user_time [ rpc_user_index ] += DELTA_TIMER ;
 }
 slurm_mutex_unlock ( & rpc_mutex ) ;
 }


static void read_coef_probs ( FRAME_CONTEXT * fc , TX_MODE tx_mode , vp9_reader * r ) {
 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size [ tx_mode ] ;
 TX_SIZE tx_size ;
 for ( tx_size = TX_4X4 ;
 tx_size <= max_tx_size ;
 ++ tx_size ) read_coef_probs_common ( fc -> coef_probs [ tx_size ] , r ) ;
 }


fast_edit_packet(struct pcap_pkthdr *pkthdr, u_char **pktdata,
        COUNTER iteration, bool cached, int datalink)
{
    uint32_t pkt_len = pkthdr->caplen;
    u_char *packet = *pktdata;
    ipv4_hdr_t *ip_hdr = NULL;
    ipv6_hdr_t *ip6_hdr = NULL;
    uint32_t src_ip, dst_ip;
    uint32_t src_ip_orig, dst_ip_orig;
    uint32_t _U_ vlan_offset;
    uint16_t ether_type;
    uint32_t l2offset;
    uint32_t l2len;
    int res;

    res = get_l2len_protocol(packet,
                             pkt_len,
                             datalink,
                             &ether_type,
                             &l2len,
                             &l2offset,
                             &vlan_offset);

    if (res < 0)
        return res;

    packet += l2offset;
    l2len -= l2offset;
    pkt_len -= l2offset;

    assert(l2len > 0);

    switch (ether_type) {
    case ETHERTYPE_IP:
        if (pkt_len < (bpf_u_int32)(l2len + sizeof(ipv4_hdr_t))) {
            dbgx(1, "IP packet too short for Unique IP feature: %u", pkthdr->caplen);
            return -1;
        }
        ip_hdr = (ipv4_hdr_t *)(packet + l2len);
        src_ip_orig = src_ip = ntohl(ip_hdr->ip_src.s_addr);
        dst_ip_orig = dst_ip = ntohl(ip_hdr->ip_dst.s_addr);
        break;

    case ETHERTYPE_IP6:
        if (pkt_len < (bpf_u_int32)(l2len + sizeof(ipv6_hdr_t))) {
            dbgx(1, "IP6 packet too short for Unique IP feature: %u", pkthdr->caplen);
            return -1;
        }
        ip6_hdr = (ipv6_hdr_t *)(packet + l2len);
        src_ip_orig = src_ip = ntohl(ip6_hdr->ip_src.__u6_addr.__u6_addr32[3]);
        dst_ip_orig = dst_ip = ntohl(ip6_hdr->ip_dst.__u6_addr.__u6_addr32[3]);
        break;

    default:
        return -1; /* non-IP or packet too short */
    }

    dbgx(2, "Layer 3 protocol type is: 0x%04x", ether_type);

    /* swap src/dst IP's in a manner that does not affect CRC */
    if ((!cached && dst_ip > src_ip) ||
            (cached && (dst_ip - iteration) > (src_ip - 1 - iteration))) {
        if (cached) {
            --src_ip;
            ++dst_ip;
        } else {
            src_ip -= iteration;
            dst_ip += iteration;
        }

        /* CRC compensations  for wrap conditions */
        if (src_ip > src_ip_orig && dst_ip > dst_ip_orig) {
            dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): before(1) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip);
            --src_ip;
            dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): after(1)  src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip);
        } else if (dst_ip < dst_ip_orig && src_ip < src_ip_orig) {
            dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): before(2) src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip);
            ++dst_ip;
            dbgx(1, "dst_ip > src_ip(" COUNTER_SPEC "): after(2)  src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip);
        }
    } else {
        if (cached) {
            ++src_ip;
            --dst_ip;
        } else {
            src_ip += iteration;
            dst_ip -= iteration;
        }

        /* CRC compensations  for wrap conditions */
        if (dst_ip > dst_ip_orig && src_ip > src_ip_orig) {
            dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): before(1) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip);
            --dst_ip;
            dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): after(1)  dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip);
        } else if (src_ip < src_ip_orig && dst_ip < dst_ip_orig) {
            dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): before(2) dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip);
            ++src_ip;
            dbgx(1, "src_ip > dst_ip(" COUNTER_SPEC "): after(2)  dst_ip=0x%08x src_ip=0x%08x", iteration, dst_ip, src_ip);
        }
    }

    dbgx(1, "(" COUNTER_SPEC "): final src_ip=0x%08x dst_ip=0x%08x", iteration, src_ip, dst_ip);

    switch (ether_type) {
    case ETHERTYPE_IP:
        ip_hdr->ip_src.s_addr = htonl(src_ip);
        ip_hdr->ip_dst.s_addr = htonl(dst_ip);
        break;

    case ETHERTYPE_IP6:
        ip6_hdr->ip_src.__u6_addr.__u6_addr32[3] = htonl(src_ip);
        ip6_hdr->ip_dst.__u6_addr.__u6_addr32[3] = htonl(dst_ip);
        break;
    }

    return 0;
}