static int decode_subframe ( WMAProDecodeCtx * s ) {
 int offset = s -> samples_per_frame ;
 int subframe_len = s -> samples_per_frame ;
 int i ;
 int total_samples = s -> samples_per_frame * s -> avctx -> channels ;
 int transmit_coeffs = 0 ;
 int cur_subwoofer_cutoff ;
 s -> subframe_offset = get_bits_count ( & s -> gb ) ;
 for ( i = 0 ;
 i < s -> avctx -> channels ;
 i ++ ) {
 s -> channel [ i ] . grouped = 0 ;
 if ( offset > s -> channel [ i ] . decoded_samples ) {
 offset = s -> channel [ i ] . decoded_samples ;
 subframe_len = s -> channel [ i ] . subframe_len [ s -> channel [ i ] . cur_subframe ] ;
 }
 }
 av_dlog ( s -> avctx , "processing subframe with offset %i len %i\n" , offset , subframe_len ) ;
 s -> channels_for_cur_subframe = 0 ;
 for ( i = 0 ;
 i < s -> avctx -> channels ;
 i ++ ) {
 const int cur_subframe = s -> channel [ i ] . cur_subframe ;
 total_samples -= s -> channel [ i ] . decoded_samples ;
 if ( offset == s -> channel [ i ] . decoded_samples && subframe_len == s -> channel [ i ] . subframe_len [ cur_subframe ] ) {
 total_samples -= s -> channel [ i ] . subframe_len [ cur_subframe ] ;
 s -> channel [ i ] . decoded_samples += s -> channel [ i ] . subframe_len [ cur_subframe ] ;
 s -> channel_indexes_for_cur_subframe [ s -> channels_for_cur_subframe ] = i ;
 ++ s -> channels_for_cur_subframe ;
 }
 }
 if ( ! total_samples ) s -> parsed_all_subframes = 1 ;
 av_dlog ( s -> avctx , "subframe is part of %i channels\n" , s -> channels_for_cur_subframe ) ;
 s -> table_idx = av_log2 ( s -> samples_per_frame / subframe_len ) ;
 s -> num_bands = s -> num_sfb [ s -> table_idx ] ;
 s -> cur_sfb_offsets = s -> sfb_offsets [ s -> table_idx ] ;
 cur_subwoofer_cutoff = s -> subwoofer_cutoffs [ s -> table_idx ] ;
 for ( i = 0 ;
 i < s -> channels_for_cur_subframe ;
 i ++ ) {
 int c = s -> channel_indexes_for_cur_subframe [ i ] ;
 s -> channel [ c ] . coeffs = & s -> channel [ c ] . out [ ( s -> samples_per_frame >> 1 ) + offset ] ;
 }
 s -> subframe_len = subframe_len ;
 s -> esc_len = av_log2 ( s -> subframe_len - 1 ) + 1 ;
 if ( get_bits1 ( & s -> gb ) ) {
 int num_fill_bits ;
 if ( ! ( num_fill_bits = get_bits ( & s -> gb , 2 ) ) ) {
 int len = get_bits ( & s -> gb , 4 ) ;
 num_fill_bits = get_bits ( & s -> gb , len ) + 1 ;
 }
 if ( num_fill_bits >= 0 ) {
 if ( get_bits_count ( & s -> gb ) + num_fill_bits > s -> num_saved_bits ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "invalid number of fill bits\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 skip_bits_long ( & s -> gb , num_fill_bits ) ;
 }
 }
 if ( get_bits1 ( & s -> gb ) ) {
 av_log_ask_for_sample ( s -> avctx , "reserved bit set\n" ) ;
 return AVERROR_PATCHWELCOME ;
 }
 if ( decode_channel_transform ( s ) < 0 ) return AVERROR_INVALIDDATA ;
 for ( i = 0 ;
 i < s -> channels_for_cur_subframe ;
 i ++ ) {
 int c = s -> channel_indexes_for_cur_subframe [ i ] ;
 if ( ( s -> channel [ c ] . transmit_coefs = get_bits1 ( & s -> gb ) ) ) transmit_coeffs = 1 ;
 }
 if ( transmit_coeffs ) {
 int step ;
 int quant_step = 90 * s -> bits_per_sample >> 4 ;
 if ( ( s -> transmit_num_vec_coeffs = get_bits1 ( & s -> gb ) ) ) {
 int num_bits = av_log2 ( ( s -> subframe_len + 3 ) / 4 ) + 1 ;
 for ( i = 0 ;
 i < s -> channels_for_cur_subframe ;
 i ++ ) {
 int c = s -> channel_indexes_for_cur_subframe [ i ] ;
 int num_vec_coeffs = get_bits ( & s -> gb , num_bits ) << 2 ;
 if ( num_vec_coeffs > WMAPRO_BLOCK_MAX_SIZE ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "num_vec_coeffs %d is too large\n" , num_vec_coeffs ) ;
 return AVERROR_INVALIDDATA ;
 }
 s -> channel [ c ] . num_vec_coeffs = num_vec_coeffs ;
 }
 }
 else {
 for ( i = 0 ;
 i < s -> channels_for_cur_subframe ;
 i ++ ) {
 int c = s -> channel_indexes_for_cur_subframe [ i ] ;
 s -> channel [ c ] . num_vec_coeffs = s -> subframe_len ;
 }
 }
 step = get_sbits ( & s -> gb , 6 ) ;
 quant_step += step ;
 if ( step == - 32 || step == 31 ) {
 const int sign = ( step == 31 ) - 1 ;
 int quant = 0 ;
 while ( get_bits_count ( & s -> gb ) + 5 < s -> num_saved_bits && ( step = get_bits ( & s -> gb , 5 ) ) == 31 ) {
 quant += 31 ;
 }
 quant_step += ( ( quant + step ) ^ sign ) - sign ;
 }
 if ( quant_step < 0 ) {
 av_log ( s -> avctx , AV_LOG_DEBUG , "negative quant step\n" ) ;
 }
 if ( s -> channels_for_cur_subframe == 1 ) {
 s -> channel [ s -> channel_indexes_for_cur_subframe [ 0 ] ] . quant_step = quant_step ;
 }
 else {
 int modifier_len = get_bits ( & s -> gb , 3 ) ;
 for ( i = 0 ;
 i < s -> channels_for_cur_subframe ;
 i ++ ) {
 int c = s -> channel_indexes_for_cur_subframe [ i ] ;
 s -> channel [ c ] . quant_step = quant_step ;
 if ( get_bits1 ( & s -> gb ) ) {
 if ( modifier_len ) {
 s -> channel [ c ] . quant_step += get_bits ( & s -> gb , modifier_len ) + 1 ;
 }
 else ++ s -> channel [ c ] . quant_step ;
 }
 }
 }
 if ( decode_scale_factors ( s ) < 0 ) return AVERROR_INVALIDDATA ;
 }
 av_dlog ( s -> avctx , "BITSTREAM: subframe header length was %i\n" , get_bits_count ( & s -> gb ) - s -> subframe_offset ) ;
 for ( i = 0 ;
 i < s -> channels_for_cur_subframe ;
 i ++ ) {
 int c = s -> channel_indexes_for_cur_subframe [ i ] ;
 if ( s -> channel [ c ] . transmit_coefs && get_bits_count ( & s -> gb ) < s -> num_saved_bits ) {
 decode_coeffs ( s , c ) ;
 }
 else memset ( s -> channel [ c ] . coeffs , 0 , sizeof ( * s -> channel [ c ] . coeffs ) * subframe_len ) ;
 }
 av_dlog ( s -> avctx , "BITSTREAM: subframe length was %i\n" , get_bits_count ( & s -> gb ) - s -> subframe_offset ) ;
 if ( transmit_coeffs ) {
 FFTContext * mdct = & s -> mdct_ctx [ av_log2 ( subframe_len ) - WMAPRO_BLOCK_MIN_BITS ] ;
 inverse_channel_transform ( s ) ;
 for ( i = 0 ;
 i < s -> channels_for_cur_subframe ;
 i ++ ) {
 int c = s -> channel_indexes_for_cur_subframe [ i ] ;
 const int * sf = s -> channel [ c ] . scale_factors ;
 int b ;
 if ( c == s -> lfe_channel ) memset ( & s -> tmp [ cur_subwoofer_cutoff ] , 0 , sizeof ( * s -> tmp ) * ( subframe_len - cur_subwoofer_cutoff ) ) ;
 for ( b = 0 ;
 b < s -> num_bands ;
 b ++ ) {
 const int end = FFMIN ( s -> cur_sfb_offsets [ b + 1 ] , s -> subframe_len ) ;
 const int exp = s -> channel [ c ] . quant_step - ( s -> channel [ c ] . max_scale_factor - * sf ++ ) * s -> channel [ c ] . scale_factor_step ;
 const float quant = pow ( 10.0 , exp / 20.0 ) ;
 int start = s -> cur_sfb_offsets [ b ] ;
 s -> fdsp . vector_fmul_scalar ( s -> tmp + start , s -> channel [ c ] . coeffs + start , quant , end - start ) ;
 }
 mdct -> imdct_half ( mdct , s -> channel [ c ] . coeffs , s -> tmp ) ;
 }
 }
 wmapro_window ( s ) ;
 for ( i = 0 ;
 i < s -> channels_for_cur_subframe ;
 i ++ ) {
 int c = s -> channel_indexes_for_cur_subframe [ i ] ;
 if ( s -> channel [ c ] . cur_subframe >= s -> channel [ c ] . num_subframes ) {
 av_log ( s -> avctx , AV_LOG_ERROR , "broken subframe\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 ++ s -> channel [ c ] . cur_subframe ;
 }
 return 0 ;
 }


void pdo_stmt_init(TSRMLS_D)
{
	zend_class_entry ce;

	INIT_CLASS_ENTRY(ce, "PDOStatement", pdo_dbstmt_functions);
	pdo_dbstmt_ce = zend_register_internal_class(&ce TSRMLS_CC);
	pdo_dbstmt_ce->get_iterator = pdo_stmt_iter_get;
	pdo_dbstmt_ce->create_object = pdo_dbstmt_new;
	zend_class_implements(pdo_dbstmt_ce TSRMLS_CC, 1, zend_ce_traversable);
	zend_declare_property_null(pdo_dbstmt_ce, "queryString", sizeof("queryString")-1, ZEND_ACC_PUBLIC TSRMLS_CC);

	memcpy(&pdo_dbstmt_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
	pdo_dbstmt_object_handlers.write_property = dbstmt_prop_write;
	pdo_dbstmt_object_handlers.unset_property = dbstmt_prop_delete;
	pdo_dbstmt_object_handlers.get_method = dbstmt_method_get;
	pdo_dbstmt_object_handlers.compare_objects = dbstmt_compare;
	pdo_dbstmt_object_handlers.clone_obj = dbstmt_clone_obj;

	INIT_CLASS_ENTRY(ce, "PDORow", pdo_row_functions);
	pdo_row_ce = zend_register_internal_class(&ce TSRMLS_CC);
	pdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */
	pdo_row_ce->create_object = pdo_row_new;
	pdo_row_ce->serialize = pdo_row_serialize;


build_append_notify(GArray *device, const char *name, const char *format, int skip, int count) { int i; GArray *method = build_alloc_array(); uint8_t op = 0x14; /* MethodOp */ build_append_nameseg(method, "%s", name); build_append_byte(method, 0x02); /* MethodFlags: ArgCount */ for (i = skip; i < count; i++) { GArray *target = build_alloc_array(); build_append_nameseg(target, format, i); assert(i < 256); /* Fits in 1 byte */ build_append_notify_target(method, target, i, 1); build_free_array(target); } build_package(method, op, 2); build_append_array(device, method); build_free_array(method); }


static void machine_numa_validate(MachineState *machine) { int i; GString *s = g_string_new(NULL); MachineClass *mc = MACHINE_GET_CLASS(machine); const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(machine); assert(nb_numa_nodes); for (i = 0; i < possible_cpus->len; i++) { const CPUArchId *cpu_slot = &possible_cpus->cpus[i]; /* at this point numa mappings are initilized by CLI options * or with default mappings so it's sufficient to list * all not yet mapped CPUs here */ /* TODO: make it hard error in future */ if (!cpu_slot->props.has_node_id) { char *cpu_str = cpu_slot_to_string(cpu_slot); g_string_append_printf(s, "%sCPU %d [%s]", s->len ? ", " : "", i, cpu_str); g_free(cpu_str); } } if (s->len) { error_report("warning: CPU(s) not present in any NUMA nodes: %s", s->str); error_report("warning: All CPU(s) up to maxcpus should be described " "in NUMA config, ability to start up with partial NUMA " "mappings is obsoleted and will be removed in future"); } g_string_free(s, true); }


static void imc_adjust_bit_allocation ( IMCContext * q , IMCChannel * chctx , int summer ) {
 float workT [ 32 ] ;
 int corrected = 0 ;
 int i , j ;
 float highest = 0 ;
 int found_indx = 0 ;
 for ( i = 0 ;
 i < BANDS ;
 i ++ ) {
 workT [ i ] = ( chctx -> bitsBandT [ i ] == 6 ) ? - 1.e20 : ( chctx -> bitsBandT [ i ] * - 2 + chctx -> flcoeffs4 [ i ] - 0.415 ) ;
 }
 while ( corrected < summer ) {
 if ( highest <= - 1.e20 ) break ;
 highest = - 1.e20 ;
 for ( i = 0 ;
 i < BANDS ;
 i ++ ) {
 if ( workT [ i ] > highest ) {
 highest = workT [ i ] ;
 found_indx = i ;
 }
 }
 if ( highest > - 1.e20 ) {
 workT [ found_indx ] -= 2.0 ;
 if ( ++ ( chctx -> bitsBandT [ found_indx ] ) == 6 ) workT [ found_indx ] = - 1.e20 ;
 for ( j = band_tab [ found_indx ] ;
 j < band_tab [ found_indx + 1 ] && ( corrected < summer ) ;
 j ++ ) {
 if ( ! chctx -> skipFlags [ j ] && ( chctx -> CWlengthT [ j ] < 6 ) ) {
 chctx -> CWlengthT [ j ] ++ ;
 corrected ++ ;
 }
 }
 }
 }
 }


double estimate_num_groups ( PlannerInfo * root , List * groupExprs , double input_rows , List * * pgset ) {
 List * varinfos = NIL ;
 double numdistinct ;
 ListCell * l ;
 int i ;
 input_rows = clamp_row_est ( input_rows ) ;
 if ( groupExprs == NIL || ( pgset && list_length ( * pgset ) < 1 ) ) return 1.0 ;
 numdistinct = 1.0 ;
 i = 0 ;
 foreach ( l , groupExprs ) {
 Node * groupexpr = ( Node * ) lfirst ( l ) ;
 VariableStatData vardata ;
 List * varshere ;
 ListCell * l2 ;
 if ( pgset && ! list_member_int ( * pgset , i ++ ) ) continue ;
 if ( exprType ( groupexpr ) == BOOLOID ) {
 numdistinct *= 2.0 ;
 continue ;
 }
 examine_variable ( root , groupexpr , 0 , & vardata ) ;
 if ( HeapTupleIsValid ( vardata . statsTuple ) || vardata . isunique ) {
 varinfos = add_unique_group_var ( root , varinfos , groupexpr , & vardata ) ;
 ReleaseVariableStats ( vardata ) ;
 continue ;
 }
 ReleaseVariableStats ( vardata ) ;
 varshere = pull_var_clause ( groupexpr , PVC_RECURSE_AGGREGATES | PVC_RECURSE_WINDOWFUNCS | PVC_RECURSE_PLACEHOLDERS ) ;
 if ( varshere == NIL ) {
 if ( contain_volatile_functions ( groupexpr ) ) return input_rows ;
 continue ;
 }
 foreach ( l2 , varshere ) {
 Node * var = ( Node * ) lfirst ( l2 ) ;
 examine_variable ( root , var , 0 , & vardata ) ;
 varinfos = add_unique_group_var ( root , varinfos , var , & vardata ) ;
 ReleaseVariableStats ( vardata ) ;
 }
 }
 if ( varinfos == NIL ) {
 if ( numdistinct > input_rows ) numdistinct = input_rows ;
 return numdistinct ;
 }
 do {
 GroupVarInfo * varinfo1 = ( GroupVarInfo * ) linitial ( varinfos ) ;
 RelOptInfo * rel = varinfo1 -> rel ;
 double reldistinct = varinfo1 -> ndistinct ;
 double relmaxndistinct = reldistinct ;
 int relvarcount = 1 ;
 List * newvarinfos = NIL ;
 for_each_cell ( l , lnext ( list_head ( varinfos ) ) ) {
 GroupVarInfo * varinfo2 = ( GroupVarInfo * ) lfirst ( l ) ;
 if ( varinfo2 -> rel == varinfo1 -> rel ) {
 reldistinct *= varinfo2 -> ndistinct ;
 if ( relmaxndistinct < varinfo2 -> ndistinct ) relmaxndistinct = varinfo2 -> ndistinct ;
 relvarcount ++ ;
 }
 else {
 newvarinfos = lcons ( varinfo2 , newvarinfos ) ;
 }
 }
 Assert ( rel -> reloptkind == RELOPT_BASEREL ) ;
 if ( rel -> tuples > 0 ) {
 double clamp = rel -> tuples ;
 if ( relvarcount > 1 ) {
 clamp *= 0.1 ;
 if ( clamp < relmaxndistinct ) {
 clamp = relmaxndistinct ;
 if ( clamp > rel -> tuples ) clamp = rel -> tuples ;
 }
 }
 if ( reldistinct > clamp ) reldistinct = clamp ;
 if ( reldistinct > 0 && rel -> rows < rel -> tuples ) {
 reldistinct *= ( 1 - pow ( ( rel -> tuples - rel -> rows ) / rel -> tuples , rel -> tuples / reldistinct ) ) ;
 }
 reldistinct = clamp_row_est ( reldistinct ) ;
 numdistinct *= reldistinct ;
 }
 varinfos = newvarinfos ;
 }
 while ( varinfos != NIL ) ;
 numdistinct = ceil ( numdistinct ) ;
 if ( numdistinct > input_rows ) numdistinct = input_rows ;
 if ( numdistinct < 1.0 ) numdistinct = 1.0 ;
 return numdistinct ;
 }


void vp9_rc_postencode_update_drop_frame ( VP9_COMP * cpi ) {
 update_buffer_level ( cpi , 0 ) ;
 cpi -> common . last_frame_type = cpi -> common . frame_type ;
 cpi -> rc . frames_since_key ++ ;
 cpi -> rc . frames_to_key -- ;
 }


static inline void mv_pred_direct ( AVSContext * h , cavs_vector * pmv_fw , cavs_vector * col_mv ) {
 cavs_vector * pmv_bw = pmv_fw + MV_BWD_OFFS ;
 int den = h -> direct_den [ col_mv -> ref ] ;
 int m = col_mv -> x >> 31 ;
 pmv_fw -> dist = h -> dist [ 1 ] ;
 pmv_bw -> dist = h -> dist [ 0 ] ;
 pmv_fw -> ref = 1 ;
 pmv_bw -> ref = 0 ;
 pmv_fw -> x = ( ( ( den + ( den * col_mv -> x * pmv_fw -> dist ^ m ) - m - 1 ) >> 14 ) ^ m ) - m ;
 pmv_bw -> x = m - ( ( ( den + ( den * col_mv -> x * pmv_bw -> dist ^ m ) - m - 1 ) >> 14 ) ^ m ) ;
 m = col_mv -> y >> 31 ;
 pmv_fw -> y = ( ( ( den + ( den * col_mv -> y * pmv_fw -> dist ^ m ) - m - 1 ) >> 14 ) ^ m ) - m ;
 pmv_bw -> y = m - ( ( ( den + ( den * col_mv -> y * pmv_bw -> dist ^ m ) - m - 1 ) >> 14 ) ^ m ) ;
 }


static void band_destroy(jpc_enc_band_t *band)
{
	jpc_enc_prc_t *prc;
	jpc_enc_rlvl_t *rlvl;
	uint_fast32_t prcno;

	if (band->prcs) {
		rlvl = band->rlvl;
		for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
		  ++prcno, ++prc) {
			prc_destroy(prc);
		}
		jas_free(band->prcs);
	}
	if (band->data) {
		jas_seq2d_destroy(band->data);
	}
}


static float * calc_distr ( const float * p , int n , int m , float rest ) {
 float * row , * prev_row , * tmp ;
 int i , j ;
 row = ( float * ) palloc ( ( m + 1 ) * sizeof ( float ) ) ;
 prev_row = ( float * ) palloc ( ( m + 1 ) * sizeof ( float ) ) ;
 row [ 0 ] = 1.0f ;
 for ( i = 1 ;
 i <= n ;
 i ++ ) {
 float t = p [ i - 1 ] ;
 tmp = row ;
 row = prev_row ;
 prev_row = tmp ;
 for ( j = 0 ;
 j <= i && j <= m ;
 j ++ ) {
 float val = 0.0f ;
 if ( j < i ) val += prev_row [ j ] * ( 1.0f - t ) ;
 if ( j > 0 ) val += prev_row [ j - 1 ] * t ;
 row [ j ] = val ;
 }
 }
 if ( rest > DEFAULT_CONTAIN_SEL ) {
 float t ;
 tmp = row ;
 row = prev_row ;
 prev_row = tmp ;
 for ( i = 0 ;
 i <= m ;
 i ++ ) row [ i ] = 0.0f ;
 t = exp ( - rest ) ;
 for ( i = 0 ;
 i <= m ;
 i ++ ) {
 for ( j = 0 ;
 j <= m - i ;
 j ++ ) row [ j + i ] += prev_row [ j ] * t ;
 t *= rest / ( float ) ( i + 1 ) ;
 }
 }
 pfree ( prev_row ) ;
 return row ;
 }


static void prc_destroy(jpc_enc_prc_t *prc)
{
	jpc_enc_cblk_t *cblk;
	uint_fast32_t cblkno;

	if (prc->cblks) {
		for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
		  ++cblkno, ++cblk) {
			cblk_destroy(cblk);
		}
		jas_free(prc->cblks);
	}
	if (prc->incltree) {
		jpc_tagtree_destroy(prc->incltree);
	}
	if (prc->nlibtree) {
		jpc_tagtree_destroy(prc->nlibtree);
	}
	if (prc->savincltree) {
		jpc_tagtree_destroy(prc->savincltree);
	}
	if (prc->savnlibtree) {
		jpc_tagtree_destroy(prc->savnlibtree);
	}
}


static gboolean gst_asf_demux_get_stream_audio ( asf_stream_audio * audio , guint8 * * p_data , guint64 * p_size ) {
 if ( * p_size < ( 2 + 2 + 4 + 4 + 2 + 2 + 2 ) ) return FALSE ;
 audio -> codec_tag = gst_asf_demux_get_uint16 ( p_data , p_size ) ;
 audio -> channels = gst_asf_demux_get_uint16 ( p_data , p_size ) ;
 audio -> sample_rate = gst_asf_demux_get_uint32 ( p_data , p_size ) ;
 audio -> byte_rate = gst_asf_demux_get_uint32 ( p_data , p_size ) ;
 audio -> block_align = gst_asf_demux_get_uint16 ( p_data , p_size ) ;
 audio -> word_size = gst_asf_demux_get_uint16 ( p_data , p_size ) ;
 audio -> size = gst_asf_demux_get_uint16 ( p_data , p_size ) ;
 if ( audio -> size > * p_size ) {
 GST_WARNING ( "Corrupted audio codec_data (should be at least %u bytes, is %" G_GUINT64_FORMAT " long)" , audio -> size , * p_size ) ;
 return FALSE ;
 }
 return TRUE ;
 }


int v9fs_co_mknod(V9fsState *s, V9fsString *path, uid_t uid, gid_t gid, dev_t dev, mode_t mode) { int err; FsCred cred; cred_init(&cred); cred.fc_uid = uid; cred.fc_gid = gid; cred.fc_mode = mode; cred.fc_rdev = dev; v9fs_co_run_in_worker( { err = s->ops->mknod(&s->ctx, path->data, &cred); if (err < 0) { err = -errno; } }); return err; }


png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask,
    int num)
{
   png_debug(1, "in png_free_data");

   if (png_ptr == NULL || info_ptr == NULL)
      return;

#ifdef PNG_TEXT_SUPPORTED
   /* Free text item num or (if num == -1) all text items */
   if (info_ptr->text != NULL &&
       ((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0)
   {
      if (num != -1)
      {
         png_free(png_ptr, info_ptr->text[num].key);
         info_ptr->text[num].key = NULL;
      }

      else
      {
         int i;

         for (i = 0; i < info_ptr->num_text; i++)
            png_free(png_ptr, info_ptr->text[i].key);

         png_free(png_ptr, info_ptr->text);
         info_ptr->text = NULL;
         info_ptr->num_text = 0;
      }
   }
#endif

#ifdef PNG_tRNS_SUPPORTED
   /* Free any tRNS entry */
   if (((mask & PNG_FREE_TRNS) & info_ptr->free_me) != 0)
   {
      info_ptr->valid &= ~PNG_INFO_tRNS;
      png_free(png_ptr, info_ptr->trans_alpha);
      info_ptr->trans_alpha = NULL;
      info_ptr->num_trans = 0;
   }
#endif

#ifdef PNG_sCAL_SUPPORTED
   /* Free any sCAL entry */
   if (((mask & PNG_FREE_SCAL) & info_ptr->free_me) != 0)
   {
      png_free(png_ptr, info_ptr->scal_s_width);
      png_free(png_ptr, info_ptr->scal_s_height);
      info_ptr->scal_s_width = NULL;
      info_ptr->scal_s_height = NULL;
      info_ptr->valid &= ~PNG_INFO_sCAL;
   }
#endif

#ifdef PNG_pCAL_SUPPORTED
   /* Free any pCAL entry */
   if (((mask & PNG_FREE_PCAL) & info_ptr->free_me) != 0)
   {
      png_free(png_ptr, info_ptr->pcal_purpose);
      png_free(png_ptr, info_ptr->pcal_units);
      info_ptr->pcal_purpose = NULL;
      info_ptr->pcal_units = NULL;

      if (info_ptr->pcal_params != NULL)
         {
            int i;

            for (i = 0; i < info_ptr->pcal_nparams; i++)
               png_free(png_ptr, info_ptr->pcal_params[i]);

            png_free(png_ptr, info_ptr->pcal_params);
            info_ptr->pcal_params = NULL;
         }
      info_ptr->valid &= ~PNG_INFO_pCAL;
   }
#endif

#ifdef PNG_iCCP_SUPPORTED
   /* Free any profile entry */
   if (((mask & PNG_FREE_ICCP) & info_ptr->free_me) != 0)
   {
      png_free(png_ptr, info_ptr->iccp_name);
      png_free(png_ptr, info_ptr->iccp_profile);
      info_ptr->iccp_name = NULL;
      info_ptr->iccp_profile = NULL;
      info_ptr->valid &= ~PNG_INFO_iCCP;
   }
#endif

#ifdef PNG_sPLT_SUPPORTED
   /* Free a given sPLT entry, or (if num == -1) all sPLT entries */
   if (info_ptr->splt_palettes != NULL &&
       ((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0)
   {
      if (num != -1)
      {
         png_free(png_ptr, info_ptr->splt_palettes[num].name);
         png_free(png_ptr, info_ptr->splt_palettes[num].entries);
         info_ptr->splt_palettes[num].name = NULL;
         info_ptr->splt_palettes[num].entries = NULL;
      }

      else
      {
         int i;

         for (i = 0; i < info_ptr->splt_palettes_num; i++)
         {
            png_free(png_ptr, info_ptr->splt_palettes[i].name);
            png_free(png_ptr, info_ptr->splt_palettes[i].entries);
         }

         png_free(png_ptr, info_ptr->splt_palettes);
         info_ptr->splt_palettes = NULL;
         info_ptr->splt_palettes_num = 0;
         info_ptr->valid &= ~PNG_INFO_sPLT;
      }
   }
#endif

#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
   if (info_ptr->unknown_chunks != NULL &&
       ((mask & PNG_FREE_UNKN) & info_ptr->free_me) != 0)
   {
      if (num != -1)
      {
          png_free(png_ptr, info_ptr->unknown_chunks[num].data);
          info_ptr->unknown_chunks[num].data = NULL;
      }

      else
      {
         int i;

         for (i = 0; i < info_ptr->unknown_chunks_num; i++)
            png_free(png_ptr, info_ptr->unknown_chunks[i].data);

         png_free(png_ptr, info_ptr->unknown_chunks);
         info_ptr->unknown_chunks = NULL;
         info_ptr->unknown_chunks_num = 0;
      }
   }
#endif

#ifdef PNG_hIST_SUPPORTED
   /* Free any hIST entry */
   if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)
   {
      png_free(png_ptr, info_ptr->hist);
      info_ptr->hist = NULL;
      info_ptr->valid &= ~PNG_INFO_hIST;
   }
#endif

   /* Free any PLTE entry that was internally allocated */
   if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)
   {
      png_free(png_ptr, info_ptr->palette);
      info_ptr->palette = NULL;
      info_ptr->valid &= ~PNG_INFO_PLTE;
      info_ptr->num_palette = 0;
   }

#ifdef PNG_INFO_IMAGE_SUPPORTED
   /* Free any image bits attached to the info structure */
   if (((mask & PNG_FREE_ROWS) & info_ptr->free_me) != 0)
   {
      if (info_ptr->row_pointers != NULL)
      {
         png_uint_32 row;
         for (row = 0; row < info_ptr->height; row++)
            png_free(png_ptr, info_ptr->row_pointers[row]);

         png_free(png_ptr, info_ptr->row_pointers);
         info_ptr->row_pointers = NULL;
      }
      info_ptr->valid &= ~PNG_INFO_IDAT;
   }
#endif

   if (num != -1)
      mask &= ~PNG_FREE_MUL;

   info_ptr->free_me &= ~mask;
}


int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr)
{
	jp2_box_t *box;
	jp2_ftyp_t *ftyp;
	jp2_ihdr_t *ihdr;
	jas_stream_t *tmpstream;
	int allcmptssame;
	jp2_bpcc_t *bpcc;
	long len;
	uint_fast16_t cmptno;
	jp2_colr_t *colr;
	char buf[4096];
	uint_fast32_t overhead;
	jp2_cdefchan_t *cdefchanent;
	jp2_cdef_t *cdef;
	int i;
	uint_fast32_t typeasoc;
	jas_iccprof_t *iccprof;
	jas_stream_t *iccstream;
	int pos;
	int needcdef;
	int prec;
	int sgnd;

	box = 0;
	tmpstream = 0;

	allcmptssame = 1;
	sgnd = jas_image_cmptsgnd(image, 0);
	prec = jas_image_cmptprec(image, 0);
	for (i = 1; i < jas_image_numcmpts(image); ++i) {
		if (jas_image_cmptsgnd(image, i) != sgnd ||
		  jas_image_cmptprec(image, i) != prec) {
			allcmptssame = 0;
			break;
		}
	}

	/* Output the signature box. */

	if (!(box = jp2_box_create(JP2_BOX_JP))) {
		goto error;
	}
	box->data.jp.magic = JP2_JP_MAGIC;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Output the file type box. */

	if (!(box = jp2_box_create(JP2_BOX_FTYP))) {
		goto error;
	}
	ftyp = &box->data.ftyp;
	ftyp->majver = JP2_FTYP_MAJVER;
	ftyp->minver = JP2_FTYP_MINVER;
	ftyp->numcompatcodes = 1;
	ftyp->compatcodes[0] = JP2_FTYP_COMPATCODE;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/*
	 * Generate the data portion of the JP2 header box.
	 * We cannot simply output the header for this box
	 * since we do not yet know the correct value for the length
	 * field.
	 */

	if (!(tmpstream = jas_stream_memopen(0, 0))) {
		goto error;
	}

	/* Generate image header box. */

	if (!(box = jp2_box_create(JP2_BOX_IHDR))) {
		goto error;
	}
	ihdr = &box->data.ihdr;
	ihdr->width = jas_image_width(image);
	ihdr->height = jas_image_height(image);
	ihdr->numcmpts = jas_image_numcmpts(image);
	ihdr->bpc = allcmptssame ? JP2_SPTOBPC(jas_image_cmptsgnd(image, 0),
	  jas_image_cmptprec(image, 0)) : JP2_IHDR_BPCNULL;
	ihdr->comptype = JP2_IHDR_COMPTYPE;
	ihdr->csunk = 0;
	ihdr->ipr = 0;
	if (jp2_box_put(box, tmpstream)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Generate bits per component box. */

	if (!allcmptssame) {
		if (!(box = jp2_box_create(JP2_BOX_BPCC))) {
			goto error;
		}
		bpcc = &box->data.bpcc;
		bpcc->numcmpts = jas_image_numcmpts(image);
		if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts,
		  sizeof(uint_fast8_t)))) {
			goto error;
		}
		for (cmptno = 0; cmptno < bpcc->numcmpts; ++cmptno) {
			bpcc->bpcs[cmptno] = JP2_SPTOBPC(jas_image_cmptsgnd(image,
			  cmptno), jas_image_cmptprec(image, cmptno));
		}
		if (jp2_box_put(box, tmpstream)) {
			goto error;
		}
		jp2_box_destroy(box);
		box = 0;
	}

	/* Generate color specification box. */

	if (!(box = jp2_box_create(JP2_BOX_COLR))) {
		goto error;
	}
	colr = &box->data.colr;
	switch (jas_image_clrspc(image)) {
	case JAS_CLRSPC_SRGB:
	case JAS_CLRSPC_SYCBCR:
	case JAS_CLRSPC_SGRAY:
		colr->method = JP2_COLR_ENUM;
		colr->csid = clrspctojp2(jas_image_clrspc(image));
		colr->pri = JP2_COLR_PRI;
		colr->approx = 0;
		break;
	default:
		colr->method = JP2_COLR_ICC;
		colr->pri = JP2_COLR_PRI;
		colr->approx = 0;
		iccprof = jas_iccprof_createfromcmprof(jas_image_cmprof(image));
		assert(iccprof);
		iccstream = jas_stream_memopen(0, 0);
		assert(iccstream);
		if (jas_iccprof_save(iccprof, iccstream))
			abort();
		if ((pos = jas_stream_tell(iccstream)) < 0)
			abort();
		colr->iccplen = pos;
		colr->iccp = jas_malloc(pos);
		assert(colr->iccp);
		jas_stream_rewind(iccstream);
		if (jas_stream_read(iccstream, colr->iccp, colr->iccplen) != colr->iccplen)
			abort();
		jas_stream_close(iccstream);
		jas_iccprof_destroy(iccprof);
		break;
	}
	if (jp2_box_put(box, tmpstream)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	needcdef = 1;
	switch (jas_clrspc_fam(jas_image_clrspc(image))) {
	case JAS_CLRSPC_FAM_RGB:
		if (jas_image_cmpttype(image, 0) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) &&
		  jas_image_cmpttype(image, 1) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) &&
		  jas_image_cmpttype(image, 2) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))
			needcdef = 0;
		break;
	case JAS_CLRSPC_FAM_YCBCR:
		if (jas_image_cmpttype(image, 0) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) &&
		  jas_image_cmpttype(image, 1) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) &&
		  jas_image_cmpttype(image, 2) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR))
			needcdef = 0;
		break;
	case JAS_CLRSPC_FAM_GRAY:
		if (jas_image_cmpttype(image, 0) ==
		  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))
			needcdef = 0;
		break;
	default:
		abort();
		break;
	}

	if (needcdef) {
		if (!(box = jp2_box_create(JP2_BOX_CDEF))) {
			goto error;
		}
		cdef = &box->data.cdef;
		cdef->numchans = jas_image_numcmpts(image);
		cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t));
		for (i = 0; i < jas_image_numcmpts(image); ++i) {
			cdefchanent = &cdef->ents[i];
			cdefchanent->channo = i;
			typeasoc = jp2_gettypeasoc(jas_image_clrspc(image), jas_image_cmpttype(image, i));
			cdefchanent->type = typeasoc >> 16;
			cdefchanent->assoc = typeasoc & 0x7fff;
		}
		if (jp2_box_put(box, tmpstream)) {
			goto error;
		}
		jp2_box_destroy(box);
		box = 0;
	}

	/* Determine the total length of the JP2 header box. */

	len = jas_stream_tell(tmpstream);
	jas_stream_rewind(tmpstream);

	/*
	 * Output the JP2 header box and all of the boxes which it contains.
	 */

	if (!(box = jp2_box_create(JP2_BOX_JP2H))) {
		goto error;
	}
	box->len = len + JP2_BOX_HDRLEN(false);
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	if (jas_stream_copy(out, tmpstream, len)) {
		goto error;
	}

	jas_stream_close(tmpstream);
	tmpstream = 0;

	/*
	 * Output the contiguous code stream box.
	 */

	if (!(box = jp2_box_create(JP2_BOX_JP2C))) {
		goto error;
	}
	box->len = 0;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Output the JPEG-2000 code stream. */

	overhead = jas_stream_getrwcount(out);
	sprintf(buf, "%s\n_jp2overhead=%lu\n", (optstr ? optstr : ""),
	  (unsigned long) overhead);

	if (jpc_encode(image, out, buf)) {
		goto error;
	}

	return 0;

error:

	if (box) {
		jp2_box_destroy(box);
	}
	if (tmpstream) {
		jas_stream_close(tmpstream);
	}
	return -1;
}


static Image *ReadVIFFImage(const ImageInfo *image_info,
  ExceptionInfo *exception)
{
#define VFF_CM_genericRGB  15
#define VFF_CM_ntscRGB  1
#define VFF_CM_NONE  0
#define VFF_DEP_DECORDER  0x4
#define VFF_DEP_NSORDER  0x8
#define VFF_DES_RAW  0
#define VFF_LOC_IMPLICIT  1
#define VFF_MAPTYP_NONE  0
#define VFF_MAPTYP_1_BYTE  1
#define VFF_MAPTYP_2_BYTE  2
#define VFF_MAPTYP_4_BYTE  4
#define VFF_MAPTYP_FLOAT  5
#define VFF_MAPTYP_DOUBLE  7
#define VFF_MS_NONE  0
#define VFF_MS_ONEPERBAND  1
#define VFF_MS_SHARED  3
#define VFF_TYP_BIT  0
#define VFF_TYP_1_BYTE  1
#define VFF_TYP_2_BYTE  2
#define VFF_TYP_4_BYTE  4
#define VFF_TYP_FLOAT  5
#define VFF_TYP_DOUBLE  9

  typedef struct _ViffInfo
  {
    unsigned char
      identifier,
      file_type,
      release,
      version,
      machine_dependency,
      reserve[3];

    char
      comment[512];

    unsigned int
      rows,
      columns,
      subrows;

    int
      x_offset,
      y_offset;

    float
      x_bits_per_pixel,
      y_bits_per_pixel;

    unsigned int
      location_type,
      location_dimension,
      number_of_images,
      number_data_bands,
      data_storage_type,
      data_encode_scheme,
      map_scheme,
      map_storage_type,
      map_rows,
      map_columns,
      map_subrows,
      map_enable,
      maps_per_cycle,
      color_space_model;
  } ViffInfo;

  double
    min_value,
    scale_factor,
    value;

  Image
    *image;

  int
    bit;

  MagickBooleanType
    status;

  MagickSizeType
    number_pixels;

  register ssize_t
    x;

  register Quantum
    *q;

  register ssize_t
    i;

  register unsigned char
    *p;

  size_t
    bytes_per_pixel,
    max_packets,
    quantum;

  ssize_t
    count,
    y;

  unsigned char
    *pixels;

  unsigned long
    lsb_first;

  ViffInfo
    viff_info;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info,exception);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Read VIFF header (1024 bytes).
  */
  count=ReadBlob(image,1,&viff_info.identifier);
  do
  {
    /*
      Verify VIFF identifier.
    */
    if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))
      ThrowReaderException(CorruptImageError,"NotAVIFFImage");
    /*
      Initialize VIFF image.
    */
    (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);
    (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);
    (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);
    (void) ReadBlob(image,sizeof(viff_info.machine_dependency),
      &viff_info.machine_dependency);
    (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);
    count=ReadBlob(image,512,(unsigned char *) viff_info.comment);
    viff_info.comment[511]='\0';
    if (strlen(viff_info.comment) > 4)
      (void) SetImageProperty(image,"comment",viff_info.comment,exception);
    if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||
        (viff_info.machine_dependency == VFF_DEP_NSORDER))
      image->endian=LSBEndian;
    else
      image->endian=MSBEndian;
    viff_info.rows=ReadBlobLong(image);
    viff_info.columns=ReadBlobLong(image);
    viff_info.subrows=ReadBlobLong(image);
    viff_info.x_offset=(int) ReadBlobLong(image);
    viff_info.y_offset=(int) ReadBlobLong(image);
    viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);
    viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);
    viff_info.location_type=ReadBlobLong(image);
    viff_info.location_dimension=ReadBlobLong(image);
    viff_info.number_of_images=ReadBlobLong(image);
    viff_info.number_data_bands=ReadBlobLong(image);
    viff_info.data_storage_type=ReadBlobLong(image);
    viff_info.data_encode_scheme=ReadBlobLong(image);
    viff_info.map_scheme=ReadBlobLong(image);
    viff_info.map_storage_type=ReadBlobLong(image);
    viff_info.map_rows=ReadBlobLong(image);
    viff_info.map_columns=ReadBlobLong(image);
    viff_info.map_subrows=ReadBlobLong(image);
    viff_info.map_enable=ReadBlobLong(image);
    viff_info.maps_per_cycle=ReadBlobLong(image);
    viff_info.color_space_model=ReadBlobLong(image);
    for (i=0; i < 420; i++)
      (void) ReadBlobByte(image);
    if (EOFBlob(image) != MagickFalse)
      ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
    image->columns=viff_info.rows;
    image->rows=viff_info.columns;
    image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :
      MAGICKCORE_QUANTUM_DEPTH;
    /*
      Verify that we can read this VIFF image.
    */
    number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;
    if (number_pixels != (size_t) number_pixels)
      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
    if (number_pixels == 0)
      ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported");
    if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))
      ThrowReaderException(CorruptImageError,"ImproperImageHeader");
    if ((viff_info.data_storage_type != VFF_TYP_BIT) &&
        (viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
        (viff_info.data_storage_type != VFF_TYP_2_BYTE) &&
        (viff_info.data_storage_type != VFF_TYP_4_BYTE) &&
        (viff_info.data_storage_type != VFF_TYP_FLOAT) &&
        (viff_info.data_storage_type != VFF_TYP_DOUBLE))
      ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported");
    if (viff_info.data_encode_scheme != VFF_DES_RAW)
      ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
    if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&
        (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&
        (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&
        (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&
        (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&
        (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))
      ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported");
    if ((viff_info.color_space_model != VFF_CM_NONE) &&
        (viff_info.color_space_model != VFF_CM_ntscRGB) &&
        (viff_info.color_space_model != VFF_CM_genericRGB))
      ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported");
    if (viff_info.location_type != VFF_LOC_IMPLICIT)
      ThrowReaderException(CoderError,"LocationTypeIsNotSupported");
    if (viff_info.number_of_images != 1)
      ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported");
    if (viff_info.map_rows == 0)
      viff_info.map_scheme=VFF_MS_NONE;
    switch ((int) viff_info.map_scheme)
    {
      case VFF_MS_NONE:
      {
        if (viff_info.number_data_bands < 3)
          {
            /*
              Create linear color ramp.
            */
            if (viff_info.data_storage_type == VFF_TYP_BIT)
              image->colors=2;
            else
              if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)
                image->colors=256UL;
              else
                image->colors=image->depth <= 8 ? 256UL : 65536UL;
            status=AcquireImageColormap(image,image->colors,exception);
            if (status == MagickFalse)
              ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          }
        break;
      }
      case VFF_MS_ONEPERBAND:
      case VFF_MS_SHARED:
      {
        unsigned char
          *viff_colormap;

        /*
          Allocate VIFF colormap.
        */
        switch ((int) viff_info.map_storage_type)
        {
          case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;
          case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;
          case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;
          case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;
          case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;
          default: bytes_per_pixel=1; break;
        }
        image->colors=viff_info.map_columns;
        if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
          ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
        if (viff_info.map_rows >
            (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)))
          ThrowReaderException(CorruptImageError,"ImproperImageHeader");
        viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
          viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));
        if (viff_colormap == (unsigned char *) NULL)
          ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
        /*
          Read VIFF raster colormap.
        */
        count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,
          viff_colormap);
        lsb_first=1;
        if (*(char *) &lsb_first &&
            ((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
             (viff_info.machine_dependency != VFF_DEP_NSORDER)))
          switch ((int) viff_info.map_storage_type)
          {
            case VFF_MAPTYP_2_BYTE:
            {
              MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*
                viff_info.map_rows));
              break;
            }
            case VFF_MAPTYP_4_BYTE:
            case VFF_MAPTYP_FLOAT:
            {
              MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*
                viff_info.map_rows));
              break;
            }
            default: break;
          }
        for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)
        {
          switch ((int) viff_info.map_storage_type)
          {
            case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;
            case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;
            case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;
            case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;
            default: value=1.0*viff_colormap[i]; break;
          }
          if (i < (ssize_t) image->colors)
            {
              image->colormap[i].red=ScaleCharToQuantum((unsigned char) value);
              image->colormap[i].green=
                ScaleCharToQuantum((unsigned char) value);
              image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value);
            }
          else
            if (i < (ssize_t) (2*image->colors))
              image->colormap[i % image->colors].green=
                ScaleCharToQuantum((unsigned char) value);
            else
              if (i < (ssize_t) (3*image->colors))
                image->colormap[i % image->colors].blue=
                  ScaleCharToQuantum((unsigned char) value);
        }
        viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);
        break;
      }
      default:
        ThrowReaderException(CoderError,"ColormapTypeNotSupported");
    }
    /*
      Initialize image structure.
    */
    image->alpha_trait=viff_info.number_data_bands == 4 ? BlendPixelTrait :
      UndefinedPixelTrait;
    image->storage_class=(viff_info.number_data_bands < 3 ? PseudoClass :
      DirectClass);
    image->columns=viff_info.rows;
    image->rows=viff_info.columns;
    if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
      if (image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    status=SetImageExtent(image,image->columns,image->rows,exception);
    if (status == MagickFalse)
      return(DestroyImageList(image));
    /*
      Allocate VIFF pixels.
    */
    switch ((int) viff_info.data_storage_type)
    {
      case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;
      case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;
      case VFF_TYP_FLOAT: bytes_per_pixel=4; break;
      case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;
      default: bytes_per_pixel=1; break;
    }
    if (viff_info.data_storage_type == VFF_TYP_BIT)
      max_packets=((image->columns+7UL) >> 3UL)*image->rows;
    else
      max_packets=(size_t) (number_pixels*viff_info.number_data_bands);
    pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels,
      max_packets),bytes_per_pixel*sizeof(*pixels));
    if (pixels == (unsigned char *) NULL)
      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
    count=ReadBlob(image,bytes_per_pixel*max_packets,pixels);
    lsb_first=1;
    if (*(char *) &lsb_first &&
        ((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
         (viff_info.machine_dependency != VFF_DEP_NSORDER)))
      switch ((int) viff_info.data_storage_type)
      {
        case VFF_TYP_2_BYTE:
        {
          MSBOrderShort(pixels,bytes_per_pixel*max_packets);
          break;
        }
        case VFF_TYP_4_BYTE:
        case VFF_TYP_FLOAT:
        {
          MSBOrderLong(pixels,bytes_per_pixel*max_packets);
          break;
        }
        default: break;
      }
    min_value=0.0;
    scale_factor=1.0;
    if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
        (viff_info.map_scheme == VFF_MS_NONE))
      {
        double
          max_value;

        /*
          Determine scale factor.
        */
        switch ((int) viff_info.data_storage_type)
        {
          case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;
          case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;
          case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;
          case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;
          default: value=1.0*pixels[0]; break;
        }
        max_value=value;
        min_value=value;
        for (i=0; i < (ssize_t) max_packets; i++)
        {
          switch ((int) viff_info.data_storage_type)
          {
            case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
            case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
            case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
            case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
            default: value=1.0*pixels[i]; break;
          }
          if (value > max_value)
            max_value=value;
          else
            if (value < min_value)
              min_value=value;
        }
        if ((min_value == 0) && (max_value == 0))
          scale_factor=0;
        else
          if (min_value == max_value)
            {
              scale_factor=(double) QuantumRange/min_value;
              min_value=0;
            }
          else
            scale_factor=(double) QuantumRange/(max_value-min_value);
      }
    /*
      Convert pixels to Quantum size.
    */
    p=(unsigned char *) pixels;
    for (i=0; i < (ssize_t) max_packets; i++)
    {
      switch ((int) viff_info.data_storage_type)
      {
        case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
        case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
        case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
        case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
        default: value=1.0*pixels[i]; break;
      }
      if (viff_info.map_scheme == VFF_MS_NONE)
        {
          value=(value-min_value)*scale_factor;
          if (value > QuantumRange)
            value=QuantumRange;
          else
            if (value < 0)
              value=0;
        }
      *p=(unsigned char) ((Quantum) value);
      p++;
    }
    /*
      Convert VIFF raster image to pixel packets.
    */
    p=(unsigned char *) pixels;
    if (viff_info.data_storage_type == VFF_TYP_BIT)
      {
        /*
          Convert bitmap scanline.
        */
        for (y=0; y < (ssize_t) image->rows; y++)
        {
          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
          if (q == (Quantum *) NULL)
            break;
          for (x=0; x < (ssize_t) (image->columns-7); x+=8)
          {
            for (bit=0; bit < 8; bit++)
            {
              quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
              SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);
              SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);
              SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);
              if (image->storage_class == PseudoClass)
                SetPixelIndex(image,(Quantum) quantum,q);
              q+=GetPixelChannels(image);
            }
            p++;
          }
          if ((image->columns % 8) != 0)
            {
              for (bit=0; bit < (int) (image->columns % 8); bit++)
              {
                quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
                SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);
                SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);
                SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);
                if (image->storage_class == PseudoClass)
                  SetPixelIndex(image,(Quantum) quantum,q);
                q+=GetPixelChannels(image);
              }
              p++;
            }
          if (SyncAuthenticPixels(image,exception) == MagickFalse)
            break;
          if (image->previous == (Image *) NULL)
            {
              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
                image->rows);
              if (status == MagickFalse)
                break;
            }
        }
      }
    else
      if (image->storage_class == PseudoClass)
        for (y=0; y < (ssize_t) image->rows; y++)
        {
          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
          if (q == (Quantum *) NULL)
            break;
          for (x=0; x < (ssize_t) image->columns; x++)
          {
            SetPixelIndex(image,*p++,q);
            q+=GetPixelChannels(image);
          }
          if (SyncAuthenticPixels(image,exception) == MagickFalse)
            break;
          if (image->previous == (Image *) NULL)
            {
              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
                image->rows);
              if (status == MagickFalse)
                break;
            }
        }
      else
        {
          /*
            Convert DirectColor scanline.
          */
          number_pixels=(MagickSizeType) image->columns*image->rows;
          for (y=0; y < (ssize_t) image->rows; y++)
          {
            q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
            if (q == (Quantum *) NULL)
              break;
            for (x=0; x < (ssize_t) image->columns; x++)
            {
              SetPixelRed(image,ScaleCharToQuantum(*p),q);
              SetPixelGreen(image,ScaleCharToQuantum(*(p+number_pixels)),q);
              SetPixelBlue(image,ScaleCharToQuantum(*(p+2*number_pixels)),q);
              if (image->colors != 0)
                {
                  ssize_t
                    index;

                  index=(ssize_t) GetPixelRed(image,q);
                  SetPixelRed(image,image->colormap[
                    ConstrainColormapIndex(image,index,exception)].red,q);
                  index=(ssize_t) GetPixelGreen(image,q);
                  SetPixelGreen(image,image->colormap[
                    ConstrainColormapIndex(image,index,exception)].green,q);
                  index=(ssize_t) GetPixelBlue(image,q);
                  SetPixelBlue(image,image->colormap[
                    ConstrainColormapIndex(image,index,exception)].blue,q);
                }
              SetPixelAlpha(image,image->alpha_trait != UndefinedPixelTrait ?
                ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueAlpha,q);
              p++;
              q+=GetPixelChannels(image);
            }
            if (SyncAuthenticPixels(image,exception) == MagickFalse)
              break;
            if (image->previous == (Image *) NULL)
              {
                status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
                image->rows);
                if (status == MagickFalse)
                  break;
              }
          }
        }
    pixels=(unsigned char *) RelinquishMagickMemory(pixels);
    if (image->storage_class == PseudoClass)
      (void) SyncImage(image,exception);
    if (EOFBlob(image) != MagickFalse)
      {
        ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
          image->filename);
        break;
      }
    /*
      Proceed to next image.
    */
    if (image_info->number_scenes != 0)
      if (image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    count=ReadBlob(image,1,&viff_info.identifier);
    if ((count != 0) && (viff_info.identifier == 0xab))
      {
        /*
          Allocate next image structure.
        */
        AcquireNextImage(image_info,image,exception);
        if (GetNextImageInList(image) == (Image *) NULL)
          {
            image=DestroyImageList(image);
            return((Image *) NULL);
          }
        image=SyncNextImageInList(image);
        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
          GetBlobSize(image));
        if (status == MagickFalse)
          break;
      }
  } while ((count != 0) && (viff_info.identifier == 0xab));
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}


static const char *get_ansi_color(THEME_REC *theme, const char *str,
				  int *fg_ret, int *bg_ret, int *flags_ret)
{
	static char ansitab[8] = { 0, 4, 2, 6, 1, 5, 3, 7 };
	const char *start;
	int fg, bg, flags, num, i;
	unsigned int num2;

	if (*str != '[')
		return str;
	start = str++;

	fg = fg_ret == NULL || *fg_ret < 0 ? theme->default_color : *fg_ret;
	bg = bg_ret == NULL || *bg_ret < 0 ? -1 : *bg_ret;
	flags = flags_ret == NULL ? 0 : *flags_ret;

	num = 0;
	for (;; str++) {
		if (*str == '\0') return start;

		if (i_isdigit(*str)) {
			num = num*10 + (*str-'0');
			continue;
		}

		if (*str != ';' && *str != 'm')
			return start;

		switch (num) {
		case 0:
			/* reset colors and attributes back to default */
			fg = theme->default_color;
			bg = -1;
			flags &= ~(GUI_PRINT_FLAG_INDENT |
				   GUI_PRINT_FLAG_BOLD | GUI_PRINT_FLAG_ITALIC | GUI_PRINT_FLAG_UNDERLINE |
				   GUI_PRINT_FLAG_BLINK | GUI_PRINT_FLAG_REVERSE |
				   GUI_PRINT_FLAG_COLOR_24_FG | GUI_PRINT_FLAG_COLOR_24_BG);
			break;
		case 1:
			/* hilight */
			flags |= GUI_PRINT_FLAG_BOLD;
			break;
		case 22:
			/* normal */
			flags &= ~GUI_PRINT_FLAG_BOLD;
			break;
		case 3:
			/* italic */
			flags |= GUI_PRINT_FLAG_ITALIC;
			break;
		case 23:
			/* not italic */
			flags &= ~GUI_PRINT_FLAG_ITALIC;
			break;
		case 4:
			/* underline */
			flags |= GUI_PRINT_FLAG_UNDERLINE;
			break;
		case 24:
			/* not underline */
			flags &= ~GUI_PRINT_FLAG_UNDERLINE;
			break;
		case 5:
			/* blink */
			flags |= GUI_PRINT_FLAG_BLINK;
			break;
		case 25:
			/* steady */
			flags &= ~GUI_PRINT_FLAG_BLINK;
			break;
		case 7:
			/* reverse */
			flags |= GUI_PRINT_FLAG_REVERSE;
			break;
		case 27:
			/* positive */
			flags &= ~GUI_PRINT_FLAG_REVERSE;
			break;
		case 39:
			/* reset fg */
			flags &= ~GUI_PRINT_FLAG_COLOR_24_FG;
			fg = theme->default_color;
			break;
		case 49:
			/* reset bg */
			bg = -1;
			flags &= ~(GUI_PRINT_FLAG_COLOR_24_BG | GUI_PRINT_FLAG_INDENT);
			break;
		case 38:
		case 48:
			/* ANSI indexed color or RGB color */
			if (*str != ';') break;
			str++;
			for (num2 = 0; i_isdigit(*str); str++)
				num2 = num2*10 + (*str-'0');

			switch (num2) {
			case 2:
				/* RGB */
				num2 = 0;

				for (i = 0; i < 3; ++i) {
					num2 <<= 8;

					if (*str != ';' && *str != ':') {
						i = -1;
						break;
					}
					str++;
					for (; i_isdigit(*str); str++)
						num2 = (num2&~0xff) |
							(((num2&0xff) * 10 + (*str-'0'))&0xff);
				}

				if (i == -1) break;
#ifdef TERM_TRUECOLOR
				if (num == 38) {
					flags |= GUI_PRINT_FLAG_COLOR_24_FG;
					fg = num2;
				} else if (num == 48) {
					flags |= GUI_PRINT_FLAG_COLOR_24_BG;
					bg = num2;
				}
#else /* !TERM_TRUECOLOR */
				if (num == 38) {
					flags &= ~GUI_PRINT_FLAG_COLOR_24_FG;
					fg = color_24bit_256_int(num2);
				} else if (num == 48) {
					flags &= ~GUI_PRINT_FLAG_COLOR_24_BG;
					bg = color_24bit_256_int(num2);
				}
#endif

				break;
			case 5:
				/* indexed */
				if (*str != ';') break;
				str++;
				for (num2 = 0; i_isdigit(*str); str++)
					num2 = num2*10 + (*str-'0');

				if (num == 38) {
					flags &= ~GUI_PRINT_FLAG_COLOR_24_FG;
					fg = num2;
				} else if (num == 48) {
					flags &= ~GUI_PRINT_FLAG_COLOR_24_BG;
					bg = num2;
				}

				break;
			}
			break;
		default:
			if (num >= 30 && num <= 37) {
				flags &= ~GUI_PRINT_FLAG_COLOR_24_FG;
				fg = ansitab[num-30];
			} else if (num >= 40 && num <= 47) {
				flags &= ~GUI_PRINT_FLAG_COLOR_24_BG;
				bg = ansitab[num-40];
			} else if (num >= 90 && num <= 97) {
				flags &= ~GUI_PRINT_FLAG_COLOR_24_FG;
				fg = 8 + ansitab[num-90];
			} else if (num >= 100 && num <= 107) {
				flags &= ~GUI_PRINT_FLAG_COLOR_24_BG;
				bg = 8 + ansitab[num-100];
			}
			break;
		}
		num = 0;

		if (*str == 'm') {
			if (fg_ret != NULL) *fg_ret = fg;
			if (bg_ret != NULL) *bg_ret = bg;
			if (flags_ret != NULL) *flags_ret = flags;

			str++;
			break;
		}
	}

	return str;
}


void vp9_init_me_luts ( ) {
 int i ;
 for ( i = 0 ;
 i < QINDEX_RANGE ;
 ++ i ) {
 const double q = vp9_convert_qindex_to_q ( i ) ;
 sad_per_bit16lut [ i ] = ( int ) ( 0.0418 * q + 2.4107 ) ;
 sad_per_bit4lut [ i ] = ( int ) ( 0.063 * q + 2.742 ) ;
 }
 }


static uint32_t record_block_getter ( uint8_t * p , uint32_t s , Gif_Reader * grr ) {
 uint32_t ncopy = ( grr -> pos + s <= grr -> length ? s : grr -> length - grr -> pos ) ;
 memcpy ( p , & grr -> v [ grr -> pos ] , ncopy ) ;
 grr -> pos += ncopy ;
 if ( ncopy < s ) memset ( p + ncopy , 0 , s - ncopy ) ;
 return ncopy ;
 }


static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC)
{
	int 		s_den;
	unsigned 	u_den;

	switch(format) {
		case TAG_FMT_SBYTE:     return *(signed char *)value;
		case TAG_FMT_BYTE:      return *(uchar *)value;

		case TAG_FMT_USHORT:    return php_ifd_get16u(value, motorola_intel);
		case TAG_FMT_ULONG:     return php_ifd_get32u(value, motorola_intel);

		case TAG_FMT_URATIONAL:
			u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
			if (u_den == 0) {
				return 0;
			} else {
				return php_ifd_get32u(value, motorola_intel) / u_den;
			}

		case TAG_FMT_SRATIONAL:
			s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
			if (s_den == 0) {
				return 0;
			} else {
				return (size_t)((double)php_ifd_get32s(value, motorola_intel) / s_den);
			}

		case TAG_FMT_SSHORT:    return php_ifd_get16u(value, motorola_intel);
		case TAG_FMT_SLONG:     return php_ifd_get32s(value, motorola_intel);

		/* Not sure if this is correct (never seen float used in Exif format) */
		case TAG_FMT_SINGLE:
#ifdef EXIF_DEBUG
			php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single");
#endif
			return (size_t)*(float *)value;
		case TAG_FMT_DOUBLE:
#ifdef EXIF_DEBUG
			php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double");
#endif
			return (size_t)*(double *)value;
	}
	return 0;
}


static int alac_decode_frame ( AVCodecContext * avctx , void * data , int * got_frame_ptr , AVPacket * avpkt ) {
 ALACContext * alac = avctx -> priv_data ;
 AVFrame * frame = data ;
 enum AlacRawDataBlockType element ;
 int channels ;
 int ch , ret , got_end ;
 init_get_bits ( & alac -> gb , avpkt -> data , avpkt -> size * 8 ) ;
 got_end = 0 ;
 alac -> nb_samples = 0 ;
 ch = 0 ;
 while ( get_bits_left ( & alac -> gb ) >= 3 ) {
 element = get_bits ( & alac -> gb , 3 ) ;
 if ( element == TYPE_END ) {
 got_end = 1 ;
 break ;
 }
 if ( element > TYPE_CPE && element != TYPE_LFE ) {
 av_log ( avctx , AV_LOG_ERROR , "syntax element unsupported: %d" , element ) ;
 return AVERROR_PATCHWELCOME ;
 }
 channels = ( element == TYPE_CPE ) ? 2 : 1 ;
 if ( ch + channels > alac -> channels ) {
 av_log ( avctx , AV_LOG_ERROR , "invalid element channel count\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 ret = decode_element ( avctx , frame , ff_alac_channel_layout_offsets [ alac -> channels - 1 ] [ ch ] , channels ) ;
 if ( ret < 0 && get_bits_left ( & alac -> gb ) ) return ret ;
 ch += channels ;
 }
 if ( ! got_end ) {
 av_log ( avctx , AV_LOG_ERROR , "no end tag found. incomplete packet.\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 if ( avpkt -> size * 8 - get_bits_count ( & alac -> gb ) > 8 ) {
 av_log ( avctx , AV_LOG_ERROR , "Error : %d bits left\n" , avpkt -> size * 8 - get_bits_count ( & alac -> gb ) ) ;
 }
 * got_frame_ptr = 1 ;
 return avpkt -> size ;
 }


alloc_invoke_arguments(argc, argv)
    int argc;
    VALUE *argv;
{
    int i;
    int thr_crit_bup;

#if TCL_MAJOR_VERSION >= 8
    Tcl_Obj **av;
#else /* TCL_MAJOR_VERSION < 8 */
    char **av;
#endif

    thr_crit_bup = rb_thread_critical;
    rb_thread_critical = Qtrue;

    /* memory allocation */
#if TCL_MAJOR_VERSION >= 8
    /* av = ALLOC_N(Tcl_Obj *, argc+1);*/ /* XXXXXXXXXX */
    av = RbTk_ALLOC_N(Tcl_Obj *, (argc+1));
#if 0 /* use Tcl_Preserve/Release */
    Tcl_Preserve((ClientData)av); /* XXXXXXXX */
#endif
    for (i = 0; i < argc; ++i) {
        av[i] = get_obj_from_str(argv[i]);
        Tcl_IncrRefCount(av[i]);
    }
    av[argc] = NULL;

#else /* TCL_MAJOR_VERSION < 8 */
    /* string interface */
    /* av = ALLOC_N(char *, argc+1); */
    av = RbTk_ALLOC_N(char *, (argc+1));
#if 0 /* use Tcl_Preserve/Release */
    Tcl_Preserve((ClientData)av); /* XXXXXXXX */
#endif
    for (i = 0; i < argc; ++i) {
        av[i] = strdup(StringValuePtr(argv[i]));
    }
    av[argc] = NULL;
#endif

    rb_thread_critical = thr_crit_bup;

    return av;
}


static void find_mv_refs_idx ( const VP9_COMMON * cm , const MACROBLOCKD * xd , const TileInfo * const tile , MODE_INFO * mi , MV_REFERENCE_FRAME ref_frame , int_mv * mv_ref_list , int block , int mi_row , int mi_col ) {
 const int * ref_sign_bias = cm -> ref_frame_sign_bias ;
 int i , refmv_count = 0 ;
 const MODE_INFO * prev_mi = ! cm -> error_resilient_mode && cm -> prev_mi ? cm -> prev_mi_grid_visible [ mi_row * xd -> mi_stride + mi_col ] : NULL ;
 const MB_MODE_INFO * const prev_mbmi = prev_mi ? & prev_mi -> mbmi : NULL ;
 const POSITION * const mv_ref_search = mv_ref_blocks [ mi -> mbmi . sb_type ] ;
 int different_ref_found = 0 ;
 int context_counter = 0 ;
 vpx_memset ( mv_ref_list , 0 , sizeof ( * mv_ref_list ) * MAX_MV_REF_CANDIDATES ) ;
 for ( i = 0 ;
 i < 2 ;
 ++ i ) {
 const POSITION * const mv_ref = & mv_ref_search [ i ] ;
 if ( is_inside ( tile , mi_col , mi_row , cm -> mi_rows , mv_ref ) ) {
 const MODE_INFO * const candidate_mi = xd -> mi [ mv_ref -> col + mv_ref -> row * xd -> mi_stride ] ;
 const MB_MODE_INFO * const candidate = & candidate_mi -> mbmi ;
 context_counter += mode_2_counter [ candidate -> mode ] ;
 different_ref_found = 1 ;
 if ( candidate -> ref_frame [ 0 ] == ref_frame ) ADD_MV_REF_LIST ( get_sub_block_mv ( candidate_mi , 0 , mv_ref -> col , block ) ) ;
 else if ( candidate -> ref_frame [ 1 ] == ref_frame ) ADD_MV_REF_LIST ( get_sub_block_mv ( candidate_mi , 1 , mv_ref -> col , block ) ) ;
 }
 }
 for ( ;
 i < MVREF_NEIGHBOURS ;
 ++ i ) {
 const POSITION * const mv_ref = & mv_ref_search [ i ] ;
 if ( is_inside ( tile , mi_col , mi_row , cm -> mi_rows , mv_ref ) ) {
 const MB_MODE_INFO * const candidate = & xd -> mi [ mv_ref -> col + mv_ref -> row * xd -> mi_stride ] -> mbmi ;
 different_ref_found = 1 ;
 if ( candidate -> ref_frame [ 0 ] == ref_frame ) ADD_MV_REF_LIST ( candidate -> mv [ 0 ] ) ;
 else if ( candidate -> ref_frame [ 1 ] == ref_frame ) ADD_MV_REF_LIST ( candidate -> mv [ 1 ] ) ;
 }
 }
 if ( prev_mbmi ) {
 if ( prev_mbmi -> ref_frame [ 0 ] == ref_frame ) ADD_MV_REF_LIST ( prev_mbmi -> mv [ 0 ] ) ;
 else if ( prev_mbmi -> ref_frame [ 1 ] == ref_frame ) ADD_MV_REF_LIST ( prev_mbmi -> mv [ 1 ] ) ;
 }
 if ( different_ref_found ) {
 for ( i = 0 ;
 i < MVREF_NEIGHBOURS ;
 ++ i ) {
 const POSITION * mv_ref = & mv_ref_search [ i ] ;
 if ( is_inside ( tile , mi_col , mi_row , cm -> mi_rows , mv_ref ) ) {
 const MB_MODE_INFO * const candidate = & xd -> mi [ mv_ref -> col + mv_ref -> row * xd -> mi_stride ] -> mbmi ;
 IF_DIFF_REF_FRAME_ADD_MV ( candidate ) ;
 }
 }
 }
 if ( prev_mbmi ) IF_DIFF_REF_FRAME_ADD_MV ( prev_mbmi ) ;
 Done : mi -> mbmi . mode_context [ ref_frame ] = counter_to_context [ context_counter ] ;
 for ( i = 0 ;
 i < MAX_MV_REF_CANDIDATES ;
 ++ i ) clamp_mv_ref ( & mv_ref_list [ i ] . as_mv , xd ) ;
 }


static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof TSRMLS_DC)
{
	char *ksep, *vsep, *val;
	size_t klen, vlen;
	/* FIXME: string-size_t */
	unsigned int new_vlen;

	if (var->ptr >= var->end) {
		return 0;
	}

	vsep = memchr(var->ptr, '&', var->end - var->ptr);
	if (!vsep) {
		if (!eof) {
			return 0;
		} else {
			vsep = var->end;
		}
	}

	ksep = memchr(var->ptr, '=', vsep - var->ptr);
	if (ksep) {
		*ksep = '\0';
		/* "foo=bar&" or "foo=&" */
		klen = ksep - var->ptr;
		vlen = vsep - ++ksep;
	} else {
		ksep = "";
		/* "foo&" */
		klen = vsep - var->ptr;
		vlen = 0;
	}

	php_url_decode(var->ptr, klen);

	val = estrndup(ksep, vlen);
	if (vlen) {
		vlen = php_url_decode(val, vlen);
	}

	if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen TSRMLS_CC)) {
		php_register_variable_safe(var->ptr, val, new_vlen, arr TSRMLS_CC);
	}
	efree(val);

	var->ptr = vsep + (vsep != var->end);
	return 1;
}


static int frame_start(MpegEncContext *s) { int ret; /* mark & release old frames */ if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr && s->last_picture_ptr != s->next_picture_ptr && s->last_picture_ptr->f.buf[0]) { ff_mpeg_unref_picture(s, s->last_picture_ptr); } s->current_picture_ptr->f.pict_type = s->pict_type; s->current_picture_ptr->f.key_frame = s->pict_type == AV_PICTURE_TYPE_I; ff_mpeg_unref_picture(s, &s->current_picture); if ((ret = ff_mpeg_ref_picture(s, &s->current_picture, s->current_picture_ptr)) < 0) return ret; if (s->pict_type != AV_PICTURE_TYPE_B) { s->last_picture_ptr = s->next_picture_ptr; if (!s->droppable) s->next_picture_ptr = s->current_picture_ptr; } if (s->last_picture_ptr) { ff_mpeg_unref_picture(s, &s->last_picture); if (s->last_picture_ptr->f.buf[0] && (ret = ff_mpeg_ref_picture(s, &s->last_picture, s->last_picture_ptr)) < 0) return ret; } if (s->next_picture_ptr) { ff_mpeg_unref_picture(s, &s->next_picture); if (s->next_picture_ptr->f.buf[0] && (ret = ff_mpeg_ref_picture(s, &s->next_picture, s->next_picture_ptr)) < 0) return ret; } if (s->picture_structure!= PICT_FRAME) { int i; for (i = 0; i < 4; i++) { if (s->picture_structure == PICT_BOTTOM_FIELD) { s->current_picture.f.data[i] += s->current_picture.f.linesize[i]; } s->current_picture.f.linesize[i] *= 2; s->last_picture.f.linesize[i] *= 2; s->next_picture.f.linesize[i] *= 2; } } if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG2VIDEO) { s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra; s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter; } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) { s->dct_unquantize_intra = s->dct_unquantize_h263_intra; s->dct_unquantize_inter = s->dct_unquantize_h263_inter; } else { s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra; s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter; } if (s->dct_error_sum) { assert(s->avctx->noise_reduction && s->encoding); update_noise_reduction(s); } return 0; }


void helper_done(void) { env->pc = env->tsptr->tpc; env->npc = env->tsptr->tnpc + 4; PUT_CCR(env, env->tsptr->tstate >> 32); env->asi = (env->tsptr->tstate >> 24) & 0xff; change_pstate((env->tsptr->tstate >> 8) & 0xf3f); PUT_CWP64(env, env->tsptr->tstate & 0xff); env->tl--; env->tsptr = &env->ts[env->tl & MAXTL_MASK]; }


bool send_del_edge ( connection_t * c , const edge_t * e ) {
 return send_request ( c , "%d %x %s %s" , DEL_EDGE , rand ( ) , e -> from -> name , e -> to -> name ) ;
 }


static int x ( struct vcache * avc , int afun , struct vrequest * areq , \ struct afs_pdata * ain , struct afs_pdata * aout , \ afs_ucred_t * * acred ) DECL_PIOCTL ( PGetFID ) ;
 DECL_PIOCTL ( PSetAcl ) ;
 DECL_PIOCTL ( PStoreBehind ) ;
 DECL_PIOCTL ( PGCPAGs ) ;
 DECL_PIOCTL ( PGetAcl ) ;
 DECL_PIOCTL ( PNoop ) ;
 DECL_PIOCTL ( PBogus ) ;
 DECL_PIOCTL ( PGetFileCell ) ;
 DECL_PIOCTL ( PGetWSCell ) ;
 DECL_PIOCTL ( PGetUserCell ) ;
 DECL_PIOCTL ( PSetTokens ) ;
 DECL_PIOCTL ( PGetVolumeStatus ) ;
 DECL_PIOCTL ( PSetVolumeStatus ) ;
 DECL_PIOCTL ( PFlush ) ;
 DECL_PIOCTL ( PNewStatMount ) ;
 DECL_PIOCTL ( PGetTokens ) ;
 DECL_PIOCTL ( PUnlog ) ;
 DECL_PIOCTL ( PMariner ) ;
 DECL_PIOCTL ( PCheckServers ) ;
 DECL_PIOCTL ( PCheckVolNames ) ;
 DECL_PIOCTL ( PCheckAuth ) ;
 DECL_PIOCTL ( PFindVolume ) ;
 DECL_PIOCTL ( PViceAccess ) ;
 DECL_PIOCTL ( PSetCacheSize ) ;
 DECL_PIOCTL ( PGetCacheSize ) ;
 DECL_PIOCTL ( PRemoveCallBack ) ;
 DECL_PIOCTL ( PNewCell ) ;
 DECL_PIOCTL ( PNewAlias ) ;
 DECL_PIOCTL ( PListCells ) ;
 DECL_PIOCTL ( PListAliases ) ;
 DECL_PIOCTL ( PRemoveMount ) ;
 DECL_PIOCTL ( PGetCellStatus ) ;
 DECL_PIOCTL ( PSetCellStatus ) ;
 DECL_PIOCTL ( PFlushVolumeData ) ;
 DECL_PIOCTL ( PFlushAllVolumeData ) ;
 DECL_PIOCTL ( PGetVnodeXStatus ) ;
 DECL_PIOCTL ( PGetVnodeXStatus2 ) ;
 DECL_PIOCTL ( PSetSysName ) ;
 DECL_PIOCTL ( PSetSPrefs ) ;
 DECL_PIOCTL ( PSetSPrefs33 ) ;
 DECL_PIOCTL ( PGetSPrefs ) ;
 DECL_PIOCTL ( PExportAfs ) ;
 DECL_PIOCTL ( PGag ) ;
 DECL_PIOCTL ( PTwiddleRx ) ;
 DECL_PIOCTL ( PGetInitParams ) ;
 DECL_PIOCTL ( PGetRxkcrypt ) ;
 DECL_PIOCTL ( PSetRxkcrypt ) ;
 DECL_PIOCTL ( PGetCPrefs )


cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
    uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
	const cdf_section_header_t *shp;
	cdf_section_header_t sh;
	const uint8_t *p, *q, *e;
	int16_t s16;
	int32_t s32;
	uint32_t u32;
	int64_t s64;
	uint64_t u64;
	cdf_timestamp_t tp;
	size_t i, o, o4, nelements, j;
	cdf_property_info_t *inp;

	if (offs > UINT32_MAX / 4) {
		errno = EFTYPE;
		goto out;
	}
	shp = CAST(const cdf_section_header_t *, (const void *)
	    ((const char *)sst->sst_tab + offs));
	if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
		goto out;
	sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
	if (sh.sh_len > CDF_SHLEN_LIMIT) {
		errno = EFTYPE;
		goto out;
	}
	sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
	if (sh.sh_properties > CDF_PROP_LIMIT)
		goto out;
	DPRINTF(("section len: %u properties %u\n", sh.sh_len,
	    sh.sh_properties));
	if (*maxcount) {
		if (*maxcount > CDF_PROP_LIMIT)
			goto out;
		*maxcount += sh.sh_properties;
		inp = CAST(cdf_property_info_t *,
		    realloc(*info, *maxcount * sizeof(*inp)));
	} else {
		*maxcount = sh.sh_properties;
		inp = CAST(cdf_property_info_t *,
		    malloc(*maxcount * sizeof(*inp)));
	}
	if (inp == NULL)
		goto out;
	*info = inp;
	inp += *count;
	*count += sh.sh_properties;
	p = CAST(const uint8_t *, (const void *)
	    ((const char *)(const void *)sst->sst_tab +
	    offs + sizeof(sh)));
	e = CAST(const uint8_t *, (const void *)
	    (((const char *)(const void *)shp) + sh.sh_len));
	if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
		goto out;
	for (i = 0; i < sh.sh_properties; i++) {
		size_t ofs, tail = (i << 1) + 1;
		if (cdf_check_stream_offset(sst, h, p, tail * sizeof(uint32_t),
		    __LINE__) == -1)
			goto out;
		ofs = CDF_GETUINT32(p, tail);
		q = (const uint8_t *)(const void *)
		    ((const char *)(const void *)p + ofs
		    - 2 * sizeof(uint32_t));
		if (q > e) {
			DPRINTF(("Ran of the end %p > %p\n", q, e));
			goto out;
		}
		inp[i].pi_id = CDF_GETUINT32(p, i << 1);
		inp[i].pi_type = CDF_GETUINT32(q, 0);
		DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
		    i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
		if (inp[i].pi_type & CDF_VECTOR) {
			nelements = CDF_GETUINT32(q, 1);
			if (nelements == 0) {
				DPRINTF(("CDF_VECTOR with nelements == 0\n"));
				goto out;
			}
			o = 2;
		} else {
			nelements = 1;
			o = 1;
		}
		o4 = o * sizeof(uint32_t);
		if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
			goto unknown;
		switch (inp[i].pi_type & CDF_TYPEMASK) {
		case CDF_NULL:
		case CDF_EMPTY:
			break;
		case CDF_SIGNED16:
			if (inp[i].pi_type & CDF_VECTOR)
				goto unknown;
			(void)memcpy(&s16, &q[o4], sizeof(s16));
			inp[i].pi_s16 = CDF_TOLE2(s16);
			break;
		case CDF_SIGNED32:
			if (inp[i].pi_type & CDF_VECTOR)
				goto unknown;
			(void)memcpy(&s32, &q[o4], sizeof(s32));
			inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
			break;
		case CDF_BOOL:
		case CDF_UNSIGNED32:
			if (inp[i].pi_type & CDF_VECTOR)
				goto unknown;
			(void)memcpy(&u32, &q[o4], sizeof(u32));
			inp[i].pi_u32 = CDF_TOLE4(u32);
			break;
		case CDF_SIGNED64:
			if (inp[i].pi_type & CDF_VECTOR)
				goto unknown;
			(void)memcpy(&s64, &q[o4], sizeof(s64));
			inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
			break;
		case CDF_UNSIGNED64:
			if (inp[i].pi_type & CDF_VECTOR)
				goto unknown;
			(void)memcpy(&u64, &q[o4], sizeof(u64));
			inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
			break;
		case CDF_FLOAT:
			if (inp[i].pi_type & CDF_VECTOR)
				goto unknown;
			(void)memcpy(&u32, &q[o4], sizeof(u32));
			u32 = CDF_TOLE4(u32);
			memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
			break;
		case CDF_DOUBLE:
			if (inp[i].pi_type & CDF_VECTOR)
				goto unknown;
			(void)memcpy(&u64, &q[o4], sizeof(u64));
			u64 = CDF_TOLE8((uint64_t)u64);
			memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
			break;
		case CDF_LENGTH32_STRING:
		case CDF_LENGTH32_WSTRING:
			if (nelements > 1) {
				size_t nelem = inp - *info;
				if (*maxcount > CDF_PROP_LIMIT
				    || nelements > CDF_PROP_LIMIT)
					goto out;
				*maxcount += nelements;
				inp = CAST(cdf_property_info_t *,
				    realloc(*info, *maxcount * sizeof(*inp)));
				if (inp == NULL)
					goto out;
				*info = inp;
				inp = *info + nelem;
			}
			DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
			    nelements));
			for (j = 0; j < nelements && i < sh.sh_properties;
			    j++, i++)
			{
				uint32_t l = CDF_GETUINT32(q, o);
				inp[i].pi_str.s_len = l;
				inp[i].pi_str.s_buf = (const char *)
				    (const void *)(&q[o4 + sizeof(l)]);
				DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
				    "u, s = %s\n", l,
				    CDF_ROUND(l, sizeof(l)),
				    inp[i].pi_str.s_buf));
				if (l & 1)
					l++;
				o += l >> 1;
				if (q + o >= e)
					goto out;
				o4 = o * sizeof(uint32_t);
			}
			i--;
			break;
		case CDF_FILETIME:
			if (inp[i].pi_type & CDF_VECTOR)
				goto unknown;
			(void)memcpy(&tp, &q[o4], sizeof(tp));
			inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
			break;
		case CDF_CLIPBOARD:
			if (inp[i].pi_type & CDF_VECTOR)
				goto unknown;
			break;
		default:
		unknown:
			DPRINTF(("Don't know how to deal with %x\n",
			    inp[i].pi_type));
			break;
		}
	}
	return 0;
out:
	free(*info);
	return -1;
}


static int gif_image_write_image(ByteIOContext *pb, int x1, int y1, int width, int height, const uint8_t *buf, int linesize, int pix_fmt) { PutBitContext p; uint8_t buffer[200]; /* 100 * 9 / 8 = 113 */ int i, left, w, v; const uint8_t *ptr; /* image block */ put_byte(pb, 0x2c); put_le16(pb, x1); put_le16(pb, y1); put_le16(pb, width); put_le16(pb, height); put_byte(pb, 0x00); /* flags */ /* no local clut */ put_byte(pb, 0x08); left= width * height; init_put_bits(&p, buffer, 130); /* * the thing here is the bitstream is written as little packets, with a size byte before * but it's still the same bitstream between packets (no flush !) */ ptr = buf; w = width; while(left>0) { gif_put_bits_rev(&p, 9, 0x0100); /* clear code */ for(i=0;i<GIF_CHUNKS;i++) { if (pix_fmt == PIX_FMT_RGB24) { v = gif_clut_index(ptr[0], ptr[1], ptr[2]); ptr+=3; } else { v = *ptr++; } gif_put_bits_rev(&p, 9, v); if (--w == 0) { w = width; buf += linesize; ptr = buf; } } if(left<=GIF_CHUNKS) { gif_put_bits_rev(&p, 9, 0x101); /* end of stream */ gif_flush_put_bits_rev(&p); } if(pbBufPtr(&p) - p.buf > 0) { put_byte(pb, pbBufPtr(&p) - p.buf); /* byte count of the packet */ put_buffer(pb, p.buf, pbBufPtr(&p) - p.buf); /* the actual buffer */ p.buf_ptr = p.buf; /* dequeue the bytes off the bitstream */ } if(left<=GIF_CHUNKS) { put_byte(pb, 0x00); /* end of image block */ } left-=GIF_CHUNKS; } return 0; }


static void qmp_input_get_next_type(Visitor *v, int *kind, const int *qobjects, const char *name, Error **errp) { QmpInputVisitor *qiv = to_qiv(v); QObject *qobj = qmp_input_get_object(qiv, name, false); if (!qobj) { error_setg(errp, QERR_MISSING_PARAMETER, name ? name : "null"); return; } *kind = qobjects[qobject_type(qobj)]; }


void kvm_arch_update_guest_debug(CPUState *env, struct kvm_guest_debug *dbg) { const uint8_t type_code[] = { [GDB_BREAKPOINT_HW] = 0x0, [GDB_WATCHPOINT_WRITE] = 0x1, [GDB_WATCHPOINT_ACCESS] = 0x3 }; const uint8_t len_code[] = { [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2 }; int n; if (kvm_sw_breakpoints_active(env)) dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP; if (nb_hw_breakpoint > 0) { dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP; dbg->arch.debugreg[7] = 0x0600; for (n = 0; n < nb_hw_breakpoint; n++) { dbg->arch.debugreg[n] = hw_breakpoint[n].addr; dbg->arch.debugreg[7] |= (2 << (n * 2)) | (type_code[hw_breakpoint[n].type] << (16 + n*4)) | (len_code[hw_breakpoint[n].len] << (18 + n*4)); } } /* Legal xcr0 for loading */ env->xcr0 = 1; }


static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { Jpeg2000DecoderContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; int tileno, ret; s->avctx = avctx; s->buf = s->buf_start = avpkt->data; s->buf_end = s->buf_start + avpkt->size; s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles // reduction factor, i.e number of resolution levels to skip s->reduction_factor = s->lowres; if (s->buf_end - s->buf < 2) return AVERROR_INVALIDDATA; // check if the image is in jp2 format if ((AV_RB32(s->buf) == 12) && (AV_RB32(s->buf + 4) == JP2_SIG_TYPE) && (AV_RB32(s->buf + 8) == JP2_SIG_VALUE)) { if (!jp2_find_codestream(s)) { av_log(avctx, AV_LOG_ERROR, "Could not find Jpeg2000 codestream atom.\n"); return AVERROR_INVALIDDATA; } } if (bytestream_get_be16(&s->buf) != JPEG2000_SOC) { av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n"); return AVERROR_INVALIDDATA; } if (ret = jpeg2000_read_main_headers(s)) goto end; /* get picture buffer */ if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) { av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n"); goto end; } picture->pict_type = AV_PICTURE_TYPE_I; picture->key_frame = 1; if (ret = jpeg2000_read_bitstream_packets(s)) goto end; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture)) goto end; *got_frame = 1; end: jpeg2000_dec_cleanup(s); return ret ? ret : s->buf - s->buf_start; }


void gdImageWBMPCtx (gdImagePtr image, int fg, gdIOCtx * out)
{
	int x, y, pos;
	Wbmp *wbmp;

	/* create the WBMP */
	if ((wbmp = createwbmp (gdImageSX (image), gdImageSY (image), WBMP_WHITE)) == NULL) {
		gd_error("Could not create WBMP");
		return;
	}

	/* fill up the WBMP structure */
	pos = 0;
	for (y = 0; y < gdImageSY(image); y++) {
		for (x = 0; x < gdImageSX(image); x++) {
			if (gdImageGetPixel (image, x, y) == fg) {
				wbmp->bitmap[pos] = WBMP_BLACK;
			}
			pos++;
		}
	}

	/* write the WBMP to a gd file descriptor */
	if (writewbmp (wbmp, &gd_putout, out)) {
		gd_error("Could not save WBMP");
	}
	/* des submitted this bugfix: gdFree the memory. */
	freewbmp(wbmp);
}


static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache) { uint8_t bus_n; uint16_t result; switch (cache->type) { case PCI_REQ_ID_BDF: result = pci_get_bdf(cache->dev); break; case PCI_REQ_ID_SECONDARY_BUS: bus_n = pci_bus_num(cache->dev->bus); result = PCI_BUILD_BDF(bus_n, 0); break; default: error_printf("Invalid PCI requester ID cache type: %d\n", cache->type); exit(1); break; } return result; }


static int clone_slice ( H264Context * dst , H264Context * src ) {
 memcpy ( dst -> block_offset , src -> block_offset , sizeof ( dst -> block_offset ) ) ;
 dst -> cur_pic_ptr = src -> cur_pic_ptr ;
 dst -> cur_pic = src -> cur_pic ;
 dst -> linesize = src -> linesize ;
 dst -> uvlinesize = src -> uvlinesize ;
 dst -> first_field = src -> first_field ;
 dst -> prev_poc_msb = src -> prev_poc_msb ;
 dst -> prev_poc_lsb = src -> prev_poc_lsb ;
 dst -> prev_frame_num_offset = src -> prev_frame_num_offset ;
 dst -> prev_frame_num = src -> prev_frame_num ;
 dst -> short_ref_count = src -> short_ref_count ;
 memcpy ( dst -> short_ref , src -> short_ref , sizeof ( dst -> short_ref ) ) ;
 memcpy ( dst -> long_ref , src -> long_ref , sizeof ( dst -> long_ref ) ) ;
 memcpy ( dst -> default_ref_list , src -> default_ref_list , sizeof ( dst -> default_ref_list ) ) ;
 memcpy ( dst -> dequant4_coeff , src -> dequant4_coeff , sizeof ( src -> dequant4_coeff ) ) ;
 memcpy ( dst -> dequant8_coeff , src -> dequant8_coeff , sizeof ( src -> dequant8_coeff ) ) ;
 return 0 ;
 }


LPSTR tr_esc_str(LPCSTR arg, bool format)
{
	LPSTR tmp = NULL;
	size_t cs = 0, x, ds, len;
	size_t s;

	if (NULL == arg)
		return NULL;

	s = strlen(arg);

	/* Find trailing whitespaces */
	while ((s > 0) && isspace(arg[s - 1]))
		s--;

	/* Prepare a initial buffer with the size of the result string. */
	ds = s + 1;

	if (s)
		tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR));

	if (NULL == tmp)
	{
		fprintf(stderr,  "Could not allocate string buffer.\n");
		exit(-2);
	}

	/* Copy character for character and check, if it is necessary to escape. */
	memset(tmp, 0, ds * sizeof(CHAR));

	for (x = 0; x < s; x++)
	{
		switch (arg[x])
		{
			case '<':
				len = format ? 13 : 4;
				ds += len - 1;
				tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR));

				if (NULL == tmp)
				{
					fprintf(stderr,  "Could not reallocate string buffer.\n");
					exit(-3);
				}

				if (format)
					/* coverity[buffer_size] */
					strncpy(&tmp[cs], "<replaceable>", len);
				else
					/* coverity[buffer_size] */
					strncpy(&tmp[cs], "<", len);

				cs += len;
				break;

			case '>':
				len = format ? 14 : 4;
				ds += len - 1;
				tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR));

				if (NULL == tmp)
				{
					fprintf(stderr,  "Could not reallocate string buffer.\n");
					exit(-4);
				}

				if (format)
					/* coverity[buffer_size] */
					strncpy(&tmp[cs], "</replaceable>", len);
				else
					/* coverity[buffer_size] */
					strncpy(&tmp[cs], "<", len);

				cs += len;
				break;

			case '\'':
				ds += 5;
				tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR));

				if (NULL == tmp)
				{
					fprintf(stderr,  "Could not reallocate string buffer.\n");
					exit(-5);
				}

				tmp[cs++] = '&';
				tmp[cs++] = 'a';
				tmp[cs++] = 'p';
				tmp[cs++] = 'o';
				tmp[cs++] = 's';
				tmp[cs++] = ';';
				break;

			case '"':
				ds += 5;
				tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR));

				if (NULL == tmp)
				{
					fprintf(stderr,  "Could not reallocate string buffer.\n");
					exit(-6);
				}

				tmp[cs++] = '&';
				tmp[cs++] = 'q';
				tmp[cs++] = 'u';
				tmp[cs++] = 'o';
				tmp[cs++] = 't';
				tmp[cs++] = ';';
				break;

			case '&':
				ds += 4;
				tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR));

				if (NULL == tmp)
				{
					fprintf(stderr,  "Could not reallocate string buffer.\n");
					exit(-7);
				}

				tmp[cs++] = '&';
				tmp[cs++] = 'a';
				tmp[cs++] = 'm';
				tmp[cs++] = 'p';
				tmp[cs++] = ';';
				break;

			default:
				tmp[cs++] = arg[x];
				break;
		}

		/* Assure, the string is '\0' terminated. */
		tmp[ds - 1] = '\0';
	}

	return tmp;
}


static int dissect_h245_NumericString_SIZE_0_40 ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_NumericString ( tvb , offset , actx , tree , hf_index , 0 , 40 , FALSE ) ;
 return offset ;
 }


static plist_t parse_dict_node(struct bplist_data *bplist, const char** bnode, uint64_t size)
{
    uint64_t j;
    uint64_t str_i = 0, str_j = 0;
    uint64_t index1, index2;
    plist_data_t data = plist_new_plist_data();
    const char *const end_data = bplist->data + bplist->size;
    const char *index1_ptr = NULL;
    const char *index2_ptr = NULL;

    data->type = PLIST_DICT;
    data->length = size;

    plist_t node = node_create(NULL, data);

    for (j = 0; j < data->length; j++) {
        str_i = j * bplist->dict_size;
        str_j = (j + size) * bplist->dict_size;
        index1_ptr = (*bnode) + str_i;
        index2_ptr = (*bnode) + str_j;

        if ((index1_ptr < bplist->data || index1_ptr + bplist->dict_size >= end_data) ||
            (index2_ptr < bplist->data || index2_ptr + bplist->dict_size >= end_data)) {
            plist_free(node);
            return NULL;
        }

        index1 = UINT_TO_HOST(index1_ptr, bplist->dict_size);
        index2 = UINT_TO_HOST(index2_ptr, bplist->dict_size);

        if (index1 >= bplist->num_objects) {
            plist_free(node);
            return NULL;
        }
        if (index2 >= bplist->num_objects) {
            plist_free(node);
            return NULL;
        }

        /* process key node */
        plist_t key = parse_bin_node_at_index(bplist, index1);
        if (!key) {
            plist_free(node);
            return NULL;
        }
        /* enforce key type */
        plist_get_data(key)->type = PLIST_KEY;
        if (!plist_get_data(key)->strval) {
            fprintf(stderr, "ERROR: Malformed binary plist dict, invalid key node encountered!\n");
            plist_free(key);
            plist_free(node);
            return NULL;
        }

        /* process value node */
        plist_t val = parse_bin_node_at_index(bplist, index2);
        if (!val) {
            plist_free(key);
            plist_free(node);
            return NULL;
        }

        node_attach(node, key);
        node_attach(node, val);
    }

    return node;
}


static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)
{
	BYTE* newBitMask;

	if (Stream_GetRemainingLength(s) < 8)
		return FALSE;

	Stream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */
	Stream_Read_UINT8(s, iconInfo->cacheId);     /* cacheId (1 byte) */
	Stream_Read_UINT8(s, iconInfo->bpp);         /* bpp (1 byte) */

	if ((iconInfo->bpp < 1) || (iconInfo->bpp > 32))
	{
		WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", iconInfo->bpp);
		return FALSE;
	}

	Stream_Read_UINT16(s, iconInfo->width);  /* width (2 bytes) */
	Stream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */

	/* cbColorTable is only present when bpp is 1, 4 or 8 */
	switch (iconInfo->bpp)
	{
		case 1:
		case 4:
		case 8:
			if (Stream_GetRemainingLength(s) < 2)
				return FALSE;

			Stream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */
			break;

		default:
			iconInfo->cbColorTable = 0;
			break;
	}

	if (Stream_GetRemainingLength(s) < 4)
		return FALSE;

	Stream_Read_UINT16(s, iconInfo->cbBitsMask);  /* cbBitsMask (2 bytes) */
	Stream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */

	/* bitsMask */
	newBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);

	if (!newBitMask)
	{
		free(iconInfo->bitsMask);
		iconInfo->bitsMask = NULL;
		return FALSE;
	}

	iconInfo->bitsMask = newBitMask;
	if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)
		return FALSE;
	Stream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);

	/* colorTable */
	if (iconInfo->colorTable == NULL)
	{
		if (iconInfo->cbColorTable)
		{
			iconInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable);

			if (!iconInfo->colorTable)
				return FALSE;
		}
	}
	else if (iconInfo->cbColorTable)
	{
		BYTE* new_tab;
		new_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable);

		if (!new_tab)
		{
			free(iconInfo->colorTable);
			iconInfo->colorTable = NULL;
			return FALSE;
		}

		iconInfo->colorTable = new_tab;
	}
	else
	{
		free(iconInfo->colorTable);
		iconInfo->colorTable = NULL;
	}

	if (iconInfo->colorTable)
	{
		if (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)
			return FALSE;
		Stream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);
	}

	/* bitsColor */
	newBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);

	if (!newBitMask)
	{
		free(iconInfo->bitsColor);
		iconInfo->bitsColor = NULL;
		return FALSE;
	}

	iconInfo->bitsColor = newBitMask;
	if (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)
		return FALSE;
	Stream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);
	return TRUE;
}


static UINT serial_process_irp_create(SERIAL_DEVICE* serial, IRP* irp)
{
	DWORD DesiredAccess;
	DWORD SharedAccess;
	DWORD CreateDisposition;
	UINT32 PathLength;

	if (Stream_GetRemainingLength(irp->input) < 32)
		return ERROR_INVALID_DATA;

	Stream_Read_UINT32(irp->input, DesiredAccess);     /* DesiredAccess (4 bytes) */
	Stream_Seek_UINT64(irp->input);                    /* AllocationSize (8 bytes) */
	Stream_Seek_UINT32(irp->input);                    /* FileAttributes (4 bytes) */
	Stream_Read_UINT32(irp->input, SharedAccess);      /* SharedAccess (4 bytes) */
	Stream_Read_UINT32(irp->input, CreateDisposition); /* CreateDisposition (4 bytes) */
	Stream_Seek_UINT32(irp->input);                    /* CreateOptions (4 bytes) */
	Stream_Read_UINT32(irp->input, PathLength);        /* PathLength (4 bytes) */

	if (Stream_GetRemainingLength(irp->input) < PathLength)
		return ERROR_INVALID_DATA;

	Stream_Seek(irp->input, PathLength); /* Path (variable) */
	assert(PathLength == 0);             /* MS-RDPESP 2.2.2.2 */
#ifndef _WIN32
	/* Windows 2012 server sends on a first call :
	 *     DesiredAccess     = 0x00100080: SYNCHRONIZE | FILE_READ_ATTRIBUTES
	 *     SharedAccess      = 0x00000007: FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ
	 *     CreateDisposition = 0x00000001: CREATE_NEW
	 *
	 * then Windows 2012 sends :
	 *     DesiredAccess     = 0x00120089: SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES |
	 * FILE_READ_EA | FILE_READ_DATA SharedAccess      = 0x00000007: FILE_SHARE_DELETE |
	 * FILE_SHARE_WRITE | FILE_SHARE_READ CreateDisposition = 0x00000001: CREATE_NEW
	 *
	 * assert(DesiredAccess == (GENERIC_READ | GENERIC_WRITE));
	 * assert(SharedAccess == 0);
	 * assert(CreateDisposition == OPEN_EXISTING);
	 *
	 */
	WLog_Print(serial->log, WLOG_DEBUG,
	           "DesiredAccess: 0x%" PRIX32 ", SharedAccess: 0x%" PRIX32
	           ", CreateDisposition: 0x%" PRIX32 "",
	           DesiredAccess, SharedAccess, CreateDisposition);
	/* FIXME: As of today only the flags below are supported by CommCreateFileA: */
	DesiredAccess = GENERIC_READ | GENERIC_WRITE;
	SharedAccess = 0;
	CreateDisposition = OPEN_EXISTING;
#endif
	serial->hComm =
	    CreateFile(serial->device.name, DesiredAccess, SharedAccess, NULL, /* SecurityAttributes */
	               CreateDisposition, 0,                                   /* FlagsAndAttributes */
	               NULL);                                                  /* TemplateFile */

	if (!serial->hComm || (serial->hComm == INVALID_HANDLE_VALUE))
	{
		WLog_Print(serial->log, WLOG_WARN, "CreateFile failure: %s last-error: 0x%08" PRIX32 "",
		           serial->device.name, GetLastError());
		irp->IoStatus = STATUS_UNSUCCESSFUL;
		goto error_handle;
	}

	_comm_setServerSerialDriver(serial->hComm, serial->ServerSerialDriverId);
	_comm_set_permissive(serial->hComm, serial->permissive);
	/* NOTE: binary mode/raw mode required for the redirection. On
	 * Linux, CommCreateFileA forces this setting.
	 */
	/* ZeroMemory(&dcb, sizeof(DCB)); */
	/* dcb.DCBlength = sizeof(DCB); */
	/* GetCommState(serial->hComm, &dcb); */
	/* dcb.fBinary = TRUE; */
	/* SetCommState(serial->hComm, &dcb); */
	assert(irp->FileId == 0);
	irp->FileId = irp->devman->id_sequence++; /* FIXME: why not ((WINPR_COMM*)hComm)->fd? */
	irp->IoStatus = STATUS_SUCCESS;
	WLog_Print(serial->log, WLOG_DEBUG, "%s (DeviceId: %" PRIu32 ", FileId: %" PRIu32 ") created.",
	           serial->device.name, irp->device->id, irp->FileId);
error_handle:
	Stream_Write_UINT32(irp->output, irp->FileId); /* FileId (4 bytes) */
	Stream_Write_UINT8(irp->output, 0);            /* Information (1 byte) */
	return CHANNEL_RC_OK;
}


static void free_deregistered_data ( gpointer data , gpointer user_data _U_ ) {
 g_free ( data ) ;
 }