GdkPixbuf * convert_buffer_to_pixbuf (GstBuffer *buffer, GCancellable *cancellable) { GstCaps *pb_caps; GstElement *pipeline; GstBuffer *out_buffer = NULL; GstElement *src, *sink, *colorspace, *scale, *filter; GstBus *bus; GstMessage *msg; GstStateChangeReturn state G_GNUC_UNUSED; gboolean ret; int dw, dh, i; GstStructure *s; s = gst_caps_get_structure (GST_BUFFER_CAPS (buffer), 0); gst_structure_get_int (s, "width", &dw); gst_structure_get_int (s, "height", &dh); pb_caps = gst_caps_new_simple ("video/x-raw-rgb", "bpp", G_TYPE_INT, 24, "depth", G_TYPE_INT, 24, "width", G_TYPE_INT, dw, "height", G_TYPE_INT, dh, "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1, NULL); pipeline = gst_pipeline_new ("pipeline"); src = gst_element_factory_make ("fakesrc", "src"); colorspace = gst_element_factory_make ("ffmpegcolorspace", "colorspace"); scale = gst_element_factory_make ("videoscale", "scale"); filter = gst_element_factory_make ("capsfilter", "filter"); sink = gst_element_factory_make ("fakesink", "sink"); gst_bin_add_many (GST_BIN (pipeline), src, colorspace, scale, filter, sink, NULL); g_object_set (filter, "caps", pb_caps, NULL); g_object_set (src, "num-buffers", 1, "sizetype", 2, "sizemax", GST_BUFFER_SIZE (buffer), "signal-handoffs", TRUE, NULL); g_signal_connect (src, "handoff", G_CALLBACK (push_buffer), buffer); g_object_set (sink, "signal-handoffs", TRUE, "preroll-queue-len", 1, NULL); g_signal_connect (sink, "handoff", G_CALLBACK (pull_buffer), &out_buffer); ret = gst_element_link (src, colorspace); if (ret == FALSE) { g_warning ("Failed to link src->colorspace"); return NULL; } ret = gst_element_link (colorspace, scale); if (ret == FALSE) { g_warning ("Failed to link colorspace->scale"); return NULL; } ret = gst_element_link (scale, filter); if (ret == FALSE) { g_warning ("Failed to link scale->filter"); return NULL; } ret = gst_element_link (filter, sink); if (ret == FALSE) { g_warning ("Failed to link filter->sink"); return NULL; } bus = gst_element_get_bus (GST_ELEMENT (pipeline)); state = gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PLAYING); i = 0; msg = NULL; while (msg == NULL && i < 5) { msg = gst_bus_timed_pop_filtered (bus, GST_SECOND, GST_MESSAGE_ERROR | GST_MESSAGE_EOS); i++; } /* FIXME: Notify about error? */ gst_message_unref (msg); gst_caps_unref (pb_caps); if (out_buffer) { GdkPixbuf *pixbuf; char *data; data = g_memdup (GST_BUFFER_DATA (out_buffer), GST_BUFFER_SIZE (out_buffer)); pixbuf = gdk_pixbuf_new_from_data ((guchar *) data, GDK_COLORSPACE_RGB, FALSE, 8, dw, dh, GST_ROUND_UP_4 (dw * 3), (GdkPixbufDestroyNotify) g_free, NULL); gst_buffer_unref (buffer); return pixbuf; } /* FIXME: Check what buffers need freed */ return NULL; }
/** * @param spline correctly setup GxkSpline * @return newly allocated spline * Produce a copy of an already setup spline. */ GxkSpline* gxk_spline_copy (GxkSpline *spline) { return g_memdup (spline, sizeof (spline[0]) + spline->n_segs * sizeof (spline->segs[0])); }
/** * clutter_event_copy: * @event: A #ClutterEvent. * * Copies @event. * * Return value: (transfer full): A newly allocated #ClutterEvent */ ClutterEvent * clutter_event_copy (const ClutterEvent *event) { ClutterEvent *new_event; ClutterEventPrivate *new_real_event; ClutterInputDevice *device; gint n_axes = 0; g_return_val_if_fail (event != NULL, NULL); new_event = clutter_event_new (CLUTTER_NOTHING); new_real_event = (ClutterEventPrivate *) new_event; *new_event = *event; if (is_event_allocated (event)) { ClutterEventPrivate *real_event = (ClutterEventPrivate *) event; new_real_event->device = real_event->device; new_real_event->source_device = real_event->source_device; new_real_event->delta_x = real_event->delta_x; new_real_event->delta_y = real_event->delta_y; } device = clutter_event_get_device (event); if (device != NULL) n_axes = clutter_input_device_get_n_axes (device); switch (event->type) { case CLUTTER_BUTTON_PRESS: case CLUTTER_BUTTON_RELEASE: if (event->button.axes != NULL) new_event->button.axes = g_memdup (event->button.axes, sizeof (gdouble) * n_axes); break; case CLUTTER_SCROLL: if (event->scroll.axes != NULL) new_event->scroll.axes = g_memdup (event->scroll.axes, sizeof (gdouble) * n_axes); break; case CLUTTER_MOTION: if (event->motion.axes != NULL) new_event->motion.axes = g_memdup (event->motion.axes, sizeof (gdouble) * n_axes); break; case CLUTTER_TOUCH_BEGIN: case CLUTTER_TOUCH_UPDATE: case CLUTTER_TOUCH_END: case CLUTTER_TOUCH_CANCEL: if (event->touch.axes != NULL) new_event->touch.axes = g_memdup (event->touch.axes, sizeof (gdouble) * n_axes); break; default: break; } if (is_event_allocated (event)) _clutter_backend_copy_event_data (clutter_get_default_backend (), event, new_event); return new_event; }
static int ossfs_getattr(const char *path, struct stat *stbuf) { gint res; OssObject *object; GError *error; gpointer value; gpointer st; GString *dir; g_debug("ossfs_getattr(path=%s)", path); memset(stbuf, 0, sizeof(struct stat)); if (cache_contains((gpointer)path)) { st = cache_lookup((gpointer)path); memcpy(stbuf, st, sizeof(struct stat)); return 0; } if (g_strcmp0(path, "/") == 0) { stbuf->st_nlink = 1; stbuf->st_mode = default_mode | S_IFDIR; stbuf->st_uid = getuid(); stbuf->st_gid = getgid(); return 0; } object = oss_object_new(path); if (!object) return -ENOMEM; error = NULL; res = oss_object_head(service, object, &error); if (res) { oss_object_destroy(object); switch (error->code) { case OSS_ERROR_NO_SUCH_KEY: if (g_str_has_suffix(path, "/")) return -ENOENT; /* try to get path as directory */ dir = g_string_new(path); if (dir == NULL) return -ENOMEM; g_string_append_c(dir, '/'); g_message("try to get %s attribute", dir->str); if (g_hash_table_contains(cache, dir->str)) { st = g_hash_table_lookup(cache, dir->str); memcpy(stbuf, st, sizeof(struct stat)); g_string_free(dir, TRUE); return 0; } object = oss_object_new(dir->str); g_string_free(dir, TRUE); if (!object) return -ENOMEM; error = NULL; res = oss_object_head(service, object, &error); if (res) { oss_object_destroy(object); switch (error->code) { case OSS_ERROR_NO_SUCH_KEY: return -ENOENT; default: return -EIO; } } break; /* case OSS_ERROR_NO_SUCH_KEY */ default: return -EIO; } } /* st_mode */ value = g_hash_table_lookup(object->meta, OSS_META_MODE); if (value) { g_debug("%s: %s", OSS_META_MODE, (gchar*)value); stbuf->st_mode = g_ascii_strtoull((gchar*)value, NULL, 10); } else { stbuf->st_mode = default_mode; /* TODO: make sure how to test an object is a dir */ if (g_str_has_suffix(object->key, "/")) { stbuf->st_mode |= S_IFDIR; } else { stbuf->st_mode |= S_IFREG; } g_debug("using default mode: %d", stbuf->st_mode); } stbuf->st_nlink = 1; stbuf->st_size = object->size; g_debug("size: %ld", (long)stbuf->st_size); if (S_ISREG(stbuf->st_mode)) { stbuf->st_blocks = stbuf->st_size / 512 + 1; } stbuf->st_uid = getuid(); stbuf->st_gid = getgid(); stbuf->st_mtime = parse_date_time_gmt(object->last_modified); st = g_memdup((gpointer)stbuf, sizeof(struct stat)); cache_add(g_strdup(object->key), st); oss_object_destroy(object); return 0; }
void fw_cfg_add_string(FWCfgState *s, uint16_t key, const char *value) { size_t sz = strlen(value) + 1; return fw_cfg_add_bytes(s, key, g_memdup(value, sz), sz); }
gchar *g_strdup (const gchar *str) { if (str) return g_memdup (str, (guint)(strlen(str) + 1)); return NULL; }
static void tcp_pending(gpointer data, gint source, PurpleInputCondition cond) { PurpleConnection *gc = (PurpleConnection *) data; qq_data *qd; qq_connection *conn; guint8 buf[1024]; /* set to 16 when test tcp_rxqueue */ gint buf_len; gint bytes; guint8 *pkt; guint16 pkt_len; gchar *error_msg; guint8 *jump; gint jump_len; g_return_if_fail(gc != NULL && gc->proto_data != NULL); qd = (qq_data *) gc->proto_data; if(cond != PURPLE_INPUT_READ) { purple_connection_error_reason(gc, PURPLE_CONNECTION_ERROR_NETWORK_ERROR, _("Socket error")); return; } conn = connection_find(qd, source); g_return_if_fail(conn != NULL); /* test code, not using tcp_rxqueue memset(pkt,0, sizeof(pkt)); buf_len = read(qd->fd, pkt, sizeof(pkt)); if (buf_len > 2) { packet_process(gc, pkt + 2, buf_len - 2); } return; */ buf_len = read(source, buf, sizeof(buf)); if (buf_len < 0) { if (errno == EAGAIN) /* No worries */ return; error_msg = g_strdup_printf(_("Lost connection with server: %s"), g_strerror(errno)); purple_connection_error_reason(gc, PURPLE_CONNECTION_ERROR_NETWORK_ERROR, error_msg); g_free(error_msg); return; } else if (buf_len == 0) { purple_connection_error_reason(gc, PURPLE_CONNECTION_ERROR_NETWORK_ERROR, _("Server closed the connection")); return; } /* keep alive will be sent in 30 seconds since last_receive * QQ need a keep alive packet in every 60 seconds gc->last_received = time(NULL); */ #if 1 purple_debug_info("TCP_PENDING", "Read %d bytes, tcp_rxlen is %d\n", buf_len, conn->tcp_rxlen); #endif conn->tcp_rxqueue = g_realloc(conn->tcp_rxqueue, buf_len + conn->tcp_rxlen); memcpy(conn->tcp_rxqueue + conn->tcp_rxlen, buf, buf_len); conn->tcp_rxlen += buf_len; pkt = g_newa(guint8, MAX_PACKET_SIZE); while (PURPLE_CONNECTION_IS_VALID(gc)) { if (qd->openconns == NULL) { break; } if (conn->tcp_rxqueue == NULL) { conn->tcp_rxlen = 0; break; } if (conn->tcp_rxlen < QQ_TCP_HEADER_LENGTH) { break; } bytes = 0; bytes += qq_get16(&pkt_len, conn->tcp_rxqueue + bytes); if (conn->tcp_rxlen < pkt_len) { break; } #if 1 qq_show_packet("tcp_pending", conn->tcp_rxqueue, pkt_len); #endif /* purple_debug_info("TCP_PENDING", "Packet len=%d, rxlen=%d\n", pkt_len, conn->tcp_rxlen); */ if ( pkt_len < QQ_TCP_HEADER_LENGTH || *(conn->tcp_rxqueue + bytes) != QQ_PACKET_TAG || *(conn->tcp_rxqueue + pkt_len - 1) != QQ_PACKET_TAIL) { /* HEY! This isn't even a QQ. What are you trying to pull? */ purple_debug_warning("TCP_PENDING", "Packet error, no header or tail tag\n"); jump = memchr(conn->tcp_rxqueue + 1, QQ_PACKET_TAIL, conn->tcp_rxlen - 1); if ( !jump ) { purple_debug_warning("TCP_PENDING", "Failed to find next tail, clear receive buffer\n"); g_free(conn->tcp_rxqueue); conn->tcp_rxqueue = NULL; conn->tcp_rxlen = 0; return; } /* jump and over QQ_PACKET_TAIL */ jump_len = (jump - conn->tcp_rxqueue) + 1; purple_debug_warning("TCP_PENDING", "Find next tail at %d, jump %d\n", jump_len, jump_len + 1); g_memmove(conn->tcp_rxqueue, jump, conn->tcp_rxlen - jump_len); conn->tcp_rxlen -= jump_len; continue; } /* get packet */ memset(pkt, 0, MAX_PACKET_SIZE); g_memmove(pkt, conn->tcp_rxqueue + bytes, pkt_len - bytes); /* jump to next packet */ conn->tcp_rxlen -= pkt_len; if (conn->tcp_rxlen) { /* purple_debug_info("TCP_PENDING", "shrink tcp_rxqueue to %d\n", conn->tcp_rxlen); */ jump = g_memdup(conn->tcp_rxqueue + pkt_len, conn->tcp_rxlen); g_free(conn->tcp_rxqueue); conn->tcp_rxqueue = jump; } else { /* purple_debug_info("TCP_PENDING", "free tcp_rxqueue\n"); */ g_free(conn->tcp_rxqueue); conn->tcp_rxqueue = NULL; } /* packet_process may call disconnect and destory data like conn * do not call packet_process before jump, * break if packet_process return FALSE */ if (packet_process(gc, pkt, pkt_len - bytes) == FALSE) { purple_debug_info("TCP_PENDING", "Connection has been destory\n"); break; } } }
static void copy_src(struct sr_config *src, struct sr_datafeed_meta *meta_copy) { g_variant_ref(src->data); meta_copy->config = g_slist_append(meta_copy->config, g_memdup(src, sizeof(struct sr_config))); }
SR_PRIV int sr_packet_copy(const struct sr_datafeed_packet *packet, struct sr_datafeed_packet **copy) { const struct sr_datafeed_meta *meta; struct sr_datafeed_meta *meta_copy; const struct sr_datafeed_logic *logic; struct sr_datafeed_logic *logic_copy; const struct sr_datafeed_analog_old *analog_old; struct sr_datafeed_analog_old *analog_old_copy; const struct sr_datafeed_analog *analog; struct sr_datafeed_analog *analog_copy; uint8_t *payload; *copy = g_malloc0(sizeof(struct sr_datafeed_packet)); (*copy)->type = packet->type; switch (packet->type) { case SR_DF_TRIGGER: case SR_DF_END: /* No payload. */ break; case SR_DF_HEADER: payload = g_malloc(sizeof(struct sr_datafeed_header)); memcpy(payload, packet->payload, sizeof(struct sr_datafeed_header)); (*copy)->payload = payload; break; case SR_DF_META: meta = packet->payload; meta_copy = g_malloc0(sizeof(struct sr_datafeed_meta)); g_slist_foreach(meta->config, (GFunc)copy_src, meta_copy->config); (*copy)->payload = meta_copy; break; case SR_DF_LOGIC: logic = packet->payload; logic_copy = g_malloc(sizeof(logic)); logic_copy->length = logic->length; logic_copy->unitsize = logic->unitsize; memcpy(logic_copy->data, logic->data, logic->length * logic->unitsize); (*copy)->payload = logic_copy; break; case SR_DF_ANALOG_OLD: analog_old = packet->payload; analog_old_copy = g_malloc(sizeof(analog_old)); analog_old_copy->channels = g_slist_copy(analog_old->channels); analog_old_copy->num_samples = analog_old->num_samples; analog_old_copy->mq = analog_old->mq; analog_old_copy->unit = analog_old->unit; analog_old_copy->mqflags = analog_old->mqflags; analog_old_copy->data = g_malloc(analog_old->num_samples * sizeof(float)); memcpy(analog_old_copy->data, analog_old->data, analog_old->num_samples * sizeof(float)); (*copy)->payload = analog_old_copy; break; case SR_DF_ANALOG: analog = packet->payload; analog_copy = g_malloc(sizeof(analog)); analog_copy->data = g_malloc( analog->encoding->unitsize * analog->num_samples); memcpy(analog_copy->data, analog->data, analog->encoding->unitsize * analog->num_samples); analog_copy->num_samples = analog->num_samples; analog_copy->encoding = g_memdup(analog->encoding, sizeof(struct sr_analog_encoding)); analog_copy->meaning = g_memdup(analog->meaning, sizeof(struct sr_analog_meaning)); analog_copy->meaning->channels = g_slist_copy( analog->meaning->channels); analog_copy->spec = g_memdup(analog->spec, sizeof(struct sr_analog_spec)); (*copy)->payload = analog_copy; break; default: sr_err("Unknown packet type %d", packet->type); return SR_ERR; } return SR_OK; }
static gboolean gst_fdkaacenc_set_format (GstAudioEncoder * enc, GstAudioInfo * info) { GstFdkAacEnc *self = GST_FDKAACENC (enc); gboolean ret = FALSE; GstCaps *allowed_caps; GstCaps *src_caps; AACENC_ERROR err; gint transmux = 0, aot = AOT_AAC_LC; gint mpegversion = 4; CHANNEL_MODE channel_mode; AACENC_InfoStruct enc_info = { 0 }; gint bitrate; if (self->enc) { /* drain */ gst_fdkaacenc_handle_frame (enc, NULL); aacEncClose (&self->enc); } allowed_caps = gst_pad_get_allowed_caps (GST_AUDIO_ENCODER_SRC_PAD (self)); GST_DEBUG_OBJECT (self, "allowed caps: %" GST_PTR_FORMAT, allowed_caps); if (allowed_caps && gst_caps_get_size (allowed_caps) > 0) { GstStructure *s = gst_caps_get_structure (allowed_caps, 0); const gchar *str = NULL; if ((str = gst_structure_get_string (s, "stream-format"))) { if (strcmp (str, "adts") == 0) { GST_DEBUG_OBJECT (self, "use ADTS format for output"); transmux = 2; } else if (strcmp (str, "adif") == 0) { GST_DEBUG_OBJECT (self, "use ADIF format for output"); transmux = 1; } else if (strcmp (str, "raw") == 0) { GST_DEBUG_OBJECT (self, "use RAW format for output"); transmux = 0; } } gst_structure_get_int (s, "mpegversion", &mpegversion); } if (allowed_caps) gst_caps_unref (allowed_caps); err = aacEncOpen (&self->enc, 0, GST_AUDIO_INFO_CHANNELS (info)); if (err != AACENC_OK) { GST_ERROR_OBJECT (self, "Unable to open encoder: %d\n", err); return FALSE; } aot = AOT_AAC_LC; if ((err = aacEncoder_SetParam (self->enc, AACENC_AOT, aot)) != AACENC_OK) { GST_ERROR_OBJECT (self, "Unable to set AOT %d: %d\n", aot, err); return FALSE; } if ((err = aacEncoder_SetParam (self->enc, AACENC_SAMPLERATE, GST_AUDIO_INFO_RATE (info))) != AACENC_OK) { GST_ERROR_OBJECT (self, "Unable to set sample rate %d: %d\n", GST_AUDIO_INFO_RATE (info), err); return FALSE; } if (GST_AUDIO_INFO_CHANNELS (info) == 1) { channel_mode = MODE_1; self->need_reorder = FALSE; self->aac_positions = NULL; } else { guint64 in_channel_mask, out_channel_mask; gint i; for (i = 0; i < G_N_ELEMENTS (channel_layouts); i++) { if (channel_layouts[i].channels != GST_AUDIO_INFO_CHANNELS (info)) continue; gst_audio_channel_positions_to_mask (&GST_AUDIO_INFO_POSITION (info, 0), GST_AUDIO_INFO_CHANNELS (info), FALSE, &in_channel_mask); gst_audio_channel_positions_to_mask (channel_layouts[i].positions, channel_layouts[i].channels, FALSE, &out_channel_mask); if (in_channel_mask == out_channel_mask) { channel_mode = channel_layouts[i].mode; self->need_reorder = memcmp (channel_layouts[i].positions, &GST_AUDIO_INFO_POSITION (info, 0), GST_AUDIO_INFO_CHANNELS (info) * sizeof (GstAudioChannelPosition)) != 0; self->aac_positions = channel_layouts[i].positions; break; } } if (i == G_N_ELEMENTS (channel_layouts)) { GST_ERROR_OBJECT (self, "Couldn't find a valid channel layout"); return FALSE; } } if ((err = aacEncoder_SetParam (self->enc, AACENC_CHANNELMODE, channel_mode)) != AACENC_OK) { GST_ERROR_OBJECT (self, "Unable to set channel mode %d: %d", channel_mode, err); return FALSE; } /* MPEG channel order */ if ((err = aacEncoder_SetParam (self->enc, AACENC_CHANNELORDER, 0)) != AACENC_OK) { GST_ERROR_OBJECT (self, "Unable to set channel order %d: %d", channel_mode, err); return FALSE; } bitrate = self->bitrate; /* See * http://wiki.hydrogenaud.io/index.php?title=Fraunhofer_FDK_AAC#Recommended_Sampling_Rate_and_Bitrate_Combinations */ if (bitrate == 0) { if (GST_AUDIO_INFO_CHANNELS (info) == 1) { if (GST_AUDIO_INFO_RATE (info) < 16000) { bitrate = 8000; } else if (GST_AUDIO_INFO_RATE (info) == 16000) { bitrate = 16000; } else if (GST_AUDIO_INFO_RATE (info) < 32000) { bitrate = 24000; } else if (GST_AUDIO_INFO_RATE (info) == 32000) { bitrate = 32000; } else if (GST_AUDIO_INFO_RATE (info) <= 44100) { bitrate = 56000; } else { bitrate = 160000; } } else if (GST_AUDIO_INFO_CHANNELS (info) == 2) { if (GST_AUDIO_INFO_RATE (info) < 16000) { bitrate = 16000; } else if (GST_AUDIO_INFO_RATE (info) == 16000) { bitrate = 24000; } else if (GST_AUDIO_INFO_RATE (info) < 22050) { bitrate = 32000; } else if (GST_AUDIO_INFO_RATE (info) < 32000) { bitrate = 40000; } else if (GST_AUDIO_INFO_RATE (info) == 32000) { bitrate = 96000; } else if (GST_AUDIO_INFO_RATE (info) <= 44100) { bitrate = 112000; } else { bitrate = 320000; } } else { /* 5, 5.1 */ if (GST_AUDIO_INFO_RATE (info) < 32000) { bitrate = 160000; } else if (GST_AUDIO_INFO_RATE (info) <= 44100) { bitrate = 240000; } else { bitrate = 320000; } } } if ((err = aacEncoder_SetParam (self->enc, AACENC_TRANSMUX, transmux)) != AACENC_OK) { GST_ERROR_OBJECT (self, "Unable to set transmux %d: %d", transmux, err); return FALSE; } if ((err = aacEncoder_SetParam (self->enc, AACENC_BITRATE, bitrate)) != AACENC_OK) { GST_ERROR_OBJECT (self, "Unable to set bitrate %d: %d", bitrate, err); return FALSE; } if ((err = aacEncEncode (self->enc, NULL, NULL, NULL, NULL)) != AACENC_OK) { GST_ERROR_OBJECT (self, "Unable to initialize encoder: %d", err); return FALSE; } if ((err = aacEncInfo (self->enc, &enc_info)) != AACENC_OK) { GST_ERROR_OBJECT (self, "Unable to get encoder info: %d", err); return FALSE; } gst_audio_encoder_set_frame_max (enc, 1); gst_audio_encoder_set_frame_samples_min (enc, enc_info.frameLength); gst_audio_encoder_set_frame_samples_max (enc, enc_info.frameLength); gst_audio_encoder_set_hard_min (enc, FALSE); self->outbuf_size = enc_info.maxOutBufBytes; self->samples_per_frame = enc_info.frameLength; src_caps = gst_caps_new_simple ("audio/mpeg", "mpegversion", G_TYPE_INT, mpegversion, "channels", G_TYPE_INT, GST_AUDIO_INFO_CHANNELS (info), "framed", G_TYPE_BOOLEAN, TRUE, "rate", G_TYPE_INT, GST_AUDIO_INFO_RATE (info), NULL); /* raw */ if (transmux == 0) { GstBuffer *codec_data = gst_buffer_new_wrapped (g_memdup (enc_info.confBuf, enc_info.confSize), enc_info.confSize); gst_caps_set_simple (src_caps, "codec_data", GST_TYPE_BUFFER, codec_data, "stream-format", G_TYPE_STRING, "raw", NULL); gst_buffer_unref (codec_data); } else if (transmux == 1) { gst_caps_set_simple (src_caps, "stream-format", G_TYPE_STRING, "adif", NULL); } else if (transmux == 2) { gst_caps_set_simple (src_caps, "stream-format", G_TYPE_STRING, "adts", NULL); } else { g_assert_not_reached (); } gst_codec_utils_aac_caps_set_level_and_profile (src_caps, enc_info.confBuf, enc_info.confSize); ret = gst_audio_encoder_set_output_format (enc, src_caps); gst_caps_unref (src_caps); return ret; }
int msn_handler( struct msn_handler_data *h ) { int st; h->rxq = g_renew( char, h->rxq, h->rxlen + 1024 ); st = read( h->fd, h->rxq + h->rxlen, 1024 ); h->rxlen += st; if( st <= 0 ) return( -1 ); if( getenv( "BITLBEE_DEBUG" ) ) { write( 2, "->C:", 4 ); write( 2, h->rxq + h->rxlen - st, st ); } while( st ) { int i; if( h->msglen == 0 ) { for( i = 0; i < h->rxlen; i ++ ) { if( h->rxq[i] == '\r' || h->rxq[i] == '\n' ) { char *cmd_text, **cmd; int count; cmd_text = g_strndup( h->rxq, i ); cmd = msn_linesplit( cmd_text ); for( count = 0; cmd[count]; count ++ ); st = h->exec_command( h, cmd, count ); g_free( cmd_text ); /* If the connection broke, don't continue. We don't even exist anymore. */ if( !st ) return( 0 ); if( h->msglen ) h->cmd_text = g_strndup( h->rxq, i ); /* Skip to the next non-emptyline */ while( i < h->rxlen && ( h->rxq[i] == '\r' || h->rxq[i] == '\n' ) ) i ++; break; } } /* If we reached the end of the buffer, there's still an incomplete command there. Return and wait for more data. */ if( i == h->rxlen && h->rxq[i-1] != '\r' && h->rxq[i-1] != '\n' ) break; } else { char *msg, **cmd; int count; /* Do we have the complete message already? */ if( h->msglen > h->rxlen ) break; msg = g_strndup( h->rxq, h->msglen ); cmd = msn_linesplit( h->cmd_text ); for( count = 0; cmd[count]; count ++ ); st = h->exec_message( h, msg, h->msglen, cmd, count ); g_free( msg ); g_free( h->cmd_text ); h->cmd_text = NULL; if( !st ) return( 0 ); i = h->msglen; h->msglen = 0; } /* More data after this block? */ if( i < h->rxlen ) { char *tmp; tmp = g_memdup( h->rxq + i, h->rxlen - i ); g_free( h->rxq ); h->rxq = tmp; h->rxlen -= i; i = 0; } else /* If not, reset the rx queue and get lost. */ { g_free( h->rxq ); h->rxq = g_new0( char, 1 ); h->rxlen = 0; return( 1 ); } } return( 1 ); }
static void make_source (GESFormatter * self, GList * reflist, GHashTable * source_table) { GHashTable *props_table, *effect_table; gchar **prio_array; GESLayer *layer; GESPitiviFormatterPrivate *priv = GES_PITIVI_FORMATTER (self)->priv; gchar *fac_ref = NULL, *media_type = NULL, *filename = NULL, *prio_str; GList *tmp = NULL, *keys, *tmp_key; GESUriClip *src = NULL; gint prio; gboolean a_avail = FALSE, v_avail = FALSE, video; GHashTable *trackelement_table = priv->track_elements_table; for (tmp = reflist; tmp; tmp = tmp->next) { /* Get the layer */ props_table = g_hash_table_lookup (trackelement_table, (gchar *) tmp->data); prio_str = (gchar *) g_hash_table_lookup (props_table, "priority"); prio_array = g_strsplit (prio_str, ")", 0); prio = (gint) g_ascii_strtod (prio_array[1], NULL); g_strfreev (prio_array); /* If we do not have any layer with this priority, create it */ if (!(layer = g_hash_table_lookup (priv->layers_table, &prio))) { layer = ges_layer_new (); g_object_set (layer, "auto-transition", TRUE, "priority", prio, NULL); ges_timeline_add_layer (self->timeline, layer); g_hash_table_insert (priv->layers_table, g_memdup (&prio, sizeof (guint64)), layer); } fac_ref = (gchar *) g_hash_table_lookup (props_table, "fac_ref"); media_type = (gchar *) g_hash_table_lookup (props_table, "media_type"); if (!g_strcmp0 (media_type, "pitivi.stream.VideoStream")) video = TRUE; else video = FALSE; /* FIXME I am sure we could reimplement this whole part * in a simpler way */ if (g_strcmp0 (fac_ref, (gchar *) "effect")) { /* FIXME this is a hack to get a ref to the formatter when receiving * child-added */ g_hash_table_insert (props_table, (gchar *) "current-formatter", self); if (a_avail && (!video)) { a_avail = FALSE; } else if (v_avail && (video)) { v_avail = FALSE; } else { /* If we only have audio or only video in the previous source, * set it has such */ if (a_avail) { ges_clip_set_supported_formats (GES_CLIP (src), GES_TRACK_TYPE_VIDEO); } else if (v_avail) { ges_clip_set_supported_formats (GES_CLIP (src), GES_TRACK_TYPE_AUDIO); } filename = (gchar *) g_hash_table_lookup (source_table, "filename"); src = ges_uri_clip_new (filename); if (!video) { v_avail = TRUE; a_avail = FALSE; } else { a_avail = TRUE; v_avail = FALSE; } set_properties (G_OBJECT (src), props_table); ges_layer_add_clip (layer, GES_CLIP (src)); g_signal_connect (src, "child-added", G_CALLBACK (track_element_added_cb), props_table); priv->sources_to_load = g_list_prepend (priv->sources_to_load, src); } } else { GESEffect *effect; gchar *active = (gchar *) g_hash_table_lookup (props_table, "active"); effect = ges_effect_new ((gchar *) g_hash_table_lookup (props_table, (gchar *) "effect_name")); ges_track_element_set_track_type (GES_TRACK_ELEMENT (effect), (video ? GES_TRACK_TYPE_VIDEO : GES_TRACK_TYPE_AUDIO)); effect_table = g_hash_table_lookup (props_table, (gchar *) "effect_props"); ges_container_add (GES_CONTAINER (src), GES_TIMELINE_ELEMENT (effect)); if (!g_strcmp0 (active, (gchar *) "(bool)False")) ges_track_element_set_active (GES_TRACK_ELEMENT (effect), FALSE); /* Set effect properties */ keys = g_hash_table_get_keys (effect_table); for (tmp_key = keys; tmp_key; tmp_key = tmp_key->next) { GstStructure *structure; const GValue *value; GParamSpec *spec; GstCaps *caps; gchar *prop_val; prop_val = (gchar *) g_hash_table_lookup (effect_table, (gchar *) tmp_key->data); if (g_strstr_len (prop_val, -1, "(GEnum)")) { gchar **val = g_strsplit (prop_val, ")", 2); ges_track_element_set_child_properties (GES_TRACK_ELEMENT (effect), (gchar *) tmp_key->data, atoi (val[1]), NULL); g_strfreev (val); } else if (ges_track_element_lookup_child (GES_TRACK_ELEMENT (effect), (gchar *) tmp->data, NULL, &spec)) { gchar *caps_str = g_strdup_printf ("structure1, property1=%s;", prop_val); caps = gst_caps_from_string (caps_str); g_free (caps_str); structure = gst_caps_get_structure (caps, 0); value = gst_structure_get_value (structure, "property1"); ges_track_element_set_child_property_by_pspec (GES_TRACK_ELEMENT (effect), spec, (GValue *) value); gst_caps_unref (caps); } } } } if (a_avail) { ges_clip_set_supported_formats (GES_CLIP (src), GES_TRACK_TYPE_VIDEO); } else if (v_avail) { ges_clip_set_supported_formats (GES_CLIP (src), GES_TRACK_TYPE_AUDIO); } }
/* * emer_gzip_compress: * @input_data: the data to compress. * @input_length: the length of the data to compress in bytes. * @compressed_length: (out): the length of the compressed data. * @error: (out) (optional): if compression failed, error will be set to a GError * describing the failure; otherwise it won't be modified. Pass NULL to ignore * this value. * * Compresses input_data with the gzip algorithm at compression level 9. Returns * NULL and sets error if compression fails. Sets compressed_length to the * length of the compressed data in bytes. * * Returns: the compressed data or NULL if compression fails. Free with g_free. */ gpointer emer_gzip_compress (gconstpointer input_data, gsize input_length, gsize *compressed_length, GError **error) { GZlibCompressor *zlib_compressor = g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_GZIP, COMPRESSION_LEVEL); GConverter *converter = G_CONVERTER (zlib_compressor); gsize allocated_space = input_length + 1; GByteArray *byte_array = g_byte_array_sized_new (allocated_space); gsize total_bytes_read = 0; gsize total_bytes_written = 0; while (TRUE) { gsize bytes_left_in_buffer = allocated_space - total_bytes_written; if (bytes_left_in_buffer == 0) { allocated_space *= 2; g_byte_array_set_size (byte_array, allocated_space); continue; } gsize bytes_left_in_input = input_length - total_bytes_read; GConverterFlags conversion_flags = bytes_left_in_input > 0 ? G_CONVERTER_NO_FLAGS : G_CONVERTER_INPUT_AT_END; guint8 *curr_output = byte_array->data + total_bytes_written; const guint8 *curr_input = ((const guint8 *) input_data) + total_bytes_read; gsize curr_bytes_written, curr_bytes_read; GError *local_error = NULL; GConverterResult conversion_result = g_converter_convert (converter, curr_input, bytes_left_in_input, curr_output, bytes_left_in_buffer, conversion_flags, &curr_bytes_read, &curr_bytes_written, &local_error); if (conversion_result == G_CONVERTER_ERROR) { if (g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NO_SPACE)) { g_error_free (local_error); allocated_space *= 2; g_byte_array_set_size (byte_array, allocated_space); continue; } g_object_unref (zlib_compressor); g_byte_array_free (byte_array, TRUE); g_propagate_error (error, local_error); return NULL; } total_bytes_read += curr_bytes_read; total_bytes_written += curr_bytes_written; if (conversion_result == G_CONVERTER_FINISHED) break; /* Expand the byte array. */ allocated_space *= 2; g_byte_array_set_size (byte_array, allocated_space); } g_object_unref (zlib_compressor); gpointer compressed_data = g_memdup (byte_array->data, total_bytes_written); g_byte_array_free (byte_array, TRUE); *compressed_length = total_bytes_written; return compressed_data; }
void mdb_append_column(GPtrArray *columns, MdbColumn *in_col) { g_ptr_array_add(columns, g_memdup(in_col,sizeof(MdbColumn))); }
static float* _vala_array_dup1 (float* self, int length) { return g_memdup (self, length * sizeof (float)); }
static int gst_wavpack_enc_push_block (void *id, void *data, int32_t count) { GstWavpackEncWriteID *wid = (GstWavpackEncWriteID *) id; GstWavpackEnc *enc = GST_WAVPACK_ENC (wid->wavpack_enc); GstFlowReturn *flow; GstBuffer *buffer; GstPad *pad; guchar *block = (guchar *) data; pad = (wid->correction) ? enc->wvcsrcpad : enc->srcpad; flow = (wid->correction) ? &enc->wvcsrcpad_last_return : &enc-> srcpad_last_return; *flow = gst_pad_alloc_buffer_and_set_caps (pad, GST_BUFFER_OFFSET_NONE, count, GST_PAD_CAPS (pad), &buffer); if (*flow != GST_FLOW_OK) { GST_WARNING_OBJECT (enc, "flow on %s:%s = %s", GST_DEBUG_PAD_NAME (pad), gst_flow_get_name (*flow)); return FALSE; } g_memmove (GST_BUFFER_DATA (buffer), block, count); if (count > sizeof (WavpackHeader) && memcmp (block, "wvpk", 4) == 0) { /* if it's a Wavpack block set buffer timestamp and duration, etc */ WavpackHeader wph; GST_LOG_OBJECT (enc, "got %d bytes of encoded wavpack %sdata", count, (wid->correction) ? "correction " : ""); gst_wavpack_read_header (&wph, block); /* Only set when pushing the first buffer again, in that case * we don't want to delay the buffer or push newsegment events */ if (!wid->passthrough) { /* Only push complete blocks */ if (enc->pending_buffer == NULL) { enc->pending_buffer = buffer; enc->pending_offset = wph.block_index; } else if (enc->pending_offset == wph.block_index) { enc->pending_buffer = gst_buffer_join (enc->pending_buffer, buffer); } else { GST_ERROR ("Got incomplete block, dropping"); gst_buffer_unref (enc->pending_buffer); enc->pending_buffer = buffer; enc->pending_offset = wph.block_index; } if (!(wph.flags & FINAL_BLOCK)) return TRUE; buffer = enc->pending_buffer; enc->pending_buffer = NULL; enc->pending_offset = 0; /* if it's the first wavpack block, send a NEW_SEGMENT event */ if (wph.block_index == 0) { gst_pad_push_event (pad, gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_TIME, 0, GST_BUFFER_OFFSET_NONE, 0)); /* save header for later reference, so we can re-send it later on * EOS with fixed up values for total sample count etc. */ if (enc->first_block == NULL && !wid->correction) { enc->first_block = g_memdup (GST_BUFFER_DATA (buffer), GST_BUFFER_SIZE (buffer)); enc->first_block_size = GST_BUFFER_SIZE (buffer); } } } /* set buffer timestamp, duration, offset, offset_end from * the wavpack header */ GST_BUFFER_TIMESTAMP (buffer) = enc->timestamp_offset + gst_util_uint64_scale_int (GST_SECOND, wph.block_index, enc->samplerate); GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale_int (GST_SECOND, wph.block_samples, enc->samplerate); GST_BUFFER_OFFSET (buffer) = wph.block_index; GST_BUFFER_OFFSET_END (buffer) = wph.block_index + wph.block_samples; } else { /* if it's something else set no timestamp and duration on the buffer */ GST_DEBUG_OBJECT (enc, "got %d bytes of unknown data", count); GST_BUFFER_TIMESTAMP (buffer) = GST_CLOCK_TIME_NONE; GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE; } /* push the buffer and forward errors */ GST_DEBUG_OBJECT (enc, "pushing buffer with %d bytes", GST_BUFFER_SIZE (buffer)); *flow = gst_pad_push (pad, buffer); if (*flow != GST_FLOW_OK) { GST_WARNING_OBJECT (enc, "flow on %s:%s = %s", GST_DEBUG_PAD_NAME (pad), gst_flow_get_name (*flow)); return FALSE; } return TRUE; }
bool mdk_dict::load_ifo(const gchar *file) { gchar *buffer; if (!g_file_get_contents(file, &buffer, NULL, NULL)) return false; #define DICT_MAGIC_DATA "StarDict's dict ifo file\nversion=" if (!g_str_has_prefix(buffer, DICT_MAGIC_DATA)) { g_free(buffer); return false; } bool is_dict_300 = false; gchar *p1; p1 = buffer + sizeof(DICT_MAGIC_DATA) -1; #define DICT_VERSION_242 "2.4.2\n" #define DICT_VERSION_300 "3.0.0\n" if (g_str_has_prefix(p1, DICT_VERSION_242)) { p1 += sizeof(DICT_VERSION_242) -2; } else if (g_str_has_prefix(p1, DICT_VERSION_300)) { p1 += sizeof(DICT_VERSION_300) -2; is_dict_300 = true; } else { g_print("Load %s failed: Unknown version.\n", file); g_free(buffer); return false; } gchar *p2, *p3; p2 = strstr(p1,"\nwordcount="); if (!p2) { g_free(buffer); return false; } p3 = strchr(p2 + sizeof("\nwordcount=")-1,'\n'); gchar *tmpstr = (gchar *)g_memdup(p2 + sizeof("\nwordcount=") - 1, p3 - (p2+sizeof("\nwordcount=") - 1) + 1); tmpstr[p3 - (p2 + sizeof("\nwordcount=") - 1)] = '\0'; wordcount = atol(tmpstr); g_free(tmpstr); p2 = strstr(p1,"\nsynwordcount="); if (p2) { p3 = strchr(p2 + sizeof("\nsynwordcount=") - 1, '\n'); gchar *tmpstr = (gchar *)g_memdup(p2 + sizeof("\nsynwordcount=") - 1, p3 - (p2 + sizeof("\nsynwordcount=") - 1) + 1); tmpstr[p3-(p2+sizeof("\nsynwordcount=")-1)] = '\0'; synwordcount = atol(tmpstr); g_free(tmpstr); } else { synwordcount = 0; } p2 = strstr(p1,"\nidxfilesize="); if (!p2) { g_free(buffer); return false; } p3 = strchr(p2+ sizeof("\nidxfilesize=")-1,'\n'); tmpstr = (gchar *)g_memdup(p2 + sizeof("\nidxfilesize=")-1, p3 - (p2 + sizeof("\nidxfilesize=")-1)+1); tmpstr[p3-(p2+sizeof("\nidxfilesize=")-1)] = '\0'; index_file_size = atol(tmpstr); g_free(tmpstr); p2 = strstr(p1,"\ndicttype="); if (p2) { p2+=sizeof("\ndicttype=")-1; p3 = strchr(p2, '\n'); dicttype.assign(p2, p3-p2); } p2 = strstr(p1,"\nbookname="); if (!p2) { g_free(buffer); return false; } p2 = p2 + sizeof("\nbookname=") -1; p3 = strchr(p2, '\n'); bookname.assign(p2, p3-p2); p2 = strstr(p1,"\nauthor="); if (p2) { p2 = p2 + sizeof("\nauthor=") -1; p3 = strchr(p2, '\n'); author.assign(p2, p3-p2); } p2 = strstr(p1,"\nemail="); if (p2) { p2 = p2 + sizeof("\nemail=") -1; p3 = strchr(p2, '\n'); email.assign(p2, p3-p2); } p2 = strstr(p1,"\nwebsite="); if (p2) { p2 = p2 + sizeof("\nwebsite=") -1; p3 = strchr(p2, '\n'); website.assign(p2, p3-p2); } p2 = strstr(p1,"\ndate="); if (p2) { p2 = p2 + sizeof("\ndate=") -1; p3 = strchr(p2, '\n'); date.assign(p2, p3-p2); } p2 = strstr(p1,"\ndescription="); if (p2) { p2 = p2 + sizeof("\ndescription=")-1; p3 = strchr(p2, '\n'); parse_description(p2, p3 - p2, description); } p2 = strstr(p1,"\nsametypesequence="); if (p2) { p2 += sizeof("\nsametypesequence=") - 1; p3 = strchr(p2, '\n'); sametypesequence.assign(p2, p3 - p2); } g_free(buffer); if (wordcount == 0) return false; return true; }
/** * snmp_bc_discover_sensors: * @handler: Pointer to handler's data. * @sensor_array: Pointer to resource's static sensor data array. * @parent_res_event: Pointer to resource's event structure. * * Discovers resource's available sensors and their events. * * Return values: * Adds sensor RDRs to internal Infra-structure queues - normal case * SA_ERR_HPI_OUT_OF_SPACE - Cannot allocate space for internal memory **/ SaErrorT snmp_bc_discover_sensors(struct oh_handler_state *handle, struct snmp_bc_sensor *sensor_array, struct oh_event *res_oh_event) { int i; SaErrorT err; SaHpiBoolT valid_sensor; struct oh_event *e; struct snmp_bc_hnd *custom_handle = (struct snmp_bc_hnd *)handle->data; struct SensorInfo *sensor_info_ptr; for (i=0; sensor_array[i].index != 0; i++) { e = (struct oh_event *)g_malloc0(sizeof(struct oh_event)); if (e == NULL) { dbg("Out of memory."); return(SA_ERR_HPI_OUT_OF_SPACE); } valid_sensor = SAHPI_FALSE; /* Check for event-only sensor */ if (sensor_array[i].sensor.DataFormat.IsSupported == SAHPI_FALSE) { valid_sensor = SAHPI_TRUE; } else { if (sensor_array[i].sensor_info.mib.oid != NULL) { valid_sensor = rdr_exists(custom_handle, &(res_oh_event->u.res_event.entry.ResourceEntity), sensor_array[i].sensor_info.mib.oid, sensor_array[i].sensor_info.mib.not_avail_indicator_num, sensor_array[i].sensor_info.mib.write_only); } else { dbg("Sensor %s cannot be read.", sensor_array[i].comment); g_free(e); return(SA_ERR_HPI_INTERNAL_ERROR); } } /* Add sensor RDR, if sensor is event-only or can be read */ if (valid_sensor) { e->type = OH_ET_RDR; e->did = oh_get_default_domain_id(); e->u.rdr_event.parent = res_oh_event->u.res_event.entry.ResourceId; e->u.rdr_event.rdr.RdrType = SAHPI_SENSOR_RDR; e->u.rdr_event.rdr.Entity = res_oh_event->u.res_event.entry.ResourceEntity; e->u.rdr_event.rdr.RdrTypeUnion.SensorRec = sensor_array[i].sensor; oh_init_textbuffer(&(e->u.rdr_event.rdr.IdString)); oh_append_textbuffer(&(e->u.rdr_event.rdr.IdString), sensor_array[i].comment); trace("Discovered sensor: %s.", e->u.rdr_event.rdr.IdString.Data); sensor_info_ptr = g_memdup(&(sensor_array[i].sensor_info), sizeof(struct SensorInfo)); err = oh_add_rdr(custom_handle->tmpcache, res_oh_event->u.res_event.entry.ResourceId, &(e->u.rdr_event.rdr), sensor_info_ptr, 0); if (err) { dbg("Cannot add RDR. Error=%s.", oh_lookup_error(err)); g_free(e); } else { custom_handle->tmpqueue = g_slist_append(custom_handle->tmpqueue, e); snmp_bc_discover_sensor_events(handle, &(res_oh_event->u.res_event.entry.ResourceEntity), sensor_array[i].sensor.Num, &(sensor_array[i])); } } else { g_free(e); } } return(SA_OK); }
/** * mono_profiler_load: * @desc: arguments to configure the profiler * * Invoke this method to initialize the profiler. This will drive the * loading of the internal ("default") or any external profilers. * * This routine is invoked by Mono's driver, but must be called manually * if you embed Mono into your application. */ void mono_profiler_load (const char *desc) { char *cdesc = NULL; mono_gc_base_init (); if (!desc || (strcmp ("default", desc) == 0)) { desc = "log:report"; } /* we keep command-line compat with the old version here */ if (strncmp (desc, "default:", 8) == 0) { gchar **args, **ptr; GString *str = g_string_new ("log:report"); args = g_strsplit (desc + 8, ",", -1); for (ptr = args; ptr && *ptr; ptr++) { const char *arg = *ptr; if (!strcmp (arg, "time")) g_string_append (str, ",calls"); else if (!strcmp (arg, "alloc")) g_string_append (str, ",alloc"); else if (!strcmp (arg, "stat")) g_string_append (str, ",sample"); else if (!strcmp (arg, "jit")) continue; /* accept and do nothing */ else if (strncmp (arg, "file=", 5) == 0) { g_string_append_printf (str, ",output=%s", arg + 5); } else { fprintf (stderr, "profiler : Unknown argument '%s'.\n", arg); return; } } desc = cdesc = g_string_free (str, FALSE); } { const char* col = strchr (desc, ':'); char* libname; char *mname; gboolean res = FALSE; if (col != NULL) { mname = g_memdup (desc, col - desc + 1); mname [col - desc] = 0; } else { mname = g_strdup (desc); } if (!load_embedded_profiler (desc, mname)) { libname = g_strdup_printf ("mono-profiler-%s", mname); if (mono_config_get_assemblies_dir ()) res = load_profiler_from_directory (mono_assembly_getrootdir (), libname, desc); if (!res) res = load_profiler_from_directory (NULL, libname, desc); if (!res) res = load_profiler_from_mono_instalation (libname, desc); if (!res) g_warning ("The '%s' profiler wasn't found in the main executable nor could it be loaded from '%s'.", mname, libname); g_free (libname); } g_free (mname); } g_free (cdesc); }
/** * snmp_bc_discover_resources: * @hnd: Handler data pointer. * * Discover all the resources, sensors, controls, etc. for this instance * of the plugin. Found entities are compared with what the HPI * Infra-structure thinks is there and any new, deleted, or changed * entities are updated. * * Return values: * Builds/updates internal RPT cache - normal operation. * SA_ERR_HPI_OUT_OF_SPACE - Cannot allocate space for internal memory **/ SaErrorT snmp_bc_discover_resources(void *hnd) { char *root_tuple; SaErrorT err = SA_OK, err1 = SA_OK; SaHpiEntityPathT ep_root; if (!hnd) { dbg("Invalid parameter."); return(SA_ERR_HPI_INVALID_PARAMS); } struct oh_handler_state *handle = (struct oh_handler_state *)hnd; struct snmp_bc_hnd *custom_handle = (struct snmp_bc_hnd *)handle->data; if (!custom_handle) { dbg("Invalid parameter."); return(SA_ERR_HPI_INVALID_PARAMS); } snmp_bc_lock_handler(custom_handle); /* Find root Entity Path */ root_tuple = (char *)g_hash_table_lookup(handle->config, "entity_root"); if (root_tuple == NULL) { dbg("Cannot find configuration parameter."); snmp_bc_unlock_handler(custom_handle); return(SA_ERR_HPI_INTERNAL_ERROR); } err = oh_encode_entitypath(root_tuple, &ep_root); if (err) { dbg("Cannot convert entity path to string. Error=%s.", oh_lookup_error(err)); snmp_bc_unlock_handler(custom_handle); return(SA_ERR_HPI_INTERNAL_ERROR); } /* Allocate space for temporary RPT cache */ custom_handle->tmpcache = (RPTable *)g_malloc0(sizeof(RPTable)); if (custom_handle->tmpcache == NULL) { dbg("Out of memory."); snmp_bc_unlock_handler(custom_handle); return(SA_ERR_HPI_OUT_OF_SPACE); } /* Initialize tmpqueue */ custom_handle->tmpqueue = NULL; /* Individual platform discovery */ if (custom_handle->platform == SNMP_BC_PLATFORM_RSA) { err = snmp_bc_discover_rsa(handle, &ep_root); } else { err = snmp_bc_discover(handle, &ep_root); } if (err) { dbg("Discovery failed. Error=%s.", oh_lookup_error(err)); goto CLEANUP; } /********************************************************************** * Rediscovery: * Get difference between current rptcache and custom_handle->tmpcache. * Delete obsolete items from rptcache and add new items in. **********************************************************************/ GSList *res_new = NULL, *rdr_new = NULL, *res_gone = NULL, *rdr_gone = NULL; GSList *node = NULL; rpt_diff(handle->rptcache, custom_handle->tmpcache, &res_new, &rdr_new, &res_gone, &rdr_gone); trace("%d resources have gone away.", g_slist_length(res_gone)); trace("%d resources are new or have changed", g_slist_length(res_new)); for (node = rdr_gone; node != NULL; node = node->next) { SaHpiRdrT *rdr = (SaHpiRdrT *)node->data; SaHpiRptEntryT *res = oh_get_resource_by_ep(handle->rptcache, &(rdr->Entity)); /* Create remove RDR event and add to event queue */ struct oh_event *e = (struct oh_event *)g_malloc0(sizeof(struct oh_event)); if (e) { e->did = oh_get_default_domain_id(); e->type = OH_ET_RDR_DEL; e->u.rdr_event.parent = res->ResourceId; memcpy(&(e->u.rdr_event.rdr), rdr, sizeof(SaHpiRdrT)); handle->eventq = g_slist_append(handle->eventq, e); } else { dbg("Out of memory."); } /* Remove RDR from plugin's RPT cache */ if (rdr && res) oh_remove_rdr(handle->rptcache, res->ResourceId, rdr->RecordId); else { dbg("No valid resource or rdr at hand. Could not remove rdr."); } } g_slist_free(rdr_gone); for (node = res_gone; node != NULL; node = node->next) { SaHpiRptEntryT *res = (SaHpiRptEntryT *)node->data; /* Create remove resource event and add to event queue */ struct oh_event *e = (struct oh_event *)g_malloc0(sizeof(struct oh_event)); if (e) { e->did = oh_get_default_domain_id(); e->type = OH_ET_RESOURCE_DEL; e->u.res_event.entry.ResourceId = res->ResourceId; handle->eventq = g_slist_append(handle->eventq, e); } else { dbg("Out of memory."); } /* Remove resource from plugin's RPT cache */ if (res) oh_remove_resource(handle->rptcache, res->ResourceId); else dbg("No valid resource at hand. Could not remove resource."); } g_slist_free(res_gone); for (node = res_new; node != NULL; node = node->next) { GSList *tmpnode = NULL; SaHpiRptEntryT *res = (SaHpiRptEntryT *)node->data; if (!res) { dbg("No valid resource at hand. Could not process new resource."); continue; } gpointer data = oh_get_resource_data(custom_handle->tmpcache, res->ResourceId); oh_add_resource(handle->rptcache, res, g_memdup(data, sizeof(struct snmp_rpt)),0); /* Add new/changed resources to the event queue */ for (tmpnode = custom_handle->tmpqueue; tmpnode != NULL; tmpnode = tmpnode->next) { struct oh_event *e = (struct oh_event *)tmpnode->data; if (e->type == OH_ET_RESOURCE && e->u.res_event.entry.ResourceId == res->ResourceId) { handle->eventq = g_slist_append(handle->eventq, e); custom_handle->tmpqueue = g_slist_remove_link(custom_handle->tmpqueue, tmpnode); g_slist_free_1(tmpnode); break; } } } g_slist_free(res_new); for (node = rdr_new; node != NULL; node = node->next) { guint rdr_data_size = 0; GSList *tmpnode = NULL; SaHpiRdrT *rdr = (SaHpiRdrT *)node->data; SaHpiRptEntryT *res = oh_get_resource_by_ep(handle->rptcache, &(rdr->Entity)); if (!res || !rdr) { dbg("No valid resource or rdr at hand. Could not process new rdr."); continue; } gpointer data = oh_get_rdr_data(custom_handle->tmpcache, res->ResourceId, rdr->RecordId); /* Need to figure out the size of the data associated with the rdr */ if (rdr->RdrType == SAHPI_SENSOR_RDR) rdr_data_size = sizeof(struct SensorInfo); else if (rdr->RdrType == SAHPI_CTRL_RDR) rdr_data_size = sizeof(struct ControlInfo); else if (rdr->RdrType == SAHPI_INVENTORY_RDR) rdr_data_size = sizeof(struct InventoryInfo); oh_add_rdr(handle->rptcache, res->ResourceId, rdr, g_memdup(data, rdr_data_size),0); /* Add new/changed rdrs to the event queue */ for (tmpnode = custom_handle->tmpqueue; tmpnode != NULL; tmpnode = tmpnode->next) { struct oh_event *e = (struct oh_event *)tmpnode->data; if (e->type == OH_ET_RDR && oh_cmp_ep(&(e->u.rdr_event.rdr.Entity),&(rdr->Entity)) && e->u.rdr_event.rdr.RecordId == rdr->RecordId) { handle->eventq = g_slist_append(handle->eventq, e); custom_handle->tmpqueue = g_slist_remove_link(custom_handle->tmpqueue, tmpnode); g_slist_free_1(tmpnode); break; } } } g_slist_free(rdr_new); /* Build cache copy of SEL. RID == 1 (2nd parm) is a dummy id */ if (g_list_length(handle->elcache->elentries) != 0) { trace("Discovery called and elcache is not empty. Re-discovery?\n"); err1 = oh_el_clear(handle->elcache); } err1 = snmp_bc_build_selcache(handle, 1); /*err1 = snmp_bc_check_selcache(handle, 1, SAHPI_NEWEST_ENTRY); */ if (err1) { /* --------------------------------------------------------------- */ /* If an error is encounterred during building of snmp_bc elcache, */ /* only log the error. Do not do any recovery because log entries */ /* are still kept in bc mm. We'll pick them up during synch. */ /* --------------------------------------------------------------- */ dbg("snmp_bc_discover, Error %s when building elcache.\n", oh_lookup_error(err1)); } CLEANUP: g_slist_free(custom_handle->tmpqueue); oh_flush_rpt(custom_handle->tmpcache); g_free(custom_handle->tmpcache); snmp_bc_unlock_handler(custom_handle); return(err); }
static gboolean gst_spectra_scope_render (GstBaseAudioVisualizer * bscope, GstBuffer * audio, GstBuffer * video) { GstSpectraScope *scope = GST_SPECTRA_SCOPE (bscope); gint16 *mono_adata; GstFFTS16Complex *fdata = scope->freq_data; guint x, y, off; guint l, h = bscope->height - 1; gfloat fr, fi; guint w = bscope->width; GstMapInfo amap, vmap; guint32 *vdata; gint channels; gst_buffer_map (audio, &amap, GST_MAP_READ); gst_buffer_map (video, &vmap, GST_MAP_WRITE); vdata = (guint32 *) vmap.data; channels = GST_AUDIO_INFO_CHANNELS (&bscope->ainfo); mono_adata = (gint16 *) g_memdup (amap.data, amap.size); if (channels > 1) { guint ch = channels; guint num_samples = amap.size / (ch * sizeof (gint16)); guint i, c, v, s = 0; /* deinterleave and mixdown adata */ for (i = 0; i < num_samples; i++) { v = 0; for (c = 0; c < ch; c++) { v += mono_adata[s++]; } mono_adata[i] = v / ch; } } /* run fft */ gst_fft_s16_window (scope->fft_ctx, mono_adata, GST_FFT_WINDOW_HAMMING); gst_fft_s16_fft (scope->fft_ctx, mono_adata, fdata); g_free (mono_adata); /* draw lines */ for (x = 0; x < bscope->width; x++) { /* figure out the range so that we don't need to clip, * or even better do a log mapping? */ fr = (gfloat) fdata[1 + x].r / 512.0; fi = (gfloat) fdata[1 + x].i / 512.0; y = (guint) (h * fabs (fr * fr + fi * fi)); if (y > h) y = h; y = h - y; off = (y * w) + x; vdata[off] = 0x00FFFFFF; for (l = y + 1; l <= h; l++) { off += w; add_pixel (&vdata[off], 0x007F7F7F); } } gst_buffer_unmap (video, &vmap); gst_buffer_unmap (audio, &amap); return TRUE; }
static void sevencup_connection_process_data(SevenCupConnection *scon) { gssize len; gchar *tmp; len = scon->rx_len; tmp = g_strstr_len(scon->rx_buf, len, "\r\n\r\n"); if (tmp == NULL) { /* This is a corner case that occurs when the connection is * prematurely closed either on the client or the server. * This can either be no data at all or a partial set of * headers. We pass along the data to be good, but don't * do any fancy massaging. In all likelihood the result will * be tossed by the connection callback func anyways */ tmp = g_strndup(scon->rx_buf, len); } else { tmp += 4; len -= g_strstr_len(scon->rx_buf, len, "\r\n\r\n") - scon->rx_buf + 4; tmp = g_memdup(tmp, len + 1); tmp[len] = '\0'; scon->rx_buf[scon->rx_len - len] = '\0'; sevencup_update_cookies(scon->sa, scon->rx_buf); if (strstr(scon->rx_buf, "Content-Encoding: gzip")) { /* we've received compressed gzip data, decompress */ gchar *gunzipped; gunzipped = sevencup_gunzip((const guchar *)tmp, &len); g_free(tmp); tmp = gunzipped; } } g_free(scon->rx_buf); scon->rx_buf = NULL; if (scon->callback != NULL) { if (!len) { purple_debug_error("7cups", "No data in response\n"); } else { JsonParser *parser = json_parser_new(); if (!json_parser_load_from_data(parser, tmp, len, NULL)) { if (scon->error_callback != NULL) { scon->error_callback(scon->sa, tmp, len, scon->user_data); } else { purple_debug_error("7cups", "Error parsing response: %s\n", tmp); } } else { JsonNode *root = json_parser_get_root(parser); JsonObject *jsonobj = json_node_get_object(root); //purple_debug_info("7cups", "Got response: %s\n", tmp); purple_debug_info("7cups", "executing callback for %s\n", scon->url); scon->callback(scon->sa, jsonobj, scon->user_data); } g_object_unref(parser); } } g_free(tmp); }
void purple_initmodule() { struct prpl funcs; GList *prots; GString *help; char *dir; if (B_EV_IO_READ != PURPLE_INPUT_READ || B_EV_IO_WRITE != PURPLE_INPUT_WRITE) { /* FIXME FIXME FIXME FIXME FIXME :-) */ exit(1); } dir = g_strdup_printf("%s/purple", global.conf->configdir); purple_util_set_user_dir(dir); g_free(dir); purple_debug_set_enabled(FALSE); purple_core_set_ui_ops(&bee_core_uiops); purple_eventloop_set_ui_ops(&glib_eventloops); if (!purple_core_init("BitlBee")) { /* Initializing the core failed. Terminate. */ fprintf(stderr, "libpurple initialization failed.\n"); abort(); } if (proxytype != PROXY_NONE) { PurpleProxyInfo *pi = purple_global_proxy_get_info(); switch (proxytype) { case PROXY_SOCKS4: purple_proxy_info_set_type(pi, PURPLE_PROXY_SOCKS4); break; case PROXY_SOCKS5: purple_proxy_info_set_type(pi, PURPLE_PROXY_SOCKS5); break; case PROXY_HTTP: purple_proxy_info_set_type(pi, PURPLE_PROXY_HTTP); break; } purple_proxy_info_set_host(pi, proxyhost); purple_proxy_info_set_port(pi, proxyport); purple_proxy_info_set_username(pi, proxyuser); purple_proxy_info_set_password(pi, proxypass); } purple_set_blist(purple_blist_new()); /* No, really. So far there were ui_ops for everything, but now suddenly one needs to use signals for typing notification stuff. :-( */ purple_signal_connect(purple_conversations_get_handle(), "buddy-typing", &funcs, PURPLE_CALLBACK(prplcb_buddy_typing), NULL); purple_signal_connect(purple_conversations_get_handle(), "buddy-typed", &funcs, PURPLE_CALLBACK(prplcb_buddy_typing), NULL); purple_signal_connect(purple_conversations_get_handle(), "buddy-typing-stopped", &funcs, PURPLE_CALLBACK(prplcb_buddy_typing), NULL); memset(&funcs, 0, sizeof(funcs)); funcs.login = purple_login; funcs.init = purple_init; funcs.logout = purple_logout; funcs.buddy_msg = purple_buddy_msg; funcs.away_states = purple_away_states; funcs.set_away = purple_set_away; funcs.add_buddy = purple_add_buddy; funcs.remove_buddy = purple_remove_buddy; funcs.add_permit = purple_add_permit; funcs.add_deny = purple_add_deny; funcs.rem_permit = purple_rem_permit; funcs.rem_deny = purple_rem_deny; funcs.get_info = purple_get_info; funcs.keepalive = purple_keepalive; funcs.send_typing = purple_send_typing; funcs.handle_cmp = g_strcasecmp; /* TODO(wilmer): Set these only for protocols that support them? */ funcs.chat_msg = purple_chat_msg; funcs.chat_with = purple_chat_with; funcs.chat_invite = purple_chat_invite; funcs.chat_kick = purple_chat_kick; funcs.chat_leave = purple_chat_leave; funcs.chat_join = purple_chat_join; funcs.transfer_request = purple_transfer_request; help = g_string_new("BitlBee libpurple module supports the following IM protocols:\n"); /* Add a protocol entry to BitlBee's structures for every protocol supported by this libpurple instance. */ for (prots = purple_plugins_get_protocols(); prots; prots = prots->next) { PurplePlugin *prot = prots->data; struct prpl *ret; /* If we already have this one (as a native module), don't add a libpurple duplicate. */ if (find_protocol(prot->info->id)) { continue; } ret = g_memdup(&funcs, sizeof(funcs)); ret->name = ret->data = prot->info->id; if (strncmp(ret->name, "prpl-", 5) == 0) { ret->name += 5; } register_protocol(ret); g_string_append_printf(help, "\n* %s (%s)", ret->name, prot->info->name); /* libpurple doesn't define a protocol called OSCAR, but we need it to be compatible with normal BitlBee. */ if (g_strcasecmp(prot->info->id, "prpl-aim") == 0) { ret = g_memdup(&funcs, sizeof(funcs)); ret->name = "oscar"; ret->data = prot->info->id; register_protocol(ret); } } g_string_append(help, "\n\nFor used protocols, more information about available " "settings can be found using \x02help purple <protocol name>\x02 " "(create an account using that protocol first!)"); /* Add a simple dynamically-generated help item listing all the supported protocols. */ help_add_mem(&global.help, "purple", help->str); g_string_free(help, TRUE); }
void send_to(gpointer data, gpointer user_data){ struct _GConn* conn = (struct _GConn*) data; gchar* buf = (gchar*) user_data; gchar* buf2 = g_memdup (buf, (guint) strlen(buf)+1); gnet_conn_write( conn, buf2, (gint) strlen(buf2)); }
void RtpAudioStream::addRtpPacket(const struct _packet_info *pinfo, const _rtp_info *rtp_info) { if (!rtp_info) return; // Combination of gtk/rtp_player.c:decode_rtp_stream + decode_rtp_packet // XXX This is more messy than it should be. SAMPLE *decode_buff = NULL; SAMPLE *resample_buff = NULL; spx_uint32_t cur_in_rate, visual_out_rate; char *write_buff; qint64 write_bytes; unsigned channels; unsigned sample_rate; rtp_packet_t rtp_packet; stop_rel_time_ = nstime_to_sec(&pinfo->rel_ts); ws_codec_resampler_get_rate(visual_resampler_, &cur_in_rate, &visual_out_rate); QString payload_name; if (rtp_info->info_payload_type_str) { payload_name = rtp_info->info_payload_type_str; } else { payload_name = try_val_to_str_ext(rtp_info->info_payload_type, &rtp_payload_type_short_vals_ext); } if (!payload_name.isEmpty()) { payload_names_ << payload_name; } // First, decode the payload. rtp_packet.info = (_rtp_info *) g_memdup(rtp_info, sizeof(struct _rtp_info)); rtp_packet.arrive_offset = start_rel_time_; if (rtp_info->info_all_data_present && (rtp_info->info_payload_len != 0)) { rtp_packet.payload_data = (guint8 *)g_malloc(rtp_info->info_payload_len); memcpy(rtp_packet.payload_data, rtp_info->info_data + rtp_info->info_payload_offset, rtp_info->info_payload_len); } else { rtp_packet.payload_data = NULL; } //size_t decoded_bytes = decode_rtp_packet(&rtp_packet, &decode_buff, decoders_hash_, &channels, &sample_rate); write_buff = (char *) decode_buff; write_bytes = rtp_info->info_payload_len * sample_bytes_; if (tempfile_->pos() == 0) { // First packet. Let it determine our sample rate. audio_out_rate_ = sample_rate; last_sequence_ = rtp_info->info_seq_num - 1; // Prepend silence to match our sibling streams. int prepend_samples = (start_rel_time_ - global_start_rel_time_) * audio_out_rate_; if (prepend_samples > 0) { int prepend_bytes = prepend_samples * sample_bytes_; char *prepend_buff = (char *) g_malloc(prepend_bytes); SAMPLE silence = 0; memccpy(prepend_buff, &silence, prepend_samples, sample_bytes_); tempfile_->write(prepend_buff, prepend_bytes); } } else if (audio_out_rate_ != sample_rate) { // Resample the audio to match our previous output rate. if (!audio_resampler_) { audio_resampler_ = ws_codec_resampler_init(1, sample_rate, audio_out_rate_, 10, NULL); ws_codec_resampler_skip_zeros(audio_resampler_); // RTP_STREAM_DEBUG("Started resampling from %u to (out) %u Hz.", sample_rate, audio_out_rate_); } else { spx_uint32_t audio_out_rate; ws_codec_resampler_get_rate(audio_resampler_, &cur_in_rate, &audio_out_rate); // Adjust rates if needed. if (sample_rate != cur_in_rate) { ws_codec_resampler_set_rate(audio_resampler_, sample_rate, audio_out_rate); ws_codec_resampler_set_rate(visual_resampler_, sample_rate, visual_out_rate); // RTP_STREAM_DEBUG("Changed input rate from %u to %u Hz. Out is %u.", cur_in_rate, sample_rate, audio_out_rate_); } } spx_uint32_t in_len = (spx_uint32_t)rtp_info->info_payload_len; spx_uint32_t out_len = (audio_out_rate_ * (spx_uint32_t)rtp_info->info_payload_len / sample_rate) + (audio_out_rate_ % sample_rate != 0); resample_buff = (SAMPLE *) g_malloc(out_len * sample_bytes_); ws_codec_resampler_process_int(audio_resampler_, 0, decode_buff, &in_len, resample_buff, &out_len); write_buff = (char *) decode_buff; write_bytes = out_len * sample_bytes_; } if (rtp_info->info_seq_num != last_sequence_+1) { out_of_seq_timestamps_.append(stop_rel_time_); // XXX Add silence to tempfile_ and visual_samples_ } last_sequence_ = rtp_info->info_seq_num; // Write the decoded, possibly-resampled audio to our temp file. tempfile_->write(write_buff, write_bytes); // Collect our visual samples. spx_uint32_t in_len = (spx_uint32_t)rtp_info->info_payload_len; spx_uint32_t out_len = (visual_out_rate * in_len / sample_rate) + (visual_out_rate % sample_rate != 0); resample_buff = (SAMPLE *) g_realloc(resample_buff, out_len * sizeof(SAMPLE)); ws_codec_resampler_process_int(visual_resampler_, 0, decode_buff, &in_len, resample_buff, &out_len); for (unsigned i = 0; i < out_len; i++) { packet_timestamps_[stop_rel_time_ + (double) i / visual_out_rate] = pinfo->fd->num; if (qAbs(resample_buff[i]) > max_sample_val_) max_sample_val_ = qAbs(resample_buff[i]); visual_samples_.append(resample_buff[i]); } // Finally, write the resampled audio to our temp file and clean up. g_free(rtp_packet.payload_data); g_free(decode_buff); g_free(resample_buff); }
static void hid_sdp_search_cb(sdp_list_t *recs, int err, gpointer data) { struct hid_device *dev = data; sdp_list_t *list; GError *gerr = NULL; DBG(""); if (err < 0) { error("hidhost: Unable to get SDP record: %s", strerror(-err)); goto fail; } if (!recs || !recs->data) { error("hidhost: No SDP records found"); goto fail; } for (list = recs; list != NULL; list = list->next) { sdp_record_t *rec = list->data; sdp_data_t *data; data = sdp_data_get(rec, SDP_ATTR_HID_COUNTRY_CODE); if (data) dev->country = data->val.uint8; data = sdp_data_get(rec, SDP_ATTR_HID_DEVICE_SUBCLASS); if (data) dev->subclass = data->val.uint8; data = sdp_data_get(rec, SDP_ATTR_HID_BOOT_DEVICE); if (data) dev->boot_dev = data->val.uint8; data = sdp_data_get(rec, SDP_ATTR_HID_DESCRIPTOR_LIST); if (data) { if (!SDP_IS_SEQ(data->dtd)) goto fail; /* First HIDDescriptor */ data = data->val.dataseq; if (!SDP_IS_SEQ(data->dtd)) goto fail; /* ClassDescriptorType */ data = data->val.dataseq; if (data->dtd != SDP_UINT8) goto fail; /* ClassDescriptorData */ data = data->next; if (!data || !SDP_IS_TEXT_STR(data->dtd)) goto fail; dev->rd_size = data->unitSize; dev->rd_data = g_memdup(data->val.str, data->unitSize); } } if (dev->ctrl_io) { if (uhid_create(dev) < 0) goto fail; return; } dev->ctrl_io = bt_io_connect(control_connect_cb, dev, NULL, &gerr, BT_IO_OPT_SOURCE_BDADDR, &adapter_addr, BT_IO_OPT_DEST_BDADDR, &dev->dst, BT_IO_OPT_PSM, L2CAP_PSM_HIDP_CTRL, BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_LOW, BT_IO_OPT_INVALID); if (gerr) { error("hidhost: Failed to connect control channel (%s)", gerr->message); g_error_free(gerr); goto fail; } return; fail: bt_hid_notify_state(dev, HAL_HIDHOST_STATE_DISCONNECTED); hid_device_remove(dev); }
static void* macro_copy(void* dest, const void* orig, size_t len _U_) { dfilter_macro_t* d = (dfilter_macro_t*)dest; const dfilter_macro_t* m = (const dfilter_macro_t*)orig; DUMP_MACRO(m); d->name = g_strdup(m->name); d->text = g_strdup(m->text); d->usable = m->usable; if (m->parts) { guint nparts = 0; /* * Copy the contents of m->priv (a "cooked" version * of m->text) into d->priv. * * First we clone m->text into d->priv, this gets * us a NUL terminated string of the proper length. * * Then we loop copying bytes from m->priv into * d-priv. Since m->priv contains internal ACSII NULs * we use the length of m->text to stop the copy. */ d->priv = g_strdup(m->text); { const gchar* oldText = m->text; const gchar* oldPriv = (const gchar*)m->priv; gchar* newPriv = (gchar*)d->priv; while(oldText && *oldText) { *(newPriv++) = *(oldPriv++); oldText++; } } /* * The contents of the m->parts array contains pointers * into various sections of m->priv. Since it's * an argv style array of ponters, this array is * actually one larger than the number of parts * to hold the final NULL terminator. * * The following copy clones the original m->parts * array into d->parts but then fixes-up the pointers * so that they point into the appropriate sections * of the d->priv. */ do nparts++; while (m->parts[nparts]); d->parts = (gchar **)g_memdup(m->parts,(nparts+1)*(guint)sizeof(void*)); nparts = 0; while(m->parts[nparts]) { if(nparts) { d->parts[nparts] = d->parts[nparts - 1] + (m->parts[nparts] - m->parts[nparts - 1]); } else { d->parts[nparts] = (gchar *)d->priv; } nparts++; } /* * Clone the contents of m->args_pos into d->args_pos. */ d->args_pos = (int *)g_memdup(m->args_pos,(--nparts)*(guint)sizeof(int)); } DUMP_MACRO(d); return d; }
wtap_open_return_val k12_open(wtap *wth, int *err, gchar **err_info) { k12_src_desc_t* rec; guint8 header_buffer[K12_FILE_HDR_LEN]; guint8* read_buffer; guint32 type; long offset; long len; guint port_type; guint32 rec_len; guint32 hwpart_len; guint32 name_len; guint32 stack_len; guint i; k12_t* file_data; #ifdef DEBUG_K12 gchar* env_level = getenv("K12_DEBUG_LEVEL"); env_file = getenv("K12_DEBUG_FILENAME"); if ( env_file ) { dbg_out = ws_fopen(env_file,"w"); if (dbg_out == NULL) { dbg_out = stderr; K12_DBG(1,("unable to open K12 DEBUG FILENAME for writing! Logging to standard error")); } } else dbg_out = stderr; if ( env_level ) debug_level = (unsigned int)strtoul(env_level,NULL,10); K12_DBG(1,("k12_open: ENTER debug_level=%u",debug_level)); #endif if ( !wtap_read_bytes(wth->fh,header_buffer,K12_FILE_HDR_LEN,err,err_info) ) { K12_DBG(1,("k12_open: FILE HEADER TOO SHORT OR READ ERROR")); if (*err != WTAP_ERR_SHORT_READ) { return WTAP_OPEN_ERROR; } return WTAP_OPEN_NOT_MINE; } if ( memcmp(header_buffer,k12_file_magic,8) != 0 ) { K12_DBG(1,("k12_open: BAD MAGIC")); return WTAP_OPEN_NOT_MINE; } offset = K12_FILE_HDR_LEN; file_data = new_k12_file_data(); file_data->file_len = pntoh32( header_buffer + 0x8); if (memiszero(header_buffer + 0x10, K12_FILE_HDR_LEN - 0x10)) { /* * The rest of the file header is all zeroes. That means * this is a file written by the old Wireshark code, and * a count of records in the file is at an offset of 0x0C. */ file_data->num_of_records = pntoh32( header_buffer + 0x0C ); } else { /* * There's at least one non-zero byte in the rest of the * header. The value 8192 is at 0xC (page size?), and * what appears to be the number of records in the file * is at an offset of 0x24 and at an offset of 0x2c. * * If the two values are not the same, we fail; if that's * the case, we need to see the file to figure out which * of those two values, if any, is the count. */ file_data->num_of_records = pntoh32( header_buffer + K12_FILE_HDR_RECORD_COUNT_1 ); if ( file_data->num_of_records != pntoh32( header_buffer + K12_FILE_HDR_RECORD_COUNT_2 ) ) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("k12: two different record counts, %u at 0x%02x and %u at 0x%02x", file_data->num_of_records, K12_FILE_HDR_RECORD_COUNT_1, pntoh32( header_buffer + K12_FILE_HDR_RECORD_COUNT_2 ), K12_FILE_HDR_RECORD_COUNT_2 ); return WTAP_OPEN_ERROR; } } K12_DBG(5,("k12_open: FILE_HEADER OK: offset=%x file_len=%i records=%i", offset, file_data->file_len, file_data->num_of_records )); do { if ( file_data->num_of_records == 0 ) { *err = WTAP_ERR_SHORT_READ; destroy_k12_file_data(file_data); return WTAP_OPEN_ERROR; } len = get_record(file_data, wth->fh, offset, FALSE, err, err_info); if ( len < 0 ) { K12_DBG(1,("k12_open: BAD HEADER RECORD",len)); destroy_k12_file_data(file_data); return WTAP_OPEN_ERROR; } if ( len == 0 ) { K12_DBG(1,("k12_open: BAD HEADER RECORD",len)); *err = WTAP_ERR_SHORT_READ; destroy_k12_file_data(file_data); return WTAP_OPEN_ERROR; } read_buffer = file_data->seq_read_buff; rec_len = pntoh32( read_buffer + K12_RECORD_LEN ); if (rec_len < K12_RECORD_TYPE + 4) { /* Record isn't long enough to have a type field */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("k12_open: record length %u < %u", rec_len, K12_RECORD_TYPE + 4); return WTAP_OPEN_ERROR; } type = pntoh32( read_buffer + K12_RECORD_TYPE ); if ( (type & K12_MASK_PACKET) == K12_REC_PACKET || (type & K12_MASK_PACKET) == K12_REC_D0020) { /* * we are at the first packet record, rewind and leave. */ if (file_seek(wth->fh, offset, SEEK_SET, err) == -1) { destroy_k12_file_data(file_data); return WTAP_OPEN_ERROR; } K12_DBG(5,("k12_open: FIRST PACKET offset=%x",offset)); break; } switch (type) { case K12_REC_SRCDSC: case K12_REC_SRCDSC2: rec = g_new0(k12_src_desc_t,1); if (rec_len < K12_SRCDESC_HWPART) { /* * Record isn't long enough to have the fixed-length portion * of the source descriptor field. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("k12_open: source descriptor record length %u < %u", rec_len, K12_SRCDESC_HWPART); destroy_k12_file_data(file_data); g_free(rec); return WTAP_OPEN_ERROR; } port_type = read_buffer[K12_SRCDESC_PORT_TYPE]; hwpart_len = pntoh16( read_buffer + K12_SRCDESC_HWPARTLEN ); name_len = pntoh16( read_buffer + K12_SRCDESC_NAMELEN ); stack_len = pntoh16( read_buffer + K12_SRCDESC_STACKLEN ); rec->input = pntoh32( read_buffer + K12_RECORD_SRC_ID ); K12_DBG(5,("k12_open: INTERFACE RECORD offset=%x interface=%x",offset,rec->input)); if (name_len == 0) { K12_DBG(5,("k12_open: failed (name_len == 0 in source description")); destroy_k12_file_data(file_data); g_free(rec); return WTAP_OPEN_NOT_MINE; } if (stack_len == 0) { K12_DBG(5,("k12_open: failed (stack_len == 0 in source description")); destroy_k12_file_data(file_data); g_free(rec); return WTAP_OPEN_NOT_MINE; } if (rec_len < K12_SRCDESC_HWPART + hwpart_len + name_len + stack_len) { /* * Record isn't long enough to have the full source descriptor * field, including the variable-length parts. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("k12_open: source descriptor record length %u < %u (%u + %u + %u + %u)", rec_len, K12_SRCDESC_HWPART + hwpart_len + name_len + stack_len, K12_SRCDESC_HWPART, hwpart_len, name_len, stack_len); destroy_k12_file_data(file_data); g_free(rec); return WTAP_OPEN_ERROR; } if (hwpart_len) { if (hwpart_len < 4) { /* Hardware part isn't long enough to have a type field */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("k12_open: source descriptor hardware part length %u < 4", hwpart_len); destroy_k12_file_data(file_data); g_free(rec); return WTAP_OPEN_ERROR; } switch(( rec->input_type = pntoh32( read_buffer + K12_SRCDESC_HWPART + K12_SRCDESC_HWPARTTYPE ) )) { case K12_PORT_DS0S: /* This appears to be variable-length */ rec->input_info.ds0mask = 0x00000000; if (hwpart_len > K12_SRCDESC_DS0_MASK) { for (i = 0; i < hwpart_len - K12_SRCDESC_DS0_MASK; i++) { rec->input_info.ds0mask |= ( *(read_buffer + K12_SRCDESC_HWPART + K12_SRCDESC_DS0_MASK + i) == 0xff ) ? 1U<<(31-i) : 0x0; } } break; case K12_PORT_ATMPVC: if (hwpart_len < K12_SRCDESC_ATM_VCI + 2) { /* Hardware part isn't long enough to have ATM information */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("k12_open: source descriptor hardware part length %u < %u", hwpart_len, K12_SRCDESC_ATM_VCI + 2); destroy_k12_file_data(file_data); g_free(rec); return WTAP_OPEN_ERROR; } rec->input_info.atm.vp = pntoh16( read_buffer + K12_SRCDESC_HWPART + K12_SRCDESC_ATM_VPI ); rec->input_info.atm.vc = pntoh16( read_buffer + K12_SRCDESC_HWPART + K12_SRCDESC_ATM_VCI ); break; default: break; } } else { /* Record viewer generated files don't have this information */ if (port_type >= 0x14 && port_type <= 0x17) { /* For ATM2_E1DS1, ATM2_E3DS3, ATM2_STM1EL and ATM2_STM1OP */ rec->input_type = K12_PORT_ATMPVC; rec->input_info.atm.vp = 0; rec->input_info.atm.vc = 0; } } if (read_buffer[K12_SRCDESC_HWPART + hwpart_len + name_len - 1] != '\0') { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("k12_open: source descriptor record contains non-null-terminated link-layer name"); destroy_k12_file_data(file_data); g_free(rec); return WTAP_OPEN_ERROR; } if (read_buffer[K12_SRCDESC_HWPART + hwpart_len + name_len + stack_len - 1] != '\0') { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("k12_open: source descriptor record contains non-null-terminated stack path"); destroy_k12_file_data(file_data); g_free(rec); return WTAP_OPEN_ERROR; } rec->input_name = (gchar *)g_memdup(read_buffer + K12_SRCDESC_HWPART + hwpart_len, name_len); rec->stack_file = (gchar *)g_memdup(read_buffer + K12_SRCDESC_HWPART + hwpart_len + name_len, stack_len); ascii_strdown_inplace (rec->stack_file); g_hash_table_insert(file_data->src_by_id,GUINT_TO_POINTER(rec->input),rec); g_hash_table_insert(file_data->src_by_name,rec->stack_file,rec); break; case K12_REC_STK_FILE: K12_DBG(1,("k12_open: K12_REC_STK_FILE")); K12_DBG(1,("Field 1: 0x%08x",pntoh32( read_buffer + 0x08 ))); K12_DBG(1,("Field 2: 0x%08x",pntoh32( read_buffer + 0x0c ))); K12_ASCII_DUMP(1, read_buffer, rec_len, 16); break; default: K12_DBG(1,("k12_open: RECORD TYPE 0x%08x",type)); break; } offset += len; file_data->num_of_records--; } while(1); wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_K12; wth->file_encap = WTAP_ENCAP_K12; wth->snapshot_length = 0; wth->subtype_read = k12_read; wth->subtype_seek_read = k12_seek_read; wth->subtype_close = k12_close; wth->priv = (void *)file_data; wth->file_tsprec = WTAP_TSPREC_NSEC; return WTAP_OPEN_MINE; }
static gboolean rosenbrock_iter (GnmNlsolve *nl) { GnmSolver *sol = nl->parent; const int n = nl->vars->len; int i, j; const gnm_float alpha = 3; const gnm_float beta = 0.5; gboolean any_at_all = FALSE; gnm_float *d, **A, *x, *dx, *t; char *state; int dones = 0; gnm_float ykm1 = nl->yk, *xkm1; gnm_float eps = gnm_pow2 (-16); int safety = 0; if (nl->tentative) { nl->tentative--; if (nl->tentative == 0) { if (nl->debug) g_printerr ("Tentative move rejected\n"); rosenbrock_tentative_end (nl, FALSE); } } if (nl->k % 20 == 0) { for (i = 0; i < n; i++) for (j = 0; j < n; j++) nl->xi[i][j] = (i == j); } A = g_new (gnm_float *, n); for (i = 0; i < n; i++) A[i] = g_new (gnm_float, n); dx = g_new (gnm_float, n); for (i = 0; i < n; i++) dx[i] = 0; x = g_new (gnm_float, n); t = g_new (gnm_float, n); d = g_new (gnm_float, n); for (i = 0; i < n; i++) { d[i] = (nl->xk[i] == 0) ? eps : gnm_abs (nl->xk[i]) * eps; } xkm1 = g_memdup (nl->xk, n * sizeof (gnm_float)); state = g_new0 (char, n); while (dones < n) { /* * A safety that shouldn't get hit, but might if the function * being optimized is non-deterministic. */ if (safety++ > n * GNM_MANT_DIG) break; for (i = 0; i < n; i++) { gnm_float y; if (state[i] == 2) continue; /* x = xk + (d[i] * xi[i]) */ for (j = 0; j < n; j++) x[j] = nl->xk[j] + d[i] * nl->xi[i][j]; set_vector (nl, x); y = get_value (nl); if (y <= nl->yk && gnm_solver_check_constraints (sol)) { if (y < nl->yk) { nl->yk = y; memcpy (nl->xk, x, n * sizeof (gnm_float)); dx[i] += d[i]; any_at_all = TRUE; } switch (state[i]) { case 0: state[i] = 1; /* Fall through */ case 1: d[i] *= alpha; break; default: case 2: break; } } else { switch (state[i]) { case 1: state[i] = 2; dones++; /* Fall through */ case 0: d[i] *= -beta; break; default: case 2: /* No sign change. */ d[i] *= 0.5; break; } } } } if (any_at_all) { gnm_float div, sum; for (j = n - 1; j >= 0; j--) for (i = 0; i < n; i++) A[j][i] = (j == n - 1 ? 0 : A[j + 1][i]) + dx[j] * nl->xi[j][i]; sum = 0; for (i = n - 1; i >= 0; i--) { sum += dx[i] * dx[i]; t[i] = sum; } for (i = n - 1; i > 0; i--) { div = gnm_sqrt (t[i - 1] * t[i]); if (div != 0) for (j = 0; j < n; j++) { nl->xi[i][j] = (dx[i - 1] * A[i][j] - nl->xi[i - 1][j] * t[i]) / div; g_assert (gnm_finite (nl->xi[i][j])); } } gnm_range_hypot (dx, n, &div); if (div != 0) { for (i = 0; i < n; i++) { nl->xi[0][i] = A[0][i] / div; if (!gnm_finite (nl->xi[0][i])) { g_printerr ("%g %g %g\n", div, A[0][i], nl->xi[0][i]); g_assert (gnm_finite (nl->xi[0][i])); } } } /* ---------------------------------------- */ if (!nl->tentative) { set_vector (nl, nl->xk); gnm_nlsolve_set_solution (nl); } if (nl->tentative) { if (nl->yk < nl->tentative_yk) { if (nl->debug) g_printerr ("Tentative move accepted!\n"); rosenbrock_tentative_end (nl, TRUE); } } else if (gnm_abs (nl->yk - ykm1) > gnm_abs (ykm1) * 0.01) { /* A big step. */ nl->smallsteps = 0; } else { nl->smallsteps++; } if (!nl->tentative && nl->smallsteps > 50) { gnm_float yk = nl->yk; nl->tentative = 10; nl->tentative_xk = g_memdup (nl->xk, n * sizeof (gnm_float)); nl->tentative_yk = yk; for (i = 0; i < 4; i++) { gnm_float ymax = yk + gnm_abs (yk) * (0.10 / (i + 1)); if (i > 0) ymax = MIN (ymax, nl->yk); if (!newton_improve (nl, nl->xk, &nl->yk, ymax)) break; } if (nl->debug) print_vector ("Tentative move to", nl->xk, n); } } g_free (x); g_free (xkm1); g_free (dx); g_free (t); g_free (d); free_matrix (A, n); g_free (state); return any_at_all; }
static void read_cb(gpointer data, gint source, GaimInputCondition cond) { MsnServConn *servconn; MsnSession *session; char buf[MSN_BUF_LEN]; char *cur, *end, *old_rx_buf; int len, cur_len; servconn = data; session = servconn->session; len = read(servconn->fd, buf, sizeof(buf) - 1); if (len < 0 && errno == EAGAIN) return; else if (len <= 0) { gaim_debug_error("msn", "servconn read error, len: %d error: %s\n", len, strerror(errno)); msn_servconn_got_error(servconn, MSN_SERVCONN_ERROR_READ); return; } buf[len] = '\0'; servconn->rx_buf = g_realloc(servconn->rx_buf, len + servconn->rx_len + 1); memcpy(servconn->rx_buf + servconn->rx_len, buf, len + 1); servconn->rx_len += len; end = old_rx_buf = servconn->rx_buf; servconn->processing = TRUE; do { cur = end; if (servconn->payload_len) { if (servconn->payload_len > servconn->rx_len) /* The payload is still not complete. */ break; cur_len = servconn->payload_len; end += cur_len; } else { end = strstr(cur, "\r\n"); if (end == NULL) /* The command is still not complete. */ break; *end = '\0'; end += 2; cur_len = end - cur; } servconn->rx_len -= cur_len; if (servconn->payload_len) { msn_cmdproc_process_payload(servconn->cmdproc, cur, cur_len); servconn->payload_len = 0; } else { msn_cmdproc_process_cmd_text(servconn->cmdproc, cur); } } while (servconn->connected && !servconn->wasted && servconn->rx_len > 0); if (servconn->connected && !servconn->wasted) { if (servconn->rx_len > 0) servconn->rx_buf = g_memdup(cur, servconn->rx_len); else servconn->rx_buf = NULL; } servconn->processing = FALSE; if (servconn->wasted) msn_servconn_destroy(servconn); g_free(old_rx_buf); }