static int matroska_parse_tracks ( AVFormatContext * s ) {
 MatroskaDemuxContext * matroska = s -> priv_data ;
 MatroskaTrack * tracks = matroska -> tracks . elem ;
 AVStream * st ;
 int i , j , ret ;
 for ( i = 0 ;
 i < matroska -> tracks . nb_elem ;
 i ++ ) {
 MatroskaTrack * track = & tracks [ i ] ;
 enum AVCodecID codec_id = AV_CODEC_ID_NONE ;
 EbmlList * encodings_list = & track -> encodings ;
 MatroskaTrackEncoding * encodings = encodings_list -> elem ;
 uint8_t * extradata = NULL ;
 int extradata_size = 0 ;
 int extradata_offset = 0 ;
 AVIOContext b ;
 if ( track -> type != MATROSKA_TRACK_TYPE_VIDEO && track -> type != MATROSKA_TRACK_TYPE_AUDIO && track -> type != MATROSKA_TRACK_TYPE_SUBTITLE ) {
 av_log ( matroska -> ctx , AV_LOG_INFO , "Unknown or unsupported track type %" PRIu64 "\n" , track -> type ) ;
 continue ;
 }
 if ( ! track -> codec_id ) continue ;
 if ( track -> type == MATROSKA_TRACK_TYPE_VIDEO ) {
 if ( ! track -> default_duration && track -> video . frame_rate > 0 ) track -> default_duration = 1000000000 / track -> video . frame_rate ;
 if ( ! track -> video . display_width ) track -> video . display_width = track -> video . pixel_width ;
 if ( ! track -> video . display_height ) track -> video . display_height = track -> video . pixel_height ;
 }
 else if ( track -> type == MATROSKA_TRACK_TYPE_AUDIO ) {
 if ( ! track -> audio . out_samplerate ) track -> audio . out_samplerate = track -> audio . samplerate ;
 }
 if ( encodings_list -> nb_elem > 1 ) {
 av_log ( matroska -> ctx , AV_LOG_ERROR , "Multiple combined encodings not supported" ) ;
 }
 else if ( encodings_list -> nb_elem == 1 ) {
 if ( encodings [ 0 ] . type || ( # if CONFIG_ZLIB encodings [ 0 ] . compression . algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB && # endif # if CONFIG_BZLIB encodings [ 0 ] . compression . algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB && # endif # if CONFIG_LZO encodings [ 0 ] . compression . algo != MATROSKA_TRACK_ENCODING_COMP_LZO && # endif encodings [ 0 ] . compression . algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP ) ) {
 encodings [ 0 ] . scope = 0 ;
 av_log ( matroska -> ctx , AV_LOG_ERROR , "Unsupported encoding type" ) ;
 }
 else if ( track -> codec_priv . size && encodings [ 0 ] . scope & 2 ) {
 uint8_t * codec_priv = track -> codec_priv . data ;
 int ret = matroska_decode_buffer ( & track -> codec_priv . data , & track -> codec_priv . size , track ) ;
 if ( ret < 0 ) {
 track -> codec_priv . data = NULL ;
 track -> codec_priv . size = 0 ;
 av_log ( matroska -> ctx , AV_LOG_ERROR , "Failed to decode codec private data\n" ) ;
 }
 if ( codec_priv != track -> codec_priv . data ) av_free ( codec_priv ) ;
 }
 }
 for ( j = 0 ;
 ff_mkv_codec_tags [ j ] . id != AV_CODEC_ID_NONE ;
 j ++ ) {
 if ( ! strncmp ( ff_mkv_codec_tags [ j ] . str , track -> codec_id , strlen ( ff_mkv_codec_tags [ j ] . str ) ) ) {
 codec_id = ff_mkv_codec_tags [ j ] . id ;
 break ;
 }
 }
 st = track -> stream = avformat_new_stream ( s , NULL ) ;
 if ( ! st ) return AVERROR ( ENOMEM ) ;
 if ( ! strcmp ( track -> codec_id , "V_MS/VFW/FOURCC" ) && track -> codec_priv . size >= 40 && track -> codec_priv . data ) {
 track -> ms_compat = 1 ;
 track -> video . fourcc = AV_RL32 ( track -> codec_priv . data + 16 ) ;
 codec_id = ff_codec_get_id ( ff_codec_bmp_tags , track -> video . fourcc ) ;
 extradata_offset = 40 ;
 }
 else if ( ! strcmp ( track -> codec_id , "A_MS/ACM" ) && track -> codec_priv . size >= 14 && track -> codec_priv . data ) {
 int ret ;
 ffio_init_context ( & b , track -> codec_priv . data , track -> codec_priv . size , 0 , NULL , NULL , NULL , NULL ) ;
 ret = ff_get_wav_header ( & b , st -> codec , track -> codec_priv . size ) ;
 if ( ret < 0 ) return ret ;
 codec_id = st -> codec -> codec_id ;
 extradata_offset = FFMIN ( track -> codec_priv . size , 18 ) ;
 }
 else if ( ! strcmp ( track -> codec_id , "V_QUICKTIME" ) && ( track -> codec_priv . size >= 86 ) && ( track -> codec_priv . data ) ) {
 track -> video . fourcc = AV_RL32 ( track -> codec_priv . data ) ;
 codec_id = ff_codec_get_id ( ff_codec_movvideo_tags , track -> video . fourcc ) ;
 }
 else if ( codec_id == AV_CODEC_ID_PCM_S16BE ) {
 switch ( track -> audio . bitdepth ) {
 case 8 : codec_id = AV_CODEC_ID_PCM_U8 ;
 break ;
 case 24 : codec_id = AV_CODEC_ID_PCM_S24BE ;
 break ;
 case 32 : codec_id = AV_CODEC_ID_PCM_S32BE ;
 break ;
 }
 }
 else if ( codec_id == AV_CODEC_ID_PCM_S16LE ) {
 switch ( track -> audio . bitdepth ) {
 case 8 : codec_id = AV_CODEC_ID_PCM_U8 ;
 break ;
 case 24 : codec_id = AV_CODEC_ID_PCM_S24LE ;
 break ;
 case 32 : codec_id = AV_CODEC_ID_PCM_S32LE ;
 break ;
 }
 }
 else if ( codec_id == AV_CODEC_ID_PCM_F32LE && track -> audio . bitdepth == 64 ) {
 codec_id = AV_CODEC_ID_PCM_F64LE ;
 }
 else if ( codec_id == AV_CODEC_ID_AAC && ! track -> codec_priv . size ) {
 int profile = matroska_aac_profile ( track -> codec_id ) ;
 int sri = matroska_aac_sri ( track -> audio . samplerate ) ;
 extradata = av_mallocz ( 5 + FF_INPUT_BUFFER_PADDING_SIZE ) ;
 if ( ! extradata ) return AVERROR ( ENOMEM ) ;
 extradata [ 0 ] = ( profile << 3 ) | ( ( sri & 0x0E ) >> 1 ) ;
 extradata [ 1 ] = ( ( sri & 0x01 ) << 7 ) | ( track -> audio . channels << 3 ) ;
 if ( strstr ( track -> codec_id , "SBR" ) ) {
 sri = matroska_aac_sri ( track -> audio . out_samplerate ) ;
 extradata [ 2 ] = 0x56 ;
 extradata [ 3 ] = 0xE5 ;
 extradata [ 4 ] = 0x80 | ( sri << 3 ) ;
 extradata_size = 5 ;
 }
 else extradata_size = 2 ;
 }
 else if ( codec_id == AV_CODEC_ID_ALAC && track -> codec_priv . size ) {
 extradata_size = 12 + track -> codec_priv . size ;
 extradata = av_mallocz ( extradata_size + FF_INPUT_BUFFER_PADDING_SIZE ) ;
 if ( ! extradata ) return AVERROR ( ENOMEM ) ;
 AV_WB32 ( extradata , extradata_size ) ;
 memcpy ( & extradata [ 4 ] , "alac" , 4 ) ;
 AV_WB32 ( & extradata [ 8 ] , 0 ) ;
 memcpy ( & extradata [ 12 ] , track -> codec_priv . data , track -> codec_priv . size ) ;
 }
 else if ( codec_id == AV_CODEC_ID_TTA ) {
 extradata_size = 30 ;
 extradata = av_mallocz ( extradata_size ) ;
 if ( ! extradata ) return AVERROR ( ENOMEM ) ;
 ffio_init_context ( & b , extradata , extradata_size , 1 , NULL , NULL , NULL , NULL ) ;
 avio_write ( & b , "TTA1" , 4 ) ;
 avio_wl16 ( & b , 1 ) ;
 avio_wl16 ( & b , track -> audio . channels ) ;
 avio_wl16 ( & b , track -> audio . bitdepth ) ;
 avio_wl32 ( & b , track -> audio . out_samplerate ) ;
 avio_wl32 ( & b , matroska -> ctx -> duration * track -> audio . out_samplerate ) ;
 }
 else if ( codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 || codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40 ) {
 extradata_offset = 26 ;
 }
 else if ( codec_id == AV_CODEC_ID_RA_144 ) {
 track -> audio . out_samplerate = 8000 ;
 track -> audio . channels = 1 ;
 }
 else if ( codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK || codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR ) {
 int flavor ;
 ffio_init_context ( & b , track -> codec_priv . data , track -> codec_priv . size , 0 , NULL , NULL , NULL , NULL ) ;
 avio_skip ( & b , 22 ) ;
 flavor = avio_rb16 ( & b ) ;
 track -> audio . coded_framesize = avio_rb32 ( & b ) ;
 avio_skip ( & b , 12 ) ;
 track -> audio . sub_packet_h = avio_rb16 ( & b ) ;
 track -> audio . frame_size = avio_rb16 ( & b ) ;
 track -> audio . sub_packet_size = avio_rb16 ( & b ) ;
 if ( flavor <= 0 || track -> audio . coded_framesize <= 0 || track -> audio . sub_packet_h <= 0 || track -> audio . frame_size <= 0 || track -> audio . sub_packet_size <= 0 ) return AVERROR_INVALIDDATA ;
 track -> audio . buf = av_malloc ( track -> audio . frame_size * track -> audio . sub_packet_h ) ;
 if ( codec_id == AV_CODEC_ID_RA_288 ) {
 st -> codec -> block_align = track -> audio . coded_framesize ;
 track -> codec_priv . size = 0 ;
 }
 else {
 if ( codec_id == AV_CODEC_ID_SIPR && flavor < 4 ) {
 const int sipr_bit_rate [ 4 ] = {
 6504 , 8496 , 5000 , 16000 }
 ;
 track -> audio . sub_packet_size = ff_sipr_subpk_size [ flavor ] ;
 st -> codec -> bit_rate = sipr_bit_rate [ flavor ] ;
 }
 st -> codec -> block_align = track -> audio . sub_packet_size ;
 extradata_offset = 78 ;
 }
 }
 else if ( codec_id == AV_CODEC_ID_FLAC && track -> codec_priv . size ) {
 ret = matroska_parse_flac ( s , track , & extradata_offset ) ;
 if ( ret < 0 ) return ret ;
 }
 track -> codec_priv . size -= extradata_offset ;
 if ( codec_id == AV_CODEC_ID_NONE ) av_log ( matroska -> ctx , AV_LOG_INFO , "Unknown/unsupported AVCodecID %s.\n" , track -> codec_id ) ;
 if ( track -> time_scale < 0.01 ) track -> time_scale = 1.0 ;
 avpriv_set_pts_info ( st , 64 , matroska -> time_scale * track -> time_scale , 1000 * 1000 * 1000 ) ;
 track -> codec_delay = av_rescale_q ( track -> codec_delay , ( AVRational ) {
 1 , 1000000000 }
 , st -> time_base ) ;
 st -> codec -> codec_id = codec_id ;
 st -> start_time = 0 ;
 if ( strcmp ( track -> language , "und" ) ) av_dict_set ( & st -> metadata , "language" , track -> language , 0 ) ;
 av_dict_set ( & st -> metadata , "title" , track -> name , 0 ) ;
 if ( track -> flag_default ) st -> disposition |= AV_DISPOSITION_DEFAULT ;
 if ( track -> flag_forced ) st -> disposition |= AV_DISPOSITION_FORCED ;
 if ( ! st -> codec -> extradata ) {
 if ( extradata ) {
 st -> codec -> extradata = extradata ;
 st -> codec -> extradata_size = extradata_size ;
 }
 else if ( track -> codec_priv . data && track -> codec_priv . size > 0 ) {
 st -> codec -> extradata = av_mallocz ( track -> codec_priv . size + FF_INPUT_BUFFER_PADDING_SIZE ) ;
 if ( ! st -> codec -> extradata ) return AVERROR ( ENOMEM ) ;
 st -> codec -> extradata_size = track -> codec_priv . size ;
 memcpy ( st -> codec -> extradata , track -> codec_priv . data + extradata_offset , track -> codec_priv . size ) ;
 }
 }
 if ( track -> type == MATROSKA_TRACK_TYPE_VIDEO ) {
 st -> codec -> codec_type = AVMEDIA_TYPE_VIDEO ;
 st -> codec -> codec_tag = track -> video . fourcc ;
 st -> codec -> width = track -> video . pixel_width ;
 st -> codec -> height = track -> video . pixel_height ;
 av_reduce ( & st -> sample_aspect_ratio . num , & st -> sample_aspect_ratio . den , st -> codec -> height * track -> video . display_width , st -> codec -> width * track -> video . display_height , 255 ) ;
 if ( st -> codec -> codec_id != AV_CODEC_ID_H264 && st -> codec -> codec_id != AV_CODEC_ID_HEVC ) st -> need_parsing = AVSTREAM_PARSE_HEADERS ;
 if ( track -> default_duration ) {
 av_reduce ( & st -> avg_frame_rate . num , & st -> avg_frame_rate . den , 1000000000 , track -> default_duration , 30000 ) ;
 }
 if ( track -> video . stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB && track -> video . stereo_mode != 10 && track -> video . stereo_mode != 12 ) {
 int ret = ff_mkv_stereo3d_conv ( st , track -> video . stereo_mode ) ;
 if ( ret < 0 ) return ret ;
 }
 }
 else if ( track -> type == MATROSKA_TRACK_TYPE_AUDIO ) {
 st -> codec -> codec_type = AVMEDIA_TYPE_AUDIO ;
 st -> codec -> sample_rate = track -> audio . out_samplerate ;
 st -> codec -> channels = track -> audio . channels ;
 if ( st -> codec -> codec_id != AV_CODEC_ID_AAC ) st -> need_parsing = AVSTREAM_PARSE_HEADERS ;
 }
 else if ( track -> type == MATROSKA_TRACK_TYPE_SUBTITLE ) {
 st -> codec -> codec_type = AVMEDIA_TYPE_SUBTITLE ;
 if ( st -> codec -> codec_id == AV_CODEC_ID_SSA ) matroska -> contains_ssa = 1 ;
 }
 }
 return 0 ;
 }


static int term_can_read(void *opaque) { return 128; }


static void build_pci_bus_end(PCIBus *bus, void *bus_state) { AcpiBuildPciBusHotplugState *child = bus_state; AcpiBuildPciBusHotplugState *parent = child->parent; GArray *bus_table = build_alloc_array(); DECLARE_BITMAP(slot_hotplug_enable, PCI_SLOT_MAX); DECLARE_BITMAP(slot_device_present, PCI_SLOT_MAX); DECLARE_BITMAP(slot_device_system, PCI_SLOT_MAX); DECLARE_BITMAP(slot_device_vga, PCI_SLOT_MAX); DECLARE_BITMAP(slot_device_qxl, PCI_SLOT_MAX); uint8_t op; int i; QObject *bsel; GArray *method; bool bus_hotplug_support = false; /* * Skip bridge subtree creation if bridge hotplug is disabled * to make acpi tables compatible with legacy machine types. * Skip creation for hotplugged bridges as well. */ if (bus->parent_dev && (!child->pcihp_bridge_en || DEVICE(bus->parent_dev)->hotplugged)) { build_free_array(bus_table); build_pci_bus_state_cleanup(child); g_free(child); return; } if (bus->parent_dev) { op = 0x82; /* DeviceOp */ build_append_namestring(bus_table, "S%.02X", bus->parent_dev->devfn); build_append_byte(bus_table, 0x08); /* NameOp */ build_append_namestring(bus_table, "_SUN"); build_append_int(bus_table, PCI_SLOT(bus->parent_dev->devfn)); build_append_byte(bus_table, 0x08); /* NameOp */ build_append_namestring(bus_table, "_ADR"); build_append_int(bus_table, (PCI_SLOT(bus->parent_dev->devfn) << 16) | PCI_FUNC(bus->parent_dev->devfn)); } else { op = 0x10; /* ScopeOp */; build_append_namestring(bus_table, "PCI0"); } bsel = object_property_get_qobject(OBJECT(bus), ACPI_PCIHP_PROP_BSEL, NULL); if (bsel) { build_append_byte(bus_table, 0x08); /* NameOp */ build_append_namestring(bus_table, "BSEL"); build_append_int(bus_table, qint_get_int(qobject_to_qint(bsel))); memset(slot_hotplug_enable, 0xff, sizeof slot_hotplug_enable); } else { /* No bsel - no slots are hot-pluggable */ memset(slot_hotplug_enable, 0x00, sizeof slot_hotplug_enable); } memset(slot_device_present, 0x00, sizeof slot_device_present); memset(slot_device_system, 0x00, sizeof slot_device_present); memset(slot_device_vga, 0x00, sizeof slot_device_vga); memset(slot_device_qxl, 0x00, sizeof slot_device_qxl); for (i = 0; i < ARRAY_SIZE(bus->devices); i += PCI_FUNC_MAX) { DeviceClass *dc; PCIDeviceClass *pc; PCIDevice *pdev = bus->devices[i]; int slot = PCI_SLOT(i); bool bridge_in_acpi; if (!pdev) { continue; } set_bit(slot, slot_device_present); pc = PCI_DEVICE_GET_CLASS(pdev); dc = DEVICE_GET_CLASS(pdev); /* When hotplug for bridges is enabled, bridges are * described in ACPI separately (see build_pci_bus_end). * In this case they aren't themselves hot-pluggable. * Hotplugged bridges *are* hot-pluggable. */ bridge_in_acpi = pc->is_bridge && child->pcihp_bridge_en && !DEVICE(pdev)->hotplugged; if (pc->class_id == PCI_CLASS_BRIDGE_ISA || bridge_in_acpi) { set_bit(slot, slot_device_system); } if (pc->class_id == PCI_CLASS_DISPLAY_VGA) { set_bit(slot, slot_device_vga); if (object_dynamic_cast(OBJECT(pdev), "qxl-vga")) { set_bit(slot, slot_device_qxl); } } if (!dc->hotpluggable || bridge_in_acpi) { clear_bit(slot, slot_hotplug_enable); } } /* Append Device object for each slot */ for (i = 0; i < PCI_SLOT_MAX; i++) { bool can_eject = test_bit(i, slot_hotplug_enable); bool present = test_bit(i, slot_device_present); bool vga = test_bit(i, slot_device_vga); bool qxl = test_bit(i, slot_device_qxl); bool system = test_bit(i, slot_device_system); if (can_eject) { void *pcihp = acpi_data_push(bus_table, ACPI_PCIHP_SIZEOF); memcpy(pcihp, ACPI_PCIHP_AML, ACPI_PCIHP_SIZEOF); patch_pcihp(i, pcihp); bus_hotplug_support = true; } else if (qxl) { void *pcihp = acpi_data_push(bus_table, ACPI_PCIQXL_SIZEOF); memcpy(pcihp, ACPI_PCIQXL_AML, ACPI_PCIQXL_SIZEOF); patch_pciqxl(i, pcihp); } else if (vga) { void *pcihp = acpi_data_push(bus_table, ACPI_PCIVGA_SIZEOF); memcpy(pcihp, ACPI_PCIVGA_AML, ACPI_PCIVGA_SIZEOF); patch_pcivga(i, pcihp); } else if (system) { /* Nothing to do: system devices are in DSDT or in SSDT above. */ } else if (present) { void *pcihp = acpi_data_push(bus_table, ACPI_PCINOHP_SIZEOF); memcpy(pcihp, ACPI_PCINOHP_AML, ACPI_PCINOHP_SIZEOF); patch_pcinohp(i, pcihp); } } if (bsel) { method = build_alloc_method("DVNT", 2); for (i = 0; i < PCI_SLOT_MAX; i++) { GArray *notify; uint8_t op; if (!test_bit(i, slot_hotplug_enable)) { continue; } notify = build_alloc_array(); op = 0xA0; /* IfOp */ build_append_byte(notify, 0x7B); /* AndOp */ build_append_byte(notify, 0x68); /* Arg0Op */ build_append_int(notify, 0x1U << i); build_append_byte(notify, 0x00); /* NullName */ build_append_byte(notify, 0x86); /* NotifyOp */ build_append_namestring(notify, "S%.02X", PCI_DEVFN(i, 0)); build_append_byte(notify, 0x69); /* Arg1Op */ /* Pack it up */ build_package(notify, op); build_append_array(method, notify); build_free_array(notify); } build_append_and_cleanup_method(bus_table, method); } /* Append PCNT method to notify about events on local and child buses. * Add unconditionally for root since DSDT expects it. */ if (bus_hotplug_support || child->notify_table->len || !bus->parent_dev) { method = build_alloc_method("PCNT", 0); /* If bus supports hotplug select it and notify about local events */ if (bsel) { build_append_byte(method, 0x70); /* StoreOp */ build_append_int(method, qint_get_int(qobject_to_qint(bsel))); build_append_namestring(method, "BNUM"); build_append_namestring(method, "DVNT"); build_append_namestring(method, "PCIU"); build_append_int(method, 1); /* Device Check */ build_append_namestring(method, "DVNT"); build_append_namestring(method, "PCID"); build_append_int(method, 3); /* Eject Request */ } /* Notify about child bus events in any case */ build_append_array(method, child->notify_table); build_append_and_cleanup_method(bus_table, method); /* Append description of child buses */ build_append_array(bus_table, child->device_table); /* Pack it up */ if (bus->parent_dev) { build_extop_package(bus_table, op); } else { build_package(bus_table, op); } /* Append our bus description to parent table */ build_append_array(parent->device_table, bus_table); /* Also tell parent how to notify us, invoking PCNT method. * At the moment this is not needed for root as we have a single root. */ if (bus->parent_dev) { build_append_namestring(parent->notify_table, "^PCNT.S%.02X", bus->parent_dev->devfn); } } qobject_decref(bsel); build_free_array(bus_table); build_pci_bus_state_cleanup(child); g_free(child); }


static bool check_overwrapping_aiocb(BDRVSheepdogState *s, SheepdogAIOCB *aiocb) { SheepdogAIOCB *cb; QLIST_FOREACH(cb, &s->inflight_aiocb_head, aiocb_siblings) { if (AIOCBOverwrapping(aiocb, cb)) { return true; } } QLIST_INSERT_HEAD(&s->inflight_aiocb_head, aiocb, aiocb_siblings); return false; }


void vp9_encode_frame ( VP9_COMP * cpi ) {
 VP9_COMMON * const cm = & cpi -> common ;
 RD_OPT * const rd_opt = & cpi -> rd ;
 if ( ! frame_is_intra_only ( cm ) ) {
 if ( ( cm -> ref_frame_sign_bias [ ALTREF_FRAME ] == cm -> ref_frame_sign_bias [ GOLDEN_FRAME ] ) || ( cm -> ref_frame_sign_bias [ ALTREF_FRAME ] == cm -> ref_frame_sign_bias [ LAST_FRAME ] ) ) {
 cm -> allow_comp_inter_inter = 0 ;
 }
 else {
 cm -> allow_comp_inter_inter = 1 ;
 cm -> comp_fixed_ref = ALTREF_FRAME ;
 cm -> comp_var_ref [ 0 ] = LAST_FRAME ;
 cm -> comp_var_ref [ 1 ] = GOLDEN_FRAME ;
 }
 }
 if ( cpi -> sf . frame_parameter_update ) {
 int i ;
 const MV_REFERENCE_FRAME frame_type = get_frame_type ( cpi ) ;
 int64_t * const mode_thrs = rd_opt -> prediction_type_threshes [ frame_type ] ;
 int64_t * const filter_thrs = rd_opt -> filter_threshes [ frame_type ] ;
 int * const tx_thrs = rd_opt -> tx_select_threshes [ frame_type ] ;
 const int is_alt_ref = frame_type == ALTREF_FRAME ;
 if ( is_alt_ref || ! cm -> allow_comp_inter_inter ) cm -> reference_mode = SINGLE_REFERENCE ;
 else if ( mode_thrs [ COMPOUND_REFERENCE ] > mode_thrs [ SINGLE_REFERENCE ] && mode_thrs [ COMPOUND_REFERENCE ] > mode_thrs [ REFERENCE_MODE_SELECT ] && check_dual_ref_flags ( cpi ) && cpi -> static_mb_pct == 100 ) cm -> reference_mode = COMPOUND_REFERENCE ;
 else if ( mode_thrs [ SINGLE_REFERENCE ] > mode_thrs [ REFERENCE_MODE_SELECT ] ) cm -> reference_mode = SINGLE_REFERENCE ;
 else cm -> reference_mode = REFERENCE_MODE_SELECT ;
 if ( cm -> interp_filter == SWITCHABLE ) cm -> interp_filter = get_interp_filter ( filter_thrs , is_alt_ref ) ;
 encode_frame_internal ( cpi ) ;
 for ( i = 0 ;
 i < REFERENCE_MODES ;
 ++ i ) mode_thrs [ i ] = ( mode_thrs [ i ] + rd_opt -> comp_pred_diff [ i ] / cm -> MBs ) / 2 ;
 for ( i = 0 ;
 i < SWITCHABLE_FILTER_CONTEXTS ;
 ++ i ) filter_thrs [ i ] = ( filter_thrs [ i ] + rd_opt -> filter_diff [ i ] / cm -> MBs ) / 2 ;
 for ( i = 0 ;
 i < TX_MODES ;
 ++ i ) {
 int64_t pd = rd_opt -> tx_select_diff [ i ] ;
 if ( i == TX_MODE_SELECT ) pd -= RDCOST ( cpi -> mb . rdmult , cpi -> mb . rddiv , 2048 * ( TX_SIZES - 1 ) , 0 ) ;
 tx_thrs [ i ] = ( tx_thrs [ i ] + ( int ) ( pd / cm -> MBs ) ) / 2 ;
 }
 if ( cm -> reference_mode == REFERENCE_MODE_SELECT ) {
 int single_count_zero = 0 ;
 int comp_count_zero = 0 ;
 for ( i = 0 ;
 i < COMP_INTER_CONTEXTS ;
 i ++ ) {
 single_count_zero += cm -> counts . comp_inter [ i ] [ 0 ] ;
 comp_count_zero += cm -> counts . comp_inter [ i ] [ 1 ] ;
 }
 if ( comp_count_zero == 0 ) {
 cm -> reference_mode = SINGLE_REFERENCE ;
 vp9_zero ( cm -> counts . comp_inter ) ;
 }
 else if ( single_count_zero == 0 ) {
 cm -> reference_mode = COMPOUND_REFERENCE ;
 vp9_zero ( cm -> counts . comp_inter ) ;
 }
 }
 if ( cm -> tx_mode == TX_MODE_SELECT ) {
 int count4x4 = 0 ;
 int count8x8_lp = 0 , count8x8_8x8p = 0 ;
 int count16x16_16x16p = 0 , count16x16_lp = 0 ;
 int count32x32 = 0 ;
 for ( i = 0 ;
 i < TX_SIZE_CONTEXTS ;
 ++ i ) {
 count4x4 += cm -> counts . tx . p32x32 [ i ] [ TX_4X4 ] ;
 count4x4 += cm -> counts . tx . p16x16 [ i ] [ TX_4X4 ] ;
 count4x4 += cm -> counts . tx . p8x8 [ i ] [ TX_4X4 ] ;
 count8x8_lp += cm -> counts . tx . p32x32 [ i ] [ TX_8X8 ] ;
 count8x8_lp += cm -> counts . tx . p16x16 [ i ] [ TX_8X8 ] ;
 count8x8_8x8p += cm -> counts . tx . p8x8 [ i ] [ TX_8X8 ] ;
 count16x16_16x16p += cm -> counts . tx . p16x16 [ i ] [ TX_16X16 ] ;
 count16x16_lp += cm -> counts . tx . p32x32 [ i ] [ TX_16X16 ] ;
 count32x32 += cm -> counts . tx . p32x32 [ i ] [ TX_32X32 ] ;
 }
 if ( count4x4 == 0 && count16x16_lp == 0 && count16x16_16x16p == 0 && count32x32 == 0 ) {
 cm -> tx_mode = ALLOW_8X8 ;
 reset_skip_tx_size ( cm , TX_8X8 ) ;
 }
 else if ( count8x8_8x8p == 0 && count16x16_16x16p == 0 && count8x8_lp == 0 && count16x16_lp == 0 && count32x32 == 0 ) {
 cm -> tx_mode = ONLY_4X4 ;
 reset_skip_tx_size ( cm , TX_4X4 ) ;
 }
 else if ( count8x8_lp == 0 && count16x16_lp == 0 && count4x4 == 0 ) {
 cm -> tx_mode = ALLOW_32X32 ;
 }
 else if ( count32x32 == 0 && count8x8_lp == 0 && count4x4 == 0 ) {
 cm -> tx_mode = ALLOW_16X16 ;
 reset_skip_tx_size ( cm , TX_16X16 ) ;
 }
 }
 }
 else {
 cm -> reference_mode = SINGLE_REFERENCE ;
 encode_frame_internal ( cpi ) ;
 }
 }


static block_t * PacketizeStreamBlock ( decoder_t * p_dec , block_t * * pp_block ) {
 decoder_sys_t * p_sys = p_dec -> p_sys ;
 uint8_t p_header [ ADTS_HEADER_SIZE + LOAS_HEADER_SIZE ] ;
 block_t * p_out_buffer ;
 uint8_t * p_buf ;
 if ( ! pp_block || ! * pp_block ) return NULL ;
 if ( ( * pp_block ) -> i_flags & ( BLOCK_FLAG_DISCONTINUITY | BLOCK_FLAG_CORRUPTED ) ) {
 if ( ( * pp_block ) -> i_flags & BLOCK_FLAG_CORRUPTED ) {
 p_sys -> i_state = STATE_NOSYNC ;
 block_BytestreamEmpty ( & p_sys -> bytestream ) ;
 }
 date_Set ( & p_sys -> end_date , 0 ) ;
 block_Release ( * pp_block ) ;
 return NULL ;
 }
 if ( ! date_Get ( & p_sys -> end_date ) && ( * pp_block ) -> i_pts <= VLC_TS_INVALID ) {
 block_Release ( * pp_block ) ;
 return NULL ;
 }
 block_BytestreamPush ( & p_sys -> bytestream , * pp_block ) ;
 for ( ;
 ;
 ) {
 switch ( p_sys -> i_state ) {
 case STATE_NOSYNC : while ( block_PeekBytes ( & p_sys -> bytestream , p_header , 2 ) == VLC_SUCCESS ) {
 if ( p_header [ 0 ] == 0xff && ( p_header [ 1 ] & 0xf6 ) == 0xf0 ) {
 if ( p_sys -> i_type != TYPE_ADTS ) msg_Dbg ( p_dec , "detected ADTS format" ) ;
 p_sys -> i_state = STATE_SYNC ;
 p_sys -> i_type = TYPE_ADTS ;
 break ;
 }
 else if ( p_header [ 0 ] == 0x56 && ( p_header [ 1 ] & 0xe0 ) == 0xe0 ) {
 if ( p_sys -> i_type != TYPE_LOAS ) msg_Dbg ( p_dec , "detected LOAS format" ) ;
 p_sys -> i_state = STATE_SYNC ;
 p_sys -> i_type = TYPE_LOAS ;
 break ;
 }
 block_SkipByte ( & p_sys -> bytestream ) ;
 }
 if ( p_sys -> i_state != STATE_SYNC ) {
 block_BytestreamFlush ( & p_sys -> bytestream ) ;
 return NULL ;
 }
 case STATE_SYNC : p_sys -> i_pts = p_sys -> bytestream . p_block -> i_pts ;
 if ( p_sys -> i_pts > VLC_TS_INVALID && p_sys -> i_pts != date_Get ( & p_sys -> end_date ) ) date_Set ( & p_sys -> end_date , p_sys -> i_pts ) ;
 p_sys -> i_state = STATE_HEADER ;
 break ;
 case STATE_HEADER : if ( p_sys -> i_type == TYPE_ADTS ) {
 if ( block_PeekBytes ( & p_sys -> bytestream , p_header , ADTS_HEADER_SIZE ) != VLC_SUCCESS ) return NULL ;
 p_sys -> i_frame_size = ADTSSyncInfo ( p_dec , p_header , & p_sys -> i_channels , & p_sys -> i_rate , & p_sys -> i_frame_length , & p_sys -> i_header_size ) ;
 }
 else {
 assert ( p_sys -> i_type == TYPE_LOAS ) ;
 if ( block_PeekBytes ( & p_sys -> bytestream , p_header , LOAS_HEADER_SIZE ) != VLC_SUCCESS ) return NULL ;
 p_sys -> i_frame_size = LOASSyncInfo ( p_header , & p_sys -> i_header_size ) ;
 }
 if ( p_sys -> i_frame_size <= 0 ) {
 msg_Dbg ( p_dec , "emulated sync word" ) ;
 block_SkipByte ( & p_sys -> bytestream ) ;
 p_sys -> i_state = STATE_NOSYNC ;
 break ;
 }
 p_sys -> i_state = STATE_NEXT_SYNC ;
 case STATE_NEXT_SYNC : if ( p_sys -> bytestream . p_block == NULL ) {
 p_sys -> i_state = STATE_NOSYNC ;
 block_BytestreamFlush ( & p_sys -> bytestream ) ;
 return NULL ;
 }
 if ( block_PeekOffsetBytes ( & p_sys -> bytestream , p_sys -> i_frame_size + p_sys -> i_header_size , p_header , 2 ) != VLC_SUCCESS ) return NULL ;
 assert ( ( p_sys -> i_type == TYPE_ADTS ) || ( p_sys -> i_type == TYPE_LOAS ) ) ;
 if ( ( ( p_sys -> i_type == TYPE_ADTS ) && ( p_header [ 0 ] != 0xff || ( p_header [ 1 ] & 0xf6 ) != 0xf0 ) ) || ( ( p_sys -> i_type == TYPE_LOAS ) && ( p_header [ 0 ] != 0x56 || ( p_header [ 1 ] & 0xe0 ) != 0xe0 ) ) ) {
 msg_Dbg ( p_dec , "emulated sync word " "(no sync on following frame)" ) ;
 p_sys -> i_state = STATE_NOSYNC ;
 block_SkipByte ( & p_sys -> bytestream ) ;
 break ;
 }
 p_sys -> i_state = STATE_SEND_DATA ;
 break ;
 case STATE_GET_DATA : if ( block_WaitBytes ( & p_sys -> bytestream , p_sys -> i_frame_size + p_sys -> i_header_size ) != VLC_SUCCESS ) return NULL ;
 p_sys -> i_state = STATE_SEND_DATA ;
 case STATE_SEND_DATA : p_out_buffer = block_Alloc ( p_sys -> i_frame_size ) ;
 if ( ! p_out_buffer ) {
 return NULL ;
 }
 p_buf = p_out_buffer -> p_buffer ;
 block_SkipBytes ( & p_sys -> bytestream , p_sys -> i_header_size ) ;
 if ( p_sys -> i_type == TYPE_ADTS ) {
 block_GetBytes ( & p_sys -> bytestream , p_buf , p_sys -> i_frame_size ) ;
 }
 else {
 assert ( p_sys -> i_type == TYPE_LOAS ) ;
 block_GetBytes ( & p_sys -> bytestream , p_buf , p_sys -> i_frame_size ) ;
 p_out_buffer -> i_buffer = LOASParse ( p_dec , p_buf , p_sys -> i_frame_size ) ;
 if ( p_out_buffer -> i_buffer <= 0 ) {
 if ( ! p_sys -> b_latm_cfg ) msg_Warn ( p_dec , "waiting for header" ) ;
 block_Release ( p_out_buffer ) ;
 p_out_buffer = NULL ;
 p_sys -> i_state = STATE_NOSYNC ;
 break ;
 }
 }
 SetupOutput ( p_dec , p_out_buffer ) ;
 if ( p_sys -> i_pts == p_sys -> bytestream . p_block -> i_pts ) p_sys -> i_pts = p_sys -> bytestream . p_block -> i_pts = VLC_TS_INVALID ;
 * pp_block = block_BytestreamPop ( & p_sys -> bytestream ) ;
 p_sys -> i_state = STATE_NOSYNC ;
 return p_out_buffer ;
 }
 }
 return NULL ;
 }


static void cleanup_unknown_header_ext ( BlockDriverState * bs ) {
 BDRVQcowState * s = bs -> opaque ;
 Qcow2UnknownHeaderExtension * uext , * next ;
 QLIST_FOREACH_SAFE ( uext , & s -> unknown_header_ext , next , next ) {
 QLIST_REMOVE ( uext , next ) ;
 g_free ( uext ) ;
 }
 }


static int best_effort_strncat_from_utf16le ( struct archive_string * as , const void * _p , size_t bytes , struct archive_string_conv * sc ) {
 return ( best_effort_strncat_from_utf16 ( as , _p , bytes , sc , 0 ) ) ;
 }


static inline float point_inside_circle ( float px , float py , float x , float y , float r ) {
 float dx = px - x ;
 float dy = py - y ;
 return dx * dx + dy * dy <= r * r ;
 }


static int get_physical_address_data(CPUState *env, target_phys_addr_t *physical, int *prot, target_ulong address, int rw, int is_user) { unsigned int i; uint64_t context; int is_nucleus; if ((env->lsu & DMMU_E) == 0) { /* DMMU disabled */ *physical = ultrasparc_truncate_physical(address); *prot = PAGE_READ | PAGE_WRITE; return 0; } context = env->dmmu.mmu_primary_context & 0x1fff; is_nucleus = env->tl > 0; for (i = 0; i < 64; i++) { // ctx match, vaddr match, valid? if (ultrasparc_tag_match(&env->dtlb[i], address, context, physical, is_nucleus)) { // access ok? if (((env->dtlb[i].tte & 0x4) && is_user) || (!(env->dtlb[i].tte & 0x2) && (rw == 1))) { uint8_t fault_type = 0; if ((env->dtlb[i].tte & 0x4) && is_user) { fault_type |= 1; /* privilege violation */ } if (env->dmmu.sfsr & 1) /* Fault status register */ env->dmmu.sfsr = 2; /* overflow (not read before another fault) */ env->dmmu.sfsr |= (is_user << 3) | ((rw == 1) << 2) | 1; env->dmmu.sfsr |= (fault_type << 7); env->dmmu.sfar = address; /* Fault address register */ env->exception_index = TT_DFAULT; #ifdef DEBUG_MMU printf("DFAULT at 0x%" PRIx64 "\n", address); #endif return 1; } *prot = PAGE_READ; if (env->dtlb[i].tte & 0x2) *prot |= PAGE_WRITE; TTE_SET_USED(env->dtlb[i].tte); return 0; } } #ifdef DEBUG_MMU printf("DMISS at 0x%" PRIx64 "\n", address); #endif env->dmmu.tag_access = (address & ~0x1fffULL) | context; env->exception_index = TT_DMISS; return 1; }


static int dissect_h245_MaintenanceLoopReject ( 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_h245_MaintenanceLoopReject , MaintenanceLoopReject_sequence ) ;
 return offset ;
 }


hb_font_funcs_t * hb_font_funcs_get_empty ( void ) {
 return const_cast < hb_font_funcs_t * > ( & _hb_font_funcs_nil ) ;
 }


static void glyph_info_destroy ( hb_glyph_info_t * g ) {
 free ( g ) ;
 }


void vp9_convolve_copy_c ( const uint8_t * src , ptrdiff_t src_stride , uint8_t * dst , ptrdiff_t dst_stride , const int16_t * filter_x , int filter_x_stride , const int16_t * filter_y , int filter_y_stride , int w , int h ) {
 int r ;
 ( void ) filter_x ;
 ( void ) filter_x_stride ;
 ( void ) filter_y ;
 ( void ) filter_y_stride ;
 for ( r = h ;
 r > 0 ;
 -- r ) {
 vpx_memcpy ( dst , src , w ) ;
 src += src_stride ;
 dst += dst_stride ;
 }
 }


static int dissect_h225_H248SignalsDescriptor ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_octet_string ( tvb , offset , actx , tree , hf_index , NO_BOUND , NO_BOUND , FALSE , NULL ) ;
 return offset ;
 }


static void vmsErrorHandler ( const char * module , const char * fmt , va_list ap ) {
 if ( module != NULL ) fprintf ( stderr , "%s: " , module ) ;
 vfprintf ( stderr , fmt , ap ) ;
 fprintf ( stderr , ".\n" ) ;
 }


static void config_monitor ( config_tree * ptree ) {
 int_node * pfilegen_token ;
 const char * filegen_string ;
 const char * filegen_file ;
 FILEGEN * filegen ;
 filegen_node * my_node ;
 attr_val * my_opts ;
 int filegen_type ;
 int filegen_flag ;
 if ( ptree -> stats_dir ) stats_config ( STATS_STATSDIR , ptree -> stats_dir ) ;
 pfilegen_token = HEAD_PFIFO ( ptree -> stats_list ) ;
 for ( ;
 pfilegen_token != NULL ;
 pfilegen_token = pfilegen_token -> link ) {
 filegen_string = keyword ( pfilegen_token -> i ) ;
 filegen = filegen_get ( filegen_string ) ;
 if ( NULL == filegen ) {
 msyslog ( LOG_ERR , "stats %s unrecognized" , filegen_string ) ;
 continue ;
 }
 DPRINTF ( 4 , ( "enabling filegen for %s statistics '%s%s'\n" , filegen_string , filegen -> prefix , filegen -> basename ) ) ;
 filegen -> flag |= FGEN_FLAG_ENABLED ;
 }
 my_node = HEAD_PFIFO ( ptree -> filegen_opts ) ;
 for ( ;
 my_node != NULL ;
 my_node = my_node -> link ) {
 filegen_file = keyword ( my_node -> filegen_token ) ;
 filegen = filegen_get ( filegen_file ) ;
 if ( NULL == filegen ) {
 msyslog ( LOG_ERR , "filegen category '%s' unrecognized" , filegen_file ) ;
 continue ;
 }
 filegen_flag = filegen -> flag ;
 filegen_type = filegen -> type ;
 filegen_flag |= FGEN_FLAG_ENABLED ;
 my_opts = HEAD_PFIFO ( my_node -> options ) ;
 for ( ;
 my_opts != NULL ;
 my_opts = my_opts -> link ) {
 switch ( my_opts -> attr ) {
 case T_File : filegen_file = my_opts -> value . s ;
 break ;
 case T_Type : switch ( my_opts -> value . i ) {
 default : NTP_INSIST ( 0 ) ;
 break ;
 case T_None : filegen_type = FILEGEN_NONE ;
 break ;
 case T_Pid : filegen_type = FILEGEN_PID ;
 break ;
 case T_Day : filegen_type = FILEGEN_DAY ;
 break ;
 case T_Week : filegen_type = FILEGEN_WEEK ;
 break ;
 case T_Month : filegen_type = FILEGEN_MONTH ;
 break ;
 case T_Year : filegen_type = FILEGEN_YEAR ;
 break ;
 case T_Age : filegen_type = FILEGEN_AGE ;
 break ;
 }
 break ;
 case T_Flag : switch ( my_opts -> value . i ) {
 case T_Link : filegen_flag |= FGEN_FLAG_LINK ;
 break ;
 case T_Nolink : filegen_flag &= ~ FGEN_FLAG_LINK ;
 break ;
 case T_Enable : filegen_flag |= FGEN_FLAG_ENABLED ;
 break ;
 case T_Disable : filegen_flag &= ~ FGEN_FLAG_ENABLED ;
 break ;
 default : msyslog ( LOG_ERR , "Unknown filegen flag token %d" , my_opts -> value . i ) ;
 exit ( 1 ) ;
 }
 break ;
 default : msyslog ( LOG_ERR , "Unknown filegen option token %d" , my_opts -> attr ) ;
 exit ( 1 ) ;
 }
 }
 filegen_config ( filegen , filegen_file , filegen_type , filegen_flag ) ;
 }
 }


afs_int32 SPR_SetFieldsEntry ( struct rx_call * call , afs_int32 id , afs_int32 mask , afs_int32 flags , afs_int32 ngroups , afs_int32 nusers , afs_int32 spare1 , afs_int32 spare2 ) {
 afs_int32 code ;
 afs_int32 cid = ANONYMOUSID ;
 code = setFieldsEntry ( call , id , mask , flags , ngroups , nusers , spare1 , spare2 , & cid ) ;
 osi_auditU ( call , PTS_SetFldEntEvent , code , AUD_ID , id , AUD_END ) ;
 ViceLog ( 5 , ( "PTS_SetFieldsEntry: code %d cid %d id %d\n" , code , cid , id ) ) ;
 return code ;
 }


void pxa27x_register_keypad(struct pxa2xx_keypad_s *kp, struct keymap *map, int size) { kp->map = (struct keymap *) qemu_mallocz(sizeof(struct keymap) * size); if(!map || size < 0x80) { fprintf(stderr, "%s - No PXA keypad map defined\n", __FUNCTION__); exit(-1); } kp->map = map; qemu_add_kbd_event_handler((QEMUPutKBDEvent *) pxa27x_keyboard_event, kp); }


static void generate_noise ( G723_1_Context * p ) {
 int i , j , idx , t ;
 int off [ SUBFRAMES ] ;
 int signs [ SUBFRAMES / 2 * 11 ] , pos [ SUBFRAMES / 2 * 11 ] ;
 int tmp [ SUBFRAME_LEN * 2 ] ;
 int16_t * vector_ptr ;
 int64_t sum ;
 int b0 , c , delta , x , shift ;
 p -> pitch_lag [ 0 ] = cng_rand ( & p -> cng_random_seed , 21 ) + 123 ;
 p -> pitch_lag [ 1 ] = cng_rand ( & p -> cng_random_seed , 19 ) + 123 ;
 for ( i = 0 ;
 i < SUBFRAMES ;
 i ++ ) {
 p -> subframe [ i ] . ad_cb_gain = cng_rand ( & p -> cng_random_seed , 50 ) + 1 ;
 p -> subframe [ i ] . ad_cb_lag = cng_adaptive_cb_lag [ i ] ;
 }
 for ( i = 0 ;
 i < SUBFRAMES / 2 ;
 i ++ ) {
 t = cng_rand ( & p -> cng_random_seed , 1 << 13 ) ;
 off [ i * 2 ] = t & 1 ;
 off [ i * 2 + 1 ] = ( ( t >> 1 ) & 1 ) + SUBFRAME_LEN ;
 t >>= 2 ;
 for ( j = 0 ;
 j < 11 ;
 j ++ ) {
 signs [ i * 11 + j ] = ( t & 1 ) * 2 - 1 << 14 ;
 t >>= 1 ;
 }
 }
 idx = 0 ;
 for ( i = 0 ;
 i < SUBFRAMES ;
 i ++ ) {
 for ( j = 0 ;
 j < SUBFRAME_LEN / 2 ;
 j ++ ) tmp [ j ] = j ;
 t = SUBFRAME_LEN / 2 ;
 for ( j = 0 ;
 j < pulses [ i ] ;
 j ++ , idx ++ ) {
 int idx2 = cng_rand ( & p -> cng_random_seed , t ) ;
 pos [ idx ] = tmp [ idx2 ] * 2 + off [ i ] ;
 tmp [ idx2 ] = tmp [ -- t ] ;
 }
 }
 vector_ptr = p -> audio + LPC_ORDER ;
 memcpy ( vector_ptr , p -> prev_excitation , PITCH_MAX * sizeof ( * p -> excitation ) ) ;
 for ( i = 0 ;
 i < SUBFRAMES ;
 i += 2 ) {
 gen_acb_excitation ( vector_ptr , vector_ptr , p -> pitch_lag [ i >> 1 ] , & p -> subframe [ i ] , p -> cur_rate ) ;
 gen_acb_excitation ( vector_ptr + SUBFRAME_LEN , vector_ptr + SUBFRAME_LEN , p -> pitch_lag [ i >> 1 ] , & p -> subframe [ i + 1 ] , p -> cur_rate ) ;
 t = 0 ;
 for ( j = 0 ;
 j < SUBFRAME_LEN * 2 ;
 j ++ ) t |= FFABS ( vector_ptr [ j ] ) ;
 t = FFMIN ( t , 0x7FFF ) ;
 if ( ! t ) {
 shift = 0 ;
 }
 else {
 shift = - 10 + av_log2 ( t ) ;
 if ( shift < - 2 ) shift = - 2 ;
 }
 sum = 0 ;
 if ( shift < 0 ) {
 for ( j = 0 ;
 j < SUBFRAME_LEN * 2 ;
 j ++ ) {
 t = vector_ptr [ j ] << - shift ;
 sum += t * t ;
 tmp [ j ] = t ;
 }
 }
 else {
 for ( j = 0 ;
 j < SUBFRAME_LEN * 2 ;
 j ++ ) {
 t = vector_ptr [ j ] >> shift ;
 sum += t * t ;
 tmp [ j ] = t ;
 }
 }
 b0 = 0 ;
 for ( j = 0 ;
 j < 11 ;
 j ++ ) b0 += tmp [ pos [ ( i / 2 ) * 11 + j ] ] * signs [ ( i / 2 ) * 11 + j ] ;
 b0 = b0 * 2 * 2979LL + ( 1 << 29 ) >> 30 ;
 c = p -> cur_gain * ( p -> cur_gain * SUBFRAME_LEN >> 5 ) ;
 if ( shift * 2 + 3 >= 0 ) c >>= shift * 2 + 3 ;
 else c <<= - ( shift * 2 + 3 ) ;
 c = ( av_clipl_int32 ( sum << 1 ) - c ) * 2979LL >> 15 ;
 delta = b0 * b0 * 2 - c ;
 if ( delta <= 0 ) {
 x = - b0 ;
 }
 else {
 delta = square_root ( delta ) ;
 x = delta - b0 ;
 t = delta + b0 ;
 if ( FFABS ( t ) < FFABS ( x ) ) x = - t ;
 }
 shift ++ ;
 if ( shift < 0 ) x >>= - shift ;
 else x <<= shift ;
 x = av_clip ( x , - 10000 , 10000 ) ;
 for ( j = 0 ;
 j < 11 ;
 j ++ ) {
 idx = ( i / 2 ) * 11 + j ;
 vector_ptr [ pos [ idx ] ] = av_clip_int16 ( vector_ptr [ pos [ idx ] ] + ( x * signs [ idx ] >> 15 ) ) ;
 }
 memcpy ( vector_ptr + PITCH_MAX , vector_ptr , sizeof ( * vector_ptr ) * SUBFRAME_LEN * 2 ) ;
 vector_ptr += SUBFRAME_LEN * 2 ;
 }
 memcpy ( p -> prev_excitation , p -> audio + LPC_ORDER + FRAME_LEN , PITCH_MAX * sizeof ( * p -> excitation ) ) ;
 }


static void _del_alloc_pack_msg ( void * x ) {
 resource_allocation_response_msg_t * alloc_msg ;
 alloc_msg = ( resource_allocation_response_msg_t * ) x ;
 alloc_msg -> working_cluster_rec = NULL ;
 slurm_free_resource_allocation_response_msg_members ( alloc_msg ) ;
 xfree ( alloc_msg ) ;
 }


juniper_parse_header(netdissect_options *ndo,
                     const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info)
{
    const struct juniper_cookie_table_t *lp = juniper_cookie_table;
    u_int idx, jnx_ext_len, jnx_header_len = 0;
    uint8_t tlv_type,tlv_len;
    uint32_t control_word;
    int tlv_value;
    const u_char *tptr;

    l2info->header_len = 0;
    l2info->cookie_len = 0;
    l2info->proto = 0;

    l2info->length = h->len;
    l2info->caplen = h->caplen;
    ND_TCHECK2(p[0], 4);
    l2info->flags = p[3];
    l2info->direction = p[3]&JUNIPER_BPF_PKT_IN;

    if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */
        ND_PRINT((ndo, "no magic-number found!"));
        return 0;
    }

    if (ndo->ndo_eflag) /* print direction */
        ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction)));

    /* magic number + flags */
    jnx_header_len = 4;

    if (ndo->ndo_vflag > 1)
        ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]",
               bittok2str(jnx_flag_values, "none", l2info->flags)));

    /* extensions present ?  - calculate how much bytes to skip */
    if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) {

        tptr = p+jnx_header_len;

        /* ok to read extension length ? */
        ND_TCHECK2(tptr[0], 2);
        jnx_ext_len = EXTRACT_16BITS(tptr);
        jnx_header_len += 2;
        tptr +=2;

        /* nail up the total length -
         * just in case something goes wrong
         * with TLV parsing */
        jnx_header_len += jnx_ext_len;

        if (ndo->ndo_vflag > 1)
            ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len));

        ND_TCHECK2(tptr[0], jnx_ext_len);
        while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) {
            tlv_type = *(tptr++);
            tlv_len = *(tptr++);
            tlv_value = 0;

            /* sanity checks */
            if (tlv_type == 0 || tlv_len == 0)
                break;
            if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len)
                goto trunc;

            if (ndo->ndo_vflag > 1)
                ND_PRINT((ndo, "\n\t  %s Extension TLV #%u, length %u, value ",
                       tok2str(jnx_ext_tlv_values,"Unknown",tlv_type),
                       tlv_type,
                       tlv_len));

            tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len);
            switch (tlv_type) {
            case JUNIPER_EXT_TLV_IFD_NAME:
                /* FIXME */
                break;
            case JUNIPER_EXT_TLV_IFD_MEDIATYPE:
            case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE:
                if (tlv_value != -1) {
                    if (ndo->ndo_vflag > 1)
                        ND_PRINT((ndo, "%s (%u)",
                               tok2str(juniper_ifmt_values, "Unknown", tlv_value),
                               tlv_value));
                }
                break;
            case JUNIPER_EXT_TLV_IFL_ENCAPS:
            case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS:
                if (tlv_value != -1) {
                    if (ndo->ndo_vflag > 1)
                        ND_PRINT((ndo, "%s (%u)",
                               tok2str(juniper_ifle_values, "Unknown", tlv_value),
                               tlv_value));
                }
                break;
            case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */
            case JUNIPER_EXT_TLV_IFL_UNIT:
            case JUNIPER_EXT_TLV_IFD_IDX:
            default:
                if (tlv_value != -1) {
                    if (ndo->ndo_vflag > 1)
                        ND_PRINT((ndo, "%u", tlv_value));
                }
                break;
            }

            tptr+=tlv_len;
            jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD;
        }

        if (ndo->ndo_vflag > 1)
            ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
    }

    if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) {
        if (ndo->ndo_eflag)
            ND_PRINT((ndo, "no-L2-hdr, "));

        /* there is no link-layer present -
         * perform the v4/v6 heuristics
         * to figure out what it is
         */
        ND_TCHECK2(p[jnx_header_len + 4], 1);
        if (ip_heuristic_guess(ndo, p + jnx_header_len + 4,
                               l2info->length - (jnx_header_len + 4)) == 0)
            ND_PRINT((ndo, "no IP-hdr found!"));

        l2info->header_len=jnx_header_len+4;
        return 0; /* stop parsing the output further */

    }
    l2info->header_len = jnx_header_len;
    p+=l2info->header_len;
    l2info->length -= l2info->header_len;
    l2info->caplen -= l2info->header_len;

    /* search through the cookie table and copy values matching for our PIC type */
    while (lp->s != NULL) {
        if (lp->pictype == l2info->pictype) {

            l2info->cookie_len += lp->cookie_len;

            switch (p[0]) {
            case LS_COOKIE_ID:
                l2info->cookie_type = LS_COOKIE_ID;
                l2info->cookie_len += 2;
                break;
            case AS_COOKIE_ID:
                l2info->cookie_type = AS_COOKIE_ID;
                l2info->cookie_len = 8;
                break;

            default:
                l2info->bundle = l2info->cookie[0];
                break;
            }

#ifdef DLT_JUNIPER_MFR
            /* MFR child links don't carry cookies */
            if (l2info->pictype == DLT_JUNIPER_MFR &&
                (p[0] & MFR_BE_MASK) == MFR_BE_MASK) {
                l2info->cookie_len = 0;
            }
#endif

            l2info->header_len += l2info->cookie_len;
            l2info->length -= l2info->cookie_len;
            l2info->caplen -= l2info->cookie_len;

            if (ndo->ndo_eflag)
                ND_PRINT((ndo, "%s-PIC, cookie-len %u",
                       lp->s,
                       l2info->cookie_len));

            if (l2info->cookie_len > 0) {
                ND_TCHECK2(p[0], l2info->cookie_len);
                if (ndo->ndo_eflag)
                    ND_PRINT((ndo, ", cookie 0x"));
                for (idx = 0; idx < l2info->cookie_len; idx++) {
                    l2info->cookie[idx] = p[idx]; /* copy cookie data */
                    if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx]));
                }
            }

            if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/

            l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len);
            break;
        }
        ++lp;
    }
    p+=l2info->cookie_len;

    /* DLT_ specific parsing */
    switch(l2info->pictype) {
#ifdef DLT_JUNIPER_MLPPP
    case DLT_JUNIPER_MLPPP:
        switch (l2info->cookie_type) {
        case LS_COOKIE_ID:
            l2info->bundle = l2info->cookie[1];
            break;
        case AS_COOKIE_ID:
            l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
            l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
            break;
        default:
            l2info->bundle = l2info->cookie[0];
            break;
        }
        break;
#endif
#ifdef DLT_JUNIPER_MLFR
    case DLT_JUNIPER_MLFR:
        switch (l2info->cookie_type) {
        case LS_COOKIE_ID:
            l2info->bundle = l2info->cookie[1];
            l2info->proto = EXTRACT_16BITS(p);
            l2info->header_len += 2;
            l2info->length -= 2;
            l2info->caplen -= 2;
            break;
        case AS_COOKIE_ID:
            l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
            l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
            break;
        default:
            l2info->bundle = l2info->cookie[0];
            l2info->header_len += 2;
            l2info->length -= 2;
            l2info->caplen -= 2;
            break;
        }
        break;
#endif
#ifdef DLT_JUNIPER_MFR
    case DLT_JUNIPER_MFR:
        switch (l2info->cookie_type) {
        case LS_COOKIE_ID:
            l2info->bundle = l2info->cookie[1];
            l2info->proto = EXTRACT_16BITS(p);
            l2info->header_len += 2;
            l2info->length -= 2;
            l2info->caplen -= 2;
            break;
        case AS_COOKIE_ID:
            l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
            l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
            break;
        default:
            l2info->bundle = l2info->cookie[0];
            break;
        }
        break;
#endif
#ifdef DLT_JUNIPER_ATM2
    case DLT_JUNIPER_ATM2:
        ND_TCHECK2(p[0], 4);
        /* ATM cell relay control word present ? */
        if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) {
            control_word = EXTRACT_32BITS(p);
            /* some control word heuristics */
            switch(control_word) {
            case 0: /* zero control word */
            case 0x08000000: /* < JUNOS 7.4 control-word */
            case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/
                l2info->header_len += 4;
                break;
            default:
                break;
            }

            if (ndo->ndo_eflag)
                ND_PRINT((ndo, "control-word 0x%08x ", control_word));
        }
        break;
#endif
#ifdef DLT_JUNIPER_GGSN
    case DLT_JUNIPER_GGSN:
        break;
#endif
#ifdef DLT_JUNIPER_ATM1
    case DLT_JUNIPER_ATM1:
        break;
#endif
#ifdef DLT_JUNIPER_PPP
    case DLT_JUNIPER_PPP:
        break;
#endif
#ifdef DLT_JUNIPER_CHDLC
    case DLT_JUNIPER_CHDLC:
        break;
#endif
#ifdef DLT_JUNIPER_ETHER
    case DLT_JUNIPER_ETHER:
        break;
#endif
#ifdef DLT_JUNIPER_FRELAY
    case DLT_JUNIPER_FRELAY:
        break;
#endif

    default:
        ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype));
        break;
    }

    if (ndo->ndo_eflag > 1)
        ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto));

    return 1; /* everything went ok so far. continue parsing */
 trunc:
    ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len));
    return 0;
}


extern "C" void *malloc_wrapper(size_t size, void *caller)
{
    void *ptr = NULL;
#if MBED_MEM_TRACING_ENABLED
    mbed_mem_trace_lock();
#endif
#if MBED_HEAP_STATS_ENABLED
    malloc_stats_mutex->lock();
    alloc_info_t *alloc_info = (alloc_info_t *)SUPER_MALLOC(size + sizeof(alloc_info_t));
    if (alloc_info != NULL) {
        alloc_info->size = size;
        alloc_info->signature = MBED_HEAP_STATS_SIGNATURE;
        ptr = (void *)(alloc_info + 1);
        heap_stats.current_size += size;
        heap_stats.total_size += size;
        heap_stats.alloc_cnt += 1;
        if (heap_stats.current_size > heap_stats.max_size) {
            heap_stats.max_size = heap_stats.current_size;
        }
        heap_stats.overhead_size += get_malloc_block_total_size((void *)alloc_info) - size;
    } else {
        heap_stats.alloc_fail_cnt += 1;
    }
    malloc_stats_mutex->unlock();
#else // #if MBED_HEAP_STATS_ENABLED
    ptr = SUPER_MALLOC(size);
#endif // #if MBED_HEAP_STATS_ENABLED
#if MBED_MEM_TRACING_ENABLED
    mbed_mem_trace_malloc(ptr, size, caller);
    mbed_mem_trace_unlock();
#endif // #if MBED_MEM_TRACING_ENABLED
    return ptr;
}


void bdrv_io_unplugged_begin(BlockDriverState *bs) { BdrvChild *child; if (bs->io_plug_disabled++ == 0 && bs->io_plugged > 0) { BlockDriver *drv = bs->drv; if (drv && drv->bdrv_io_unplug) { drv->bdrv_io_unplug(bs); } } QLIST_FOREACH(child, &bs->children, next) { bdrv_io_unplugged_begin(child->bs); } }


static int count_contiguous_clusters_unallocated(int nb_clusters, uint64_t *l2_table, QCow2ClusterType wanted_type) { int i; assert(wanted_type == QCOW2_CLUSTER_ZERO || wanted_type == QCOW2_CLUSTER_UNALLOCATED); for (i = 0; i < nb_clusters; i++) { uint64_t entry = be64_to_cpu(l2_table[i]); QCow2ClusterType type = qcow2_get_cluster_type(entry); if (type != wanted_type || entry & L2E_OFFSET_MASK) { break; } } return i; }


static int isoent_traverse_tree ( struct archive_write * a , struct vdd * vdd ) {
 struct iso9660 * iso9660 = a -> format_data ;
 struct isoent * np ;
 struct idr idr ;
 int depth ;
 int r ;
 int ( * genid ) ( struct archive_write * , struct isoent * , struct idr * ) ;
 idr_init ( iso9660 , vdd , & idr ) ;
 np = vdd -> rootent ;
 depth = 0 ;
 if ( vdd -> vdd_type == VDD_JOLIET ) genid = isoent_gen_joliet_identifier ;
 else genid = isoent_gen_iso9660_identifier ;
 do {
 if ( np -> virtual && ! archive_entry_mtime_is_set ( np -> file -> entry ) ) {
 archive_entry_set_mtime ( np -> file -> entry , iso9660 -> birth_time , 0 ) ;
 archive_entry_set_atime ( np -> file -> entry , iso9660 -> birth_time , 0 ) ;
 archive_entry_set_ctime ( np -> file -> entry , iso9660 -> birth_time , 0 ) ;
 }
 if ( np -> children . first != NULL ) {
 if ( vdd -> vdd_type != VDD_JOLIET && ! iso9660 -> opt . rr && depth + 1 >= vdd -> max_depth ) {
 if ( np -> children . cnt > 0 ) iso9660 -> directories_too_deep = np ;
 }
 else {
 r = genid ( a , np , & idr ) ;
 if ( r < 0 ) goto exit_traverse_tree ;
 r = isoent_make_sorted_files ( a , np , & idr ) ;
 if ( r < 0 ) goto exit_traverse_tree ;
 if ( np -> subdirs . first != NULL && depth + 1 < vdd -> max_depth ) {
 np = np -> subdirs . first ;
 depth ++ ;
 continue ;
 }
 }
 }
 while ( np != np -> parent ) {
 if ( np -> drnext == NULL ) {
 np = np -> parent ;
 depth -- ;
 }
 else {
 np = np -> drnext ;
 break ;
 }
 }
 }
 while ( np != np -> parent ) ;
 r = ARCHIVE_OK ;
 exit_traverse_tree : idr_cleanup ( & idr ) ;
 return ( r ) ;
 }


  void Compute(OpKernelContext* context) override {
    const Tensor& input = context->input(0);
    const TensorShape& input_shape = input.shape();
    const int32_t input_dims = input_shape.dims();

    const Tensor& segment_id = context->input(1);
    const TensorShape& segment_id_shape = segment_id.shape();
    const int32_t segment_dims = segment_id_shape.dims();

    const Tensor& num_segments_tensor = context->input(2);
    OP_REQUIRES(context, num_segments_tensor.NumElements() != 0,
                errors::InvalidArgument("Number of segments cannot be empty."));
    auto num_segments = num_segments_tensor.scalar<NUM_SEGMENTS_TYPE>()();

    OP_REQUIRES(context, segment_dims != 0,
                errors::InvalidArgument("Segment_id cannot have rank 0"));

    OP_REQUIRES(
        context, segment_dims <= input_dims,
        errors::OutOfRange("Invalid segment_id rank ", segment_dims,
                           " for input with ", input_dims, " dimension(s)"));
    for (auto i = 0; i < segment_dims; i++) {
      OP_REQUIRES(
          context, segment_id_shape.dim_size(i) == input_shape.dim_size(i),
          errors::InvalidArgument(
              "Segment dimension is ", segment_id_shape.dim_size(i),
              " while input dimension is ", input_dims, " in rank ", i));
    }

    // Making output tensor.
    Tensor* output_tensor = nullptr;
    TensorShape output_shape =
        GetOutputShape(input_shape, segment_id_shape, num_segments);
    OP_REQUIRES_OK(context, context->allocate_output("output", output_shape,
                                                     &output_tensor));

    // Preparating flat tensors.
    auto output_flat = output_tensor->flat<tstring>();
    auto flat_segment_id = segment_id.flat<INDICES_TYPE>();
    auto flat_input = input.flat<tstring>();

    for (int i = 0; i < flat_segment_id.size(); i++) {
      OP_REQUIRES(
          context,
          ((flat_segment_id(i) < num_segments) && (flat_segment_id(i) >= 0)),
          errors::InvalidArgument(
              "segment_ids are not allowed to exceed num_segments or"
              " to have negative values."));
    }

    int64_t big_stride;
    int64_t small_stride;
    std::tie(big_stride, small_stride) =
        GetStrides<INDICES_TYPE>(input_shape, segment_id_shape);
    auto relative_offset_set =
        GetFlattenedRelativeOffsets<INDICES_TYPE>(small_stride, big_stride);
    for (auto start_offset = 0; start_offset < big_stride; start_offset++) {
      for (auto i = 0; i < relative_offset_set.size(); i++) {
        auto output_index = start_offset + flat_segment_id(i) * big_stride;
        auto offset = start_offset + relative_offset_set[i];
        if (output_flat(output_index).length() != 0)
          output_flat(output_index).append(separator_.c_str());
        output_flat(output_index).append(flat_input(offset));
      }
    }
  }


int qemu_show_nic_models(const char *arg, const char *const *models) { int i; if (!arg || strcmp(arg, "?")) return 0; fprintf(stderr, "qemu: Supported NIC models: "); for (i = 0 ; models[i]; i++) fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n'); return 1; }


TSReturnCode TSHttpTxnCloseAfterResponse ( TSHttpTxn txnp , int should_close ) {
 if ( sdk_sanity_check_txn ( txnp ) != TS_SUCCESS ) {
 return TS_ERROR ;
 }
 HttpSM * sm = ( HttpSM * ) txnp ;
 if ( should_close ) {
 sm -> t_state . client_info . keep_alive = HTTP_NO_KEEPALIVE ;
 if ( sm -> ua_session ) {
 sm -> set_ua_half_close_flag ( ) ;
 }
 }
 else if ( sm -> t_state . client_info . keep_alive == HTTP_NO_KEEPALIVE ) {
 sm -> t_state . client_info . keep_alive = HTTP_KEEPALIVE ;
 }
 return TS_SUCCESS ;
 }


void HTTPSession::onCertificate(uint16_t certId,
                                std::unique_ptr<IOBuf> authenticator) {
  DestructorGuard dg(this);
  VLOG(4) << "CERTIFICATE on" << *this << ", certId=" << certId;

  bool isValid = false;
  auto fizzBase = getTransport()->getUnderlyingTransport<AsyncFizzBase>();
  if (fizzBase) {
    if (isUpstream()) {
      isValid = secondAuthManager_->validateAuthenticator(
          *fizzBase,
          TransportDirection::UPSTREAM,
          certId,
          std::move(authenticator));
    } else {
      isValid = secondAuthManager_->validateAuthenticator(
          *fizzBase,
          TransportDirection::DOWNSTREAM,
          certId,
          std::move(authenticator));
    }
  } else {
    VLOG(4) << "Underlying transport does not support secondary "
               "authentication.";
    return;
  }
  if (isValid) {
    VLOG(4) << "Successfully validated the authenticator provided by the peer.";
  } else {
    VLOG(4) << "Failed to validate the authenticator provided by the peer";
  }
}


static int bdrv_can_snapshot(BlockDriverState *bs) { return (bs && !bdrv_is_removable(bs) && !bdrv_is_read_only(bs)); }


static void tgq_idct_put_mb_dconly ( TgqContext * s , int mb_x , int mb_y , const int8_t * dc ) {
 int linesize = s -> frame . linesize [ 0 ] ;
 uint8_t * dest_y = s -> frame . data [ 0 ] + ( mb_y * 16 * linesize ) + mb_x * 16 ;
 uint8_t * dest_cb = s -> frame . data [ 1 ] + ( mb_y * 8 * s -> frame . linesize [ 1 ] ) + mb_x * 8 ;
 uint8_t * dest_cr = s -> frame . data [ 2 ] + ( mb_y * 8 * s -> frame . linesize [ 2 ] ) + mb_x * 8 ;
 tgq_dconly ( s , dest_y , linesize , dc [ 0 ] ) ;
 tgq_dconly ( s , dest_y + 8 , linesize , dc [ 1 ] ) ;
 tgq_dconly ( s , dest_y + 8 * linesize , linesize , dc [ 2 ] ) ;
 tgq_dconly ( s , dest_y + 8 * linesize + 8 , linesize , dc [ 3 ] ) ;
 if ( ! ( s -> avctx -> flags & CODEC_FLAG_GRAY ) ) {
 tgq_dconly ( s , dest_cb , s -> frame . linesize [ 1 ] , dc [ 4 ] ) ;
 tgq_dconly ( s , dest_cr , s -> frame . linesize [ 2 ] , dc [ 5 ] ) ;
 }
 }


CreateStatistics(CreateStatsStmt *stmt)
{
	int16		attnums[STATS_MAX_DIMENSIONS];
	int			numcols = 0;
	char	   *namestr;
	NameData	stxname;
	Oid			statoid;
	Oid			namespaceId;
	Oid			stxowner = GetUserId();
	HeapTuple	htup;
	Datum		values[Natts_pg_statistic_ext];
	bool		nulls[Natts_pg_statistic_ext];
	Datum		datavalues[Natts_pg_statistic_ext_data];
	bool		datanulls[Natts_pg_statistic_ext_data];
	int2vector *stxkeys;
	Relation	statrel;
	Relation	datarel;
	Relation	rel = NULL;
	Oid			relid;
	ObjectAddress parentobject,
				myself;
	Datum		types[3];		/* one for each possible type of statistic */
	int			ntypes;
	ArrayType  *stxkind;
	bool		build_ndistinct;
	bool		build_dependencies;
	bool		build_mcv;
	bool		requested_type = false;
	int			i;
	ListCell   *cell;

	Assert(IsA(stmt, CreateStatsStmt));

	/*
	 * Examine the FROM clause.  Currently, we only allow it to be a single
	 * simple table, but later we'll probably allow multiple tables and JOIN
	 * syntax.  The grammar is already prepared for that, so we have to check
	 * here that what we got is what we can support.
	 */
	if (list_length(stmt->relations) != 1)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("only a single relation is allowed in CREATE STATISTICS")));

	foreach(cell, stmt->relations)
	{
		Node	   *rln = (Node *) lfirst(cell);

		if (!IsA(rln, RangeVar))
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("only a single relation is allowed in CREATE STATISTICS")));

		/*
		 * CREATE STATISTICS will influence future execution plans but does
		 * not interfere with currently executing plans.  So it should be
		 * enough to take only ShareUpdateExclusiveLock on relation,
		 * conflicting with ANALYZE and other DDL that sets statistical
		 * information, but not with normal queries.
		 */
		rel = relation_openrv((RangeVar *) rln, ShareUpdateExclusiveLock);

		/* Restrict to allowed relation types */
		if (rel->rd_rel->relkind != RELKIND_RELATION &&
			rel->rd_rel->relkind != RELKIND_MATVIEW &&
			rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
			rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("relation \"%s\" is not a table, foreign table, or materialized view",
							RelationGetRelationName(rel))));

		/* You must own the relation to create stats on it */
		if (!pg_class_ownercheck(RelationGetRelid(rel), stxowner))
			aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
						   RelationGetRelationName(rel));

		/* Creating statistics on system catalogs is not allowed */
		if (!allowSystemTableMods && IsSystemRelation(rel))
			ereport(ERROR,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
					 errmsg("permission denied: \"%s\" is a system catalog",
							RelationGetRelationName(rel))));
	}

	Assert(rel);
	relid = RelationGetRelid(rel);

	/*
	 * If the node has a name, split it up and determine creation namespace.
	 * If not (a possibility not considered by the grammar, but one which can
	 * occur via the "CREATE TABLE ... (LIKE)" command), then we put the
	 * object in the same namespace as the relation, and cons up a name for
	 * it.
	 */
	if (stmt->defnames)
		namespaceId = QualifiedNameGetCreationNamespace(stmt->defnames,
														&namestr);
	else
	{
		namespaceId = RelationGetNamespace(rel);
		namestr = ChooseExtendedStatisticName(RelationGetRelationName(rel),
											  ChooseExtendedStatisticNameAddition(stmt->exprs),
											  "stat",
											  namespaceId);
	}
	namestrcpy(&stxname, namestr);

	/*
	 * Deal with the possibility that the statistics object already exists.
	 */
	if (SearchSysCacheExists2(STATEXTNAMENSP,
							  CStringGetDatum(namestr),
							  ObjectIdGetDatum(namespaceId)))
	{
		if (stmt->if_not_exists)
		{
			ereport(NOTICE,
					(errcode(ERRCODE_DUPLICATE_OBJECT),
					 errmsg("statistics object \"%s\" already exists, skipping",
							namestr)));
			relation_close(rel, NoLock);
			return InvalidObjectAddress;
		}

		ereport(ERROR,
				(errcode(ERRCODE_DUPLICATE_OBJECT),
				 errmsg("statistics object \"%s\" already exists", namestr)));
	}

	/*
	 * Currently, we only allow simple column references in the expression
	 * list.  That will change someday, and again the grammar already supports
	 * it so we have to enforce restrictions here.  For now, we can convert
	 * the expression list to a simple array of attnums.  While at it, enforce
	 * some constraints.
	 */
	foreach(cell, stmt->exprs)
	{
		Node	   *expr = (Node *) lfirst(cell);
		ColumnRef  *cref;
		char	   *attname;
		HeapTuple	atttuple;
		Form_pg_attribute attForm;
		TypeCacheEntry *type;

		if (!IsA(expr, ColumnRef))
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("only simple column references are allowed in CREATE STATISTICS")));
		cref = (ColumnRef *) expr;

		if (list_length(cref->fields) != 1)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("only simple column references are allowed in CREATE STATISTICS")));
		attname = strVal((Value *) linitial(cref->fields));

		atttuple = SearchSysCacheAttName(relid, attname);
		if (!HeapTupleIsValid(atttuple))
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
					 errmsg("column \"%s\" does not exist",
							attname)));
		attForm = (Form_pg_attribute) GETSTRUCT(atttuple);

		/* Disallow use of system attributes in extended stats */
		if (attForm->attnum <= 0)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("statistics creation on system columns is not supported")));

		/* Disallow data types without a less-than operator */
		type = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);
		if (type->lt_opr == InvalidOid)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class",
							attname, format_type_be(attForm->atttypid))));

		/* Make sure no more than STATS_MAX_DIMENSIONS columns are used */
		if (numcols >= STATS_MAX_DIMENSIONS)
			ereport(ERROR,
					(errcode(ERRCODE_TOO_MANY_COLUMNS),
					 errmsg("cannot have more than %d columns in statistics",
							STATS_MAX_DIMENSIONS)));

		attnums[numcols] = attForm->attnum;
		numcols++;
		ReleaseSysCache(atttuple);
	}

	/*
	 * Check that at least two columns were specified in the statement. The
	 * upper bound was already checked in the loop above.
	 */
	if (numcols < 2)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
				 errmsg("extended statistics require at least 2 columns")));

	/*
	 * Sort the attnums, which makes detecting duplicates somewhat easier, and
	 * it does not hurt (it does not affect the efficiency, unlike for
	 * indexes, for example).
	 */
	qsort(attnums, numcols, sizeof(int16), compare_int16);

	/*
	 * Check for duplicates in the list of columns. The attnums are sorted so
	 * just check consecutive elements.
	 */
	for (i = 1; i < numcols; i++)
	{
		if (attnums[i] == attnums[i - 1])
			ereport(ERROR,
					(errcode(ERRCODE_DUPLICATE_COLUMN),
					 errmsg("duplicate column name in statistics definition")));
	}

	/* Form an int2vector representation of the sorted column list */
	stxkeys = buildint2vector(attnums, numcols);

	/*
	 * Parse the statistics kinds.
	 */
	build_ndistinct = false;
	build_dependencies = false;
	build_mcv = false;
	foreach(cell, stmt->stat_types)
	{
		char	   *type = strVal((Value *) lfirst(cell));

		if (strcmp(type, "ndistinct") == 0)
		{
			build_ndistinct = true;
			requested_type = true;
		}
		else if (strcmp(type, "dependencies") == 0)
		{
			build_dependencies = true;
			requested_type = true;
		}
		else if (strcmp(type, "mcv") == 0)
		{
			build_mcv = true;
			requested_type = true;
		}
		else
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 errmsg("unrecognized statistics kind \"%s\"",
							type)));
	}
	/* If no statistic type was specified, build them all. */
	if (!requested_type)
	{
		build_ndistinct = true;
		build_dependencies = true;
		build_mcv = true;
	}

	/* construct the char array of enabled statistic types */
	ntypes = 0;
	if (build_ndistinct)
		types[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT);
	if (build_dependencies)
		types[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES);
	if (build_mcv)
		types[ntypes++] = CharGetDatum(STATS_EXT_MCV);
	Assert(ntypes > 0 && ntypes <= lengthof(types));
	stxkind = construct_array(types, ntypes, CHAROID, 1, true, 'c');

	statrel = table_open(StatisticExtRelationId, RowExclusiveLock);

	/*
	 * Everything seems fine, so let's build the pg_statistic_ext tuple.
	 */
	memset(values, 0, sizeof(values));
	memset(nulls, false, sizeof(nulls));

	statoid = GetNewOidWithIndex(statrel, StatisticExtOidIndexId,
								 Anum_pg_statistic_ext_oid);
	values[Anum_pg_statistic_ext_oid - 1] = ObjectIdGetDatum(statoid);
	values[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid);
	values[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname);
	values[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);
	values[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);
	values[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);
	values[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);

	/* insert it into pg_statistic_ext */
	htup = heap_form_tuple(statrel->rd_att, values, nulls);
	CatalogTupleInsert(statrel, htup);
	heap_freetuple(htup);

	relation_close(statrel, RowExclusiveLock);

	/*
	 * Also build the pg_statistic_ext_data tuple, to hold the actual
	 * statistics data.
	 */
	datarel = table_open(StatisticExtDataRelationId, RowExclusiveLock);

	memset(datavalues, 0, sizeof(datavalues));
	memset(datanulls, false, sizeof(datanulls));

	datavalues[Anum_pg_statistic_ext_data_stxoid - 1] = ObjectIdGetDatum(statoid);

	/* no statistics built yet */
	datanulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = true;
	datanulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = true;
	datanulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = true;

	/* insert it into pg_statistic_ext_data */
	htup = heap_form_tuple(datarel->rd_att, datavalues, datanulls);
	CatalogTupleInsert(datarel, htup);
	heap_freetuple(htup);

	relation_close(datarel, RowExclusiveLock);

	/*
	 * Invalidate relcache so that others see the new statistics object.
	 */
	CacheInvalidateRelcache(rel);

	relation_close(rel, NoLock);

	/*
	 * Add an AUTO dependency on each column used in the stats, so that the
	 * stats object goes away if any or all of them get dropped.
	 */
	ObjectAddressSet(myself, StatisticExtRelationId, statoid);

	for (i = 0; i < numcols; i++)
	{
		ObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);
		recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);
	}

	/*
	 * Also add dependencies on namespace and owner.  These are required
	 * because the stats object might have a different namespace and/or owner
	 * than the underlying table(s).
	 */
	ObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);
	recordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);

	recordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner);

	/*
	 * XXX probably there should be a recordDependencyOnCurrentExtension call
	 * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP
	 * STATISTICS, which is more work than it seems worth.
	 */

	/* Add any requested comment */
	if (stmt->stxcomment != NULL)
		CreateComments(statoid, StatisticExtRelationId, 0,
					   stmt->stxcomment);

	/* Return stats object's address */
	return myself;
}


static void float_number(void) { int i; struct { const char *encoded; double decoded; int skip; } test_cases[] = { { "32.43", 32.43 }, { "0.222", 0.222 }, { "-32.12313", -32.12313 }, { "-32.20e-10", -32.20e-10, .skip = 1 }, { }, }; for (i = 0; test_cases[i].encoded; i++) { QObject *obj; QFloat *qfloat; obj = qobject_from_json(test_cases[i].encoded, NULL); qfloat = qobject_to_qfloat(obj); g_assert(qfloat); g_assert(qfloat_get_double(qfloat) == test_cases[i].decoded); if (test_cases[i].skip == 0) { QString *str; str = qobject_to_json(obj); g_assert(strcmp(qstring_get_str(str), test_cases[i].encoded) == 0); QDECREF(str); } QDECREF(qfloat); } }


Oid get_rel_tablespace ( Oid relid ) {
 HeapTuple tp ;
 tp = SearchSysCache1 ( RELOID , ObjectIdGetDatum ( relid ) ) ;
 if ( HeapTupleIsValid ( tp ) ) {
 Form_pg_class reltup = ( Form_pg_class ) GETSTRUCT ( tp ) ;
 Oid result ;
 result = reltup -> reltablespace ;
 ReleaseSysCache ( tp ) ;
 return result ;
 }
 else return InvalidOid ;
 }


enum message_read_status evhttp_parse_firstline ( struct evhttp_request * req , struct evbuffer * buffer ) {
 char * line ;
 enum message_read_status status = ALL_DATA_READ ;
 line = evbuffer_readline ( buffer ) ;
 if ( line == NULL ) return ( MORE_DATA_EXPECTED ) ;
 switch ( req -> kind ) {
 case EVHTTP_REQUEST : if ( evhttp_parse_request_line ( req , line ) == - 1 ) status = DATA_CORRUPTED ;
 break ;
 case EVHTTP_RESPONSE : if ( evhttp_parse_response_line ( req , line ) == - 1 ) status = DATA_CORRUPTED ;
 break ;
 default : status = DATA_CORRUPTED ;
 }
 free ( line ) ;
 return ( status ) ;
 }


static int bmdma_prepare_buf(IDEDMA *dma, int is_write) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); IDEState *s = bmdma_active_if(bm); PCIDevice *pci_dev = PCI_DEVICE(bm->pci_dev); struct { uint32_t addr; uint32_t size; } prd; int l, len; pci_dma_sglist_init(&s->sg, pci_dev, s->nsector / (BMDMA_PAGE_SIZE / 512) + 1); s->io_buffer_size = 0; for(;;) { if (bm->cur_prd_len == 0) { /* end of table (with a fail safe of one page) */ if (bm->cur_prd_last || (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE) return s->io_buffer_size != 0; pci_dma_read(pci_dev, bm->cur_addr, &prd, 8); bm->cur_addr += 8; prd.addr = le32_to_cpu(prd.addr); prd.size = le32_to_cpu(prd.size); len = prd.size & 0xfffe; if (len == 0) len = 0x10000; bm->cur_prd_len = len; bm->cur_prd_addr = prd.addr; bm->cur_prd_last = (prd.size & 0x80000000); } l = bm->cur_prd_len; if (l > 0) { qemu_sglist_add(&s->sg, bm->cur_prd_addr, l); bm->cur_prd_addr += l; bm->cur_prd_len -= l; s->io_buffer_size += l; } } return 1; }


static void version ( ) {
 printf ( "icucal version %s (ICU version %s), created by Stephen F. Booth.\n" , CAL_VERSION , U_ICU_VERSION ) ;
 puts ( U_COPYRIGHT_STRING ) ;
 }


void ntpq_custom_opt_handler ( tOptions * pOptions , tOptDesc * pOptDesc ) {
 switch ( pOptDesc -> optValue ) {
 default : fprintf ( stderr , "ntpq_custom_opt_handler unexpected option '%c' (%d)\n" , pOptDesc -> optValue , pOptDesc -> optValue ) ;
 exit ( 1 ) ;
 case 'c' : ADDCMD ( pOptDesc -> pzLastArg ) ;
 break ;
 case 'p' : ADDCMD ( "peers" ) ;
 break ;
 }
 }


static int queue_picture(VideoState *is, AVFrame *src_frame, double pts1, int64_t pos) { VideoPicture *vp; double frame_delay, pts = pts1; /* compute the exact PTS for the picture if it is omitted in the stream * pts1 is the dts of the pkt / pts of the frame */ if (pts != 0) { /* update video clock with pts, if present */ is->video_clock = pts; } else { pts = is->video_clock; /* update video clock for next frame */ frame_delay = av_q2d(is->video_st->codec->time_base); /* for MPEG2, the frame can be repeated, so we update the clock accordingly */ frame_delay += src_frame->repeat_pict * (frame_delay * 0.5); is->video_clock += frame_delay; #if defined(DEBUG_SYNC) && 0 printf("frame_type=%c clock=%0.3f pts=%0.3f\n", av_get_picture_type_char(src_frame->pict_type), pts, pts1); #endif /* wait until we have space to put a new picture */ SDL_LockMutex(is->pictq_mutex); if(is->pictq_size>=VIDEO_PICTURE_QUEUE_SIZE && !is->refresh) is->skip_frames= FFMAX(1.0 - FRAME_SKIP_FACTOR, is->skip_frames * (1.0-FRAME_SKIP_FACTOR)); while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE && !is->videoq.abort_request) { SDL_UnlockMutex(is->pictq_mutex); if (is->videoq.abort_request) return -1; vp = &is->pictq[is->pictq_windex]; vp->duration = frame_delay; /* alloc or resize hardware picture buffer */ if (!vp->bmp || #if CONFIG_AVFILTER vp->width != is->out_video_filter->inputs[0]->w || vp->height != is->out_video_filter->inputs[0]->h) { #else vp->width != is->video_st->codec->width || vp->height != is->video_st->codec->height) { #endif SDL_Event event; vp->allocated = 0; /* the allocation must be done in the main thread to avoid locking problems */ event.type = FF_ALLOC_EVENT; event.user.data1 = is; SDL_PushEvent(&event); /* wait until the picture is allocated */ SDL_LockMutex(is->pictq_mutex); while (!vp->allocated && !is->videoq.abort_request) { SDL_UnlockMutex(is->pictq_mutex); if (is->videoq.abort_request) return -1; /* if the frame is not skipped, then display it */ if (vp->bmp) { AVPicture pict; #if CONFIG_AVFILTER if(vp->picref) avfilter_unref_buffer(vp->picref); vp->picref = src_frame->opaque; #endif /* get a pointer on the bitmap */ SDL_LockYUVOverlay (vp->bmp); memset(&pict,0,sizeof(AVPicture)); pict.data[0] = vp->bmp->pixels[0]; pict.data[1] = vp->bmp->pixels[2]; pict.data[2] = vp->bmp->pixels[1]; pict.linesize[0] = vp->bmp->pitches[0]; pict.linesize[1] = vp->bmp->pitches[2]; pict.linesize[2] = vp->bmp->pitches[1]; #if CONFIG_AVFILTER //FIXME use direct rendering av_picture_copy(&pict, (AVPicture *)src_frame, vp->pix_fmt, vp->width, vp->height); #else sws_flags = av_get_int(sws_opts, "sws_flags", NULL); is->img_convert_ctx = sws_getCachedContext(is->img_convert_ctx, vp->width, vp->height, vp->pix_fmt, vp->width, vp->height, PIX_FMT_YUV420P, sws_flags, NULL, NULL, NULL); if (is->img_convert_ctx == NULL) { fprintf(stderr, "Cannot initialize the conversion context\n"); exit(1); sws_scale(is->img_convert_ctx, src_frame->data, src_frame->linesize, 0, vp->height, pict.data, pict.linesize); #endif /* update the bitmap content */ SDL_UnlockYUVOverlay(vp->bmp); vp->pts = pts; vp->pos = pos; /* now we can update the picture count */ if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE) is->pictq_windex = 0; SDL_LockMutex(is->pictq_mutex); vp->target_clock= compute_target_time(vp->pts, is); is->pictq_size++; SDL_UnlockMutex(is->pictq_mutex); return 0;


Publisher* ParticipantImpl::createPublisher(
        const PublisherAttributes& att,
        PublisherListener* listen)
{
    logInfo(PARTICIPANT, "CREATING PUBLISHER IN TOPIC: " << att.topic.getTopicName());
    //Look for the correct type registration

    TopicDataType* p_type = nullptr;

    /// Preconditions
    // Check the type was registered.
    if (!getRegisteredType(att.topic.getTopicDataType().c_str(), &p_type))
    {
        logError(PARTICIPANT, "Type : " << att.topic.getTopicDataType() << " Not Registered");
        return nullptr;
    }
    // Check the type supports keys.
    if (att.topic.topicKind == WITH_KEY && !p_type->m_isGetKeyDefined)
    {
        logError(PARTICIPANT, "Keyed Topic needs getKey function");
        return nullptr;
    }

    if (m_att.rtps.builtin.discovery_config.use_STATIC_EndpointDiscoveryProtocol)
    {
        if (att.getUserDefinedID() <= 0)
        {
            logError(PARTICIPANT, "Static EDP requires user defined Id");
            return nullptr;
        }
    }
    if (!att.unicastLocatorList.isValid())
    {
        logError(PARTICIPANT, "Unicast Locator List for Publisher contains invalid Locator");
        return nullptr;
    }
    if (!att.multicastLocatorList.isValid())
    {
        logError(PARTICIPANT, " Multicast Locator List for Publisher contains invalid Locator");
        return nullptr;
    }
    if (!att.remoteLocatorList.isValid())
    {
        logError(PARTICIPANT, "Remote Locator List for Publisher contains invalid Locator");
        return nullptr;
    }
    if (!att.qos.checkQos() || !att.topic.checkQos())
    {
        return nullptr;
    }

    //TODO CONSTRUIR LA IMPLEMENTACION DENTRO DEL OBJETO DEL USUARIO.
    PublisherImpl* pubimpl = new PublisherImpl(this, p_type, att, listen);
    Publisher* pub = new Publisher(pubimpl);
    pubimpl->mp_userPublisher = pub;
    pubimpl->mp_rtpsParticipant = this->mp_rtpsParticipant;

    WriterAttributes watt;
    watt.throughputController = att.throughputController;
    watt.endpoint.durabilityKind = att.qos.m_durability.durabilityKind();
    watt.endpoint.endpointKind = WRITER;
    watt.endpoint.multicastLocatorList = att.multicastLocatorList;
    watt.endpoint.reliabilityKind = att.qos.m_reliability.kind == RELIABLE_RELIABILITY_QOS ? RELIABLE : BEST_EFFORT;
    watt.endpoint.topicKind = att.topic.topicKind;
    watt.endpoint.unicastLocatorList = att.unicastLocatorList;
    watt.endpoint.remoteLocatorList = att.remoteLocatorList;
    watt.mode = att.qos.m_publishMode.kind ==
            eprosima::fastrtps::SYNCHRONOUS_PUBLISH_MODE ? SYNCHRONOUS_WRITER : ASYNCHRONOUS_WRITER;
    watt.endpoint.properties = att.properties;
    if (att.getEntityID() > 0)
    {
        watt.endpoint.setEntityID((uint8_t)att.getEntityID());
    }
    if (att.getUserDefinedID() > 0)
    {
        watt.endpoint.setUserDefinedID((uint8_t)att.getUserDefinedID());
    }
    watt.times = att.times;
    watt.liveliness_kind = att.qos.m_liveliness.kind;
    watt.liveliness_lease_duration = att.qos.m_liveliness.lease_duration;
    watt.liveliness_announcement_period = att.qos.m_liveliness.announcement_period;
    watt.matched_readers_allocation = att.matched_subscriber_allocation;

    // TODO(Ricardo) Remove in future
    // Insert topic_name and partitions
    Property property;
    property.name("topic_name");
    property.value(att.topic.getTopicName().c_str());
    watt.endpoint.properties.properties().push_back(std::move(property));
    if (att.qos.m_partition.names().size() > 0)
    {
        property.name("partitions");
        std::string partitions;
        for (auto partition : att.qos.m_partition.names())
        {
            partitions += partition + ";";
        }
        property.value(std::move(partitions));
        watt.endpoint.properties.properties().push_back(std::move(property));
    }
    if (att.qos.m_disablePositiveACKs.enabled &&
            att.qos.m_disablePositiveACKs.duration != c_TimeInfinite)
    {
        watt.disable_positive_acks = true;
        watt.keep_duration = att.qos.m_disablePositiveACKs.duration;
    }

    RTPSWriter* writer = RTPSDomain::createRTPSWriter(
        this->mp_rtpsParticipant,
        watt,
        (WriterHistory*)&pubimpl->m_history,
        (WriterListener*)&pubimpl->m_writerListener);
    if (writer == nullptr)
    {
        logError(PARTICIPANT, "Problem creating associated Writer");
        delete(pubimpl);
        return nullptr;
    }
    pubimpl->mp_writer = writer;

    // In case it has been loaded from the persistence DB, rebuild instances on history
    pubimpl->m_history.rebuild_instances();

    //SAVE THE PUBLISHER PAIR
    t_p_PublisherPair pubpair;
    pubpair.first = pub;
    pubpair.second = pubimpl;
    m_publishers.push_back(pubpair);

    //REGISTER THE WRITER
    this->mp_rtpsParticipant->registerWriter(writer, att.topic, att.qos);

    return pub;
}


static bool is_topic_in_criterias(
        const char* topic_name,
        const std::vector<Criteria>& criterias)
{
    bool returned_value = false;

    for (auto criteria_it = criterias.begin(); !returned_value &&
            criteria_it != criterias.end(); ++criteria_it)
    {
        for (auto topic : (*criteria_it).topics)
        {
            if (StringMatching::matchString(topic.c_str(), topic_name))
            {
                returned_value = true;
                break;
            }
        }
    }

    return returned_value;
}


static void vvalue_strbuf_append_null ( wmem_strbuf_t * strbuf _U_ , void * ptr _U_ ) {
 }


static int get_bits(Jpeg2000DecoderContext *s, int n) { int res = 0; if (s->buf_end - s->buf < ((n - s->bit_index) >> 8)) return AVERROR(EINVAL); while (--n >= 0) { res <<= 1; if (s->bit_index == 0) { s->bit_index = 7 + (*s->buf != 0xff); s->buf++; } s->bit_index--; res |= (*s->buf >> s->bit_index) & 1; } return res; }


static vpx_codec_err_t encoder_destroy ( vpx_codec_alg_priv_t * ctx ) {
 free ( ctx -> cx_data ) ;
 vp9_remove_compressor ( ctx -> cpi ) ;
 vpx_free ( ctx ) ;
 return VPX_CODEC_OK ;
 }


uint64_t HELPER(neon_sub_saturate_s64)(uint64_t src1, uint64_t src2) { uint64_t res; res = src1 - src2; if (((res ^ src1) & SIGNBIT64) && ((src1 ^ src2) & SIGNBIT64)) { env->QF = 1; res = ((int64_t)src1 >> 63) ^ ~SIGNBIT64; } return res; }


static int net_socket_connect_init(VLANState *vlan, const char *model, const char *name, const char *host_str) { NetSocketState *s; int fd, connected, ret, err; struct sockaddr_in saddr; if (parse_host_port(&saddr, host_str) < 0) return -1; fd = socket(PF_INET, SOCK_STREAM, 0); if (fd < 0) { perror("socket"); return -1; } socket_set_nonblock(fd); connected = 0; for(;;) { ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr)); if (ret < 0) { err = socket_error(); if (err == EINTR || err == EWOULDBLOCK) { } else if (err == EINPROGRESS) { break; #ifdef _WIN32 } else if (err == WSAEALREADY) { break; #endif } else { perror("connect"); closesocket(fd); return -1; } } else { connected = 1; break; } } s = net_socket_fd_init(vlan, model, name, fd, connected); if (!s) return -1; snprintf(s->nc.info_str, sizeof(s->nc.info_str), "socket: connect to %s:%d", inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port)); return 0; }


static int kvm_update_routing_entry(KVMState *s, struct kvm_irq_routing_entry *new_entry) { struct kvm_irq_routing_entry *entry; int n; for (n = 0; n < s->irq_routes->nr; n++) { entry = &s->irq_routes->entries[n]; if (entry->gsi != new_entry->gsi) { continue; } entry->type = new_entry->type; entry->flags = new_entry->flags; entry->u = new_entry->u; kvm_irqchip_commit_routes(s); return 0; } return -ESRCH; }


TEST_F ( TransportSecurityPersisterTest , PublicKeyHashes ) {
 TransportSecurityState : : DomainState domain_state ;
 static const char kTestDomain [ ] = "example.com" ;
 EXPECT_FALSE ( state_ . GetDynamicDomainState ( kTestDomain , & domain_state ) ) ;
 net : : HashValueVector hashes ;
 std : : string failure_log ;
 EXPECT_FALSE ( domain_state . CheckPublicKeyPins ( hashes , & failure_log ) ) ;
 net : : HashValue sha1 ( net : : HASH_VALUE_SHA1 ) ;
 memset ( sha1 . data ( ) , '1' , sha1 . size ( ) ) ;
 domain_state . pkp . spki_hashes . push_back ( sha1 ) ;
 EXPECT_FALSE ( domain_state . CheckPublicKeyPins ( hashes , & failure_log ) ) ;
 hashes . push_back ( sha1 ) ;
 EXPECT_TRUE ( domain_state . CheckPublicKeyPins ( hashes , & failure_log ) ) ;
 hashes [ 0 ] . data ( ) [ 0 ] = '2' ;
 EXPECT_FALSE ( domain_state . CheckPublicKeyPins ( hashes , & failure_log ) ) ;
 const base : : Time current_time ( base : : Time : : Now ( ) ) ;
 const base : : Time expiry = current_time + base : : TimeDelta : : FromSeconds ( 1000 ) ;
 bool include_subdomains = false ;
 state_ . AddHSTS ( kTestDomain , expiry , include_subdomains ) ;
 state_ . AddHPKP ( kTestDomain , expiry , include_subdomains , domain_state . pkp . spki_hashes ) ;
 std : : string serialized ;
 EXPECT_TRUE ( persister_ -> SerializeData ( & serialized ) ) ;
 bool dirty ;
 EXPECT_TRUE ( persister_ -> LoadEntries ( serialized , & dirty ) ) ;
 TransportSecurityState : : DomainState new_domain_state ;
 EXPECT_TRUE ( state_ . GetDynamicDomainState ( kTestDomain , & new_domain_state ) ) ;
 EXPECT_EQ ( 1u , new_domain_state . pkp . spki_hashes . size ( ) ) ;
 EXPECT_EQ ( sha1 . tag , new_domain_state . pkp . spki_hashes [ 0 ] . tag ) ;
 EXPECT_EQ ( 0 , memcmp ( new_domain_state . pkp . spki_hashes [ 0 ] . data ( ) , sha1 . data ( ) , sha1 . size ( ) ) ) ;
 }


njs_vmcode_array(njs_vm_t *vm, u_char *pc)
{
    uint32_t            length;
    njs_array_t         *array;
    njs_value_t         *value;
    njs_vmcode_array_t  *code;

    code = (njs_vmcode_array_t *) pc;

    array = njs_array_alloc(vm, 0, code->length, NJS_ARRAY_SPARE);

    if (njs_fast_path(array != NULL)) {

        if (code->ctor) {
            /* Array of the form [,,,], [1,,]. */
            value = array->start;
            length = array->length;

            do {
                njs_set_invalid(value);
                value++;
                length--;
            } while (length != 0);

        } else {
            /* Array of the form [], [,,1], [1,2,3]. */
            array->length = 0;
        }

        njs_set_array(&vm->retval, array);

        return sizeof(njs_vmcode_array_t);
    }

    return NJS_ERROR;
}


static void qvirtio_9p_pci_free(QVirtIO9P *v9p) { qvirtqueue_cleanup(v9p->dev->bus, v9p->vq, v9p->alloc); pc_alloc_uninit(v9p->alloc); qvirtio_pci_device_disable(container_of(v9p->dev, QVirtioPCIDevice, vdev)); g_free(v9p->dev); qpci_free_pc(v9p->bus); g_free(v9p); }


int load_vmstate(const char *name) { BlockDriverState *bs, *bs_vm_state; QEMUSnapshotInfo sn; QEMUFile *f; int ret; if (!bdrv_all_can_snapshot(&bs)) { error_report("Device '%s' is writable but does not support snapshots.", bdrv_get_device_name(bs)); return -ENOTSUP; } bs_vm_state = find_vmstate_bs(); if (!bs_vm_state) { error_report("No block device supports snapshots"); return -ENOTSUP; } /* Don't even try to load empty VM states */ ret = bdrv_snapshot_find(bs_vm_state, &sn, name); if (ret < 0) { return ret; } else if (sn.vm_state_size == 0) { error_report("This is a disk-only snapshot. Revert to it offline " "using qemu-img."); return -EINVAL; } /* Verify if there is any device that doesn't support snapshots and is writable and check if the requested snapshot is available too. */ bs = NULL; while ((bs = bdrv_next(bs))) { if (!bdrv_can_snapshot(bs)) { continue; } ret = bdrv_snapshot_find(bs, &sn, name); if (ret < 0) { error_report("Device '%s' does not have the requested snapshot '%s'", bdrv_get_device_name(bs), name); return ret; } } /* Flush all IO requests so they don't interfere with the new state. */ bdrv_drain_all(); ret = bdrv_all_goto_snapshot(name, &bs); if (ret < 0) { error_report("Error %d while activating snapshot '%s' on '%s'", ret, name, bdrv_get_device_name(bs)); return ret; } /* restore the VM state */ f = qemu_fopen_bdrv(bs_vm_state, 0); if (!f) { error_report("Could not open VM state file"); return -EINVAL; } qemu_system_reset(VMRESET_SILENT); migration_incoming_state_new(f); ret = qemu_loadvm_state(f); qemu_fclose(f); migration_incoming_state_destroy(); if (ret < 0) { error_report("Error %d while loading VM state", ret); return ret; } return 0; }


static void gdb_read_byte(GDBState *s, int ch) { CPUState *env = s->env; int i, csum; uint8_t reply; #ifndef CONFIG_USER_ONLY if (s->last_packet_len) { /* Waiting for a response to the last packet. If we see the start of a new command then abandon the previous response. */ if (ch == '-') { #ifdef DEBUG_GDB printf("Got NACK, retransmitting\n"); #endif put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len); } #ifdef DEBUG_GDB else if (ch == '+') printf("Got ACK\n"); else printf("Got '%c' when expecting ACK/NACK\n", ch); #endif if (ch == '+' || ch == '$') s->last_packet_len = 0; if (ch != '$') return; } if (vm_running) { /* when the CPU is running, we cannot do anything except stop it when receiving a char */ vm_stop(EXCP_INTERRUPT); } else #endif { switch(s->state) { case RS_IDLE: if (ch == '$') { s->line_buf_index = 0; s->state = RS_GETLINE; } break; case RS_GETLINE: if (ch == '#') { s->state = RS_CHKSUM1; } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) { s->state = RS_IDLE; } else { s->line_buf[s->line_buf_index++] = ch; } break; case RS_CHKSUM1: s->line_buf[s->line_buf_index] = '\0'; s->line_csum = fromhex(ch) << 4; s->state = RS_CHKSUM2; break; case RS_CHKSUM2: s->line_csum |= fromhex(ch); csum = 0; for(i = 0; i < s->line_buf_index; i++) { csum += s->line_buf[i]; } if (s->line_csum != (csum & 0xff)) { reply = '-'; put_buffer(s, &reply, 1); s->state = RS_IDLE; } else { reply = '+'; put_buffer(s, &reply, 1); s->state = gdb_handle_packet(s, env, s->line_buf); } break; default: abort(); } } }


static int _warc_read ( struct archive_read * a , const void * * buf , size_t * bsz , int64_t * off ) {
 struct warc_s * w = a -> format -> data ;
 const char * rab ;
 ssize_t nrd ;
 if ( w -> cntoff >= w -> cntlen ) {
 eof : * buf = NULL ;
 * bsz = 0U ;
 * off = w -> cntoff + 4U ;
 w -> unconsumed = 0U ;
 return ( ARCHIVE_EOF ) ;
 }
 rab = __archive_read_ahead ( a , 1U , & nrd ) ;
 if ( nrd < 0 ) {
 * bsz = 0U ;
 return ( int ) nrd ;
 }
 else if ( nrd == 0 ) {
 goto eof ;
 }
 else if ( ( size_t ) nrd > w -> cntlen - w -> cntoff ) {
 nrd = w -> cntlen - w -> cntoff ;
 }
 * off = w -> cntoff ;
 * bsz = nrd ;
 * buf = rab ;
 w -> cntoff += nrd ;
 w -> unconsumed = ( size_t ) nrd ;
 return ( ARCHIVE_OK ) ;
 }


static int parse_CRowSeekAt ( tvbuff_t * tvb , int offset , proto_tree * parent_tree , const char * fmt , ... ) {
 proto_tree * tree ;
 proto_item * item ;
 va_list ap ;
 const char * txt ;
 va_start ( ap , fmt ) ;
 txt = wmem_strdup_vprintf ( wmem_packet_scope ( ) , fmt , ap ) ;
 va_end ( ap ) ;
 tree = proto_tree_add_subtree ( parent_tree , tvb , offset , 0 , ett_CRowsSeekAt , & item , txt ) ;
 proto_tree_add_item ( tree , hf_mswsp_crowseekat_bmkoffset , tvb , offset , 4 , ENC_LITTLE_ENDIAN ) ;
 offset += 4 ;
 proto_tree_add_item ( tree , hf_mswsp_crowseekat_skip , tvb , offset , 4 , ENC_LITTLE_ENDIAN ) ;
 offset += 4 ;
 proto_tree_add_item ( tree , hf_mswsp_crowseekat_hregion , tvb , offset , 4 , ENC_LITTLE_ENDIAN ) ;
 offset += 4 ;
 proto_item_set_end ( item , tvb , offset ) ;
 return offset ;
 }


void ahlog ( ArchiveHandle * AH , int level , const char * fmt , ... ) {
 va_list ap ;
 if ( AH -> debugLevel < level && ( ! AH -> public . verbose || level > 1 ) ) return ;
 va_start ( ap , fmt ) ;
 vwrite_msg ( NULL , fmt , ap ) ;
 va_end ( ap ) ;
 }


static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
				  unsigned long arg)
{
	struct mm_struct *mm = ctx->mm;
	struct vm_area_struct *vma, *prev, *cur;
	int ret;
	struct uffdio_range uffdio_unregister;
	unsigned long new_flags;
	bool found;
	unsigned long start, end, vma_end;
	const void __user *buf = (void __user *)arg;

	ret = -EFAULT;
	if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
		goto out;

	ret = validate_range(mm, uffdio_unregister.start,
			     uffdio_unregister.len);
	if (ret)
		goto out;

	start = uffdio_unregister.start;
	end = start + uffdio_unregister.len;

	ret = -ENOMEM;
	if (!mmget_not_zero(mm))
		goto out;

	down_write(&mm->mmap_sem);
	vma = find_vma_prev(mm, start, &prev);
	if (!vma)
		goto out_unlock;

	/* check that there's at least one vma in the range */
	ret = -EINVAL;
	if (vma->vm_start >= end)
		goto out_unlock;

	/*
	 * If the first vma contains huge pages, make sure start address
	 * is aligned to huge page size.
	 */
	if (is_vm_hugetlb_page(vma)) {
		unsigned long vma_hpagesize = vma_kernel_pagesize(vma);

		if (start & (vma_hpagesize - 1))
			goto out_unlock;
	}

	/*
	 * Search for not compatible vmas.
	 */
	found = false;
	ret = -EINVAL;
	for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
		cond_resched();

		BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
		       !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));

		/*
		 * Check not compatible vmas, not strictly required
		 * here as not compatible vmas cannot have an
		 * userfaultfd_ctx registered on them, but this
		 * provides for more strict behavior to notice
		 * unregistration errors.
		 */
		if (!vma_can_userfault(cur))
			goto out_unlock;

		found = true;
	}
	BUG_ON(!found);

	if (vma->vm_start < start)
		prev = vma;

	ret = 0;
	do {
		cond_resched();

		BUG_ON(!vma_can_userfault(vma));

		/*
		 * Nothing to do: this vma is already registered into this
		 * userfaultfd and with the right tracking mode too.
		 */
		if (!vma->vm_userfaultfd_ctx.ctx)
			goto skip;

		if (vma->vm_start > start)
			start = vma->vm_start;
		vma_end = min(end, vma->vm_end);

		if (userfaultfd_missing(vma)) {
			/*
			 * Wake any concurrent pending userfault while
			 * we unregister, so they will not hang
			 * permanently and it avoids userland to call
			 * UFFDIO_WAKE explicitly.
			 */
			struct userfaultfd_wake_range range;
			range.start = start;
			range.len = vma_end - start;
			wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
		}

		new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
		prev = vma_merge(mm, prev, start, vma_end, new_flags,
				 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
				 vma_policy(vma),
				 NULL_VM_UFFD_CTX);
		if (prev) {
			vma = prev;
			goto next;
		}
		if (vma->vm_start < start) {
			ret = split_vma(mm, vma, start, 1);
			if (ret)
				break;
		}
		if (vma->vm_end > end) {
			ret = split_vma(mm, vma, end, 0);
			if (ret)
				break;
		}
	next:
		/*
		 * In the vma_merge() successful mprotect-like case 8:
		 * the next vma was merged into the current one and
		 * the current one has not been updated yet.
		 */
		vma->vm_flags = new_flags;
		vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;

	skip:
		prev = vma;
		start = vma->vm_end;
		vma = vma->vm_next;
	} while (vma && vma->vm_start < end);
out_unlock:
	up_write(&mm->mmap_sem);
	mmput(mm);
out:
	return ret;
}


void error_set(Error **errp, const char *fmt, ...) { Error *err; va_list ap; if (errp == NULL) { return; } assert(*errp == NULL); err = g_malloc0(sizeof(*err)); va_start(ap, fmt); err->obj = qobject_to_qdict(qobject_from_jsonv(fmt, &ap)); va_end(ap); err->msg = qerror_format(fmt, err->obj); *errp = err; }


static inline void vmsvga_cursor_define ( struct vmsvga_state_s * s , struct vmsvga_cursor_definition_s * c ) {
 QEMUCursor * qc ;
 int i , pixels ;
 qc = cursor_alloc ( c -> width , c -> height ) ;
 qc -> hot_x = c -> hot_x ;
 qc -> hot_y = c -> hot_y ;
 switch ( c -> bpp ) {
 case 1 : cursor_set_mono ( qc , 0xffffff , 0x000000 , ( void * ) c -> image , 1 , ( void * ) c -> mask ) ;
 # ifdef DEBUG cursor_print_ascii_art ( qc , "vmware/mono" ) ;
 # endif break ;
 case 32 : cursor_set_mono ( qc , 0x000000 , 0x000000 , ( void * ) c -> mask , 1 , ( void * ) c -> mask ) ;
 pixels = c -> width * c -> height ;
 for ( i = 0 ;
 i < pixels ;
 i ++ ) {
 qc -> data [ i ] |= c -> image [ i ] & 0xffffff ;
 }
 # ifdef DEBUG cursor_print_ascii_art ( qc , "vmware/32bit" ) ;
 # endif break ;
 default : fprintf ( stderr , "%s: unhandled bpp %d, using fallback cursor\n" , __func__ , c -> bpp ) ;
 cursor_put ( qc ) ;
 qc = cursor_builtin_left_ptr ( ) ;
 }
 dpy_cursor_define ( s -> vga . con , qc ) ;
 cursor_put ( qc ) ;
 }


int nextvar ( int * datalen , const char * * datap , char * * vname , char * * vvalue ) {
 const char * cp ;
 const char * np ;
 const char * cpend ;
 size_t srclen ;
 size_t len ;
 static char name [ MAXVARLEN ] ;
 static char value [ MAXVALLEN ] ;
 cp = * datap ;
 cpend = cp + * datalen ;
 while ( cp < cpend && ( * cp == ',' || isspace ( ( int ) * cp ) ) ) cp ++ ;
 if ( cp >= cpend ) return 0 ;
 srclen = strcspn ( cp , ",=\r\n" ) ;
 srclen = min ( srclen , ( size_t ) ( cpend - cp ) ) ;
 len = srclen ;
 while ( len > 0 && isspace ( ( unsigned char ) cp [ len - 1 ] ) ) len -- ;
 if ( len > 0 ) memcpy ( name , cp , len ) ;
 name [ len ] = '\0' ;
 * vname = name ;
 cp += srclen ;
 if ( cp >= cpend || * cp == ',' || * cp == '\r' || * cp == '\n' ) {
 if ( cp < cpend ) cp ++ ;
 * datap = cp ;
 * datalen = cpend - cp ;
 * vvalue = NULL ;
 return 1 ;
 }
 cp ++ ;
 while ( cp < cpend && ( isspace ( ( unsigned char ) * cp ) && * cp != '\r' && * cp != '\n' ) ) cp ++ ;
 np = cp ;
 if ( '"' == * np ) {
 do {
 np ++ ;
 }
 while ( np < cpend && '"' != * np ) ;
 if ( np < cpend && '"' == * np ) np ++ ;
 }
 else {
 while ( np < cpend && ',' != * np && '\r' != * np ) np ++ ;
 }
 len = np - cp ;
 if ( np > cpend || len >= sizeof ( value ) || ( np < cpend && ',' != * np && '\r' != * np ) ) return 0 ;
 memcpy ( value , cp , len ) ;
 while ( len > 0 && isspace ( ( unsigned char ) value [ len - 1 ] ) ) len -- ;
 value [ len ] = '\0' ;
 if ( np < cpend && ',' == * np ) np ++ ;
 * datap = np ;
 * datalen = cpend - np ;
 * vvalue = value ;
 return 1 ;
 }


static void usb_host_auto_check(void *unused) { struct USBHostDevice *s; int unconnected = 0; usb_host_scan(NULL, usb_host_auto_scan); QTAILQ_FOREACH(s, &hostdevs, next) { if (s->fd == -1) { unconnected++; } } if (unconnected == 0) { /* nothing to watch */ if (usb_auto_timer) { qemu_del_timer(usb_auto_timer); } return; } if (!usb_auto_timer) { usb_auto_timer = qemu_new_timer(rt_clock, usb_host_auto_check, NULL); if (!usb_auto_timer) { return; } } qemu_mod_timer(usb_auto_timer, qemu_get_clock(rt_clock) + 2000); }