コード例 #1
0
    for (i = s->header.header_size; i < check->nclusters; i++) {
        if (!qed_test_bit(check->used_clusters, i)) {
            check->result->leaks++;
        }
    }
}

int qed_check(BDRVQEDState *s, BdrvCheckResult *result, bool fix)
{
    QEDCheck check = {
        .s = s,
        .result = result,
        .nclusters = qed_bytes_to_clusters(s, s->file_size),
        .request = { .l2_table = NULL },
        .fix = fix,
    };
    int ret;

    check.used_clusters = g_malloc0(((check.nclusters + 31) / 32) *
                                       sizeof(check.used_clusters[0]));

    ret = qed_check_l1_table(&check, s->l1_table);
    if (ret == 0) {
        /* Only check for leaks if entire image was scanned successfully */
        qed_check_for_leaks(&check);
    }

    g_free(check.used_clusters);
    return ret;
}
コード例 #2
0
ファイル: stats_tree.c プロジェクト: ARK1988/wireshark
/* creates a stat_tree node
*    name: the name of the stats_tree node
*    parent_name: the name of the ALREADY REGISTERED parent
*    with_hash: whether or not it should keep a hash with its children names
*    as_named_node: whether or not it has to be registered in the root namespace
*/
static stat_node*
new_stat_node(stats_tree *st, const gchar *name, int parent_id,
          gboolean with_hash, gboolean as_parent_node)
{

    stat_node *node = (stat_node *)g_malloc (sizeof(stat_node));
    stat_node *last_chld = NULL;

    node->counter = 0;
    node->total = 0;
    node->minvalue = G_MAXINT;
    node->maxvalue = G_MININT;
    node->st_flags = parent_id?0:ST_FLG_ROOTCHILD;

    node->bh = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
    node->bt = node->bh;
    node->bcount = 0;
    node->max_burst = 0;
    node->burst_time = -1.0;

    node->name = g_strdup(name);
    node->children = NULL;
    node->next = NULL;
    node->st = (stats_tree*) st;
    node->hash = with_hash ? g_hash_table_new(g_str_hash,g_str_equal) : NULL;
    node->parent = NULL;
    node->rng  =  NULL;

    if (as_parent_node) {
        g_hash_table_insert(st->names,
                            node->name,
                            node);

        g_ptr_array_add(st->parents,node);

        node->id = st->parents->len - 1;
    } else {
        node->id = -1;
    }

    if (parent_id >= 0 && parent_id < (int) st->parents->len ) {
        node->parent = (stat_node *)g_ptr_array_index(st->parents,parent_id);
    } else {
        /* ??? should we set the parent to be root ??? */
        g_assert_not_reached();
    }

    if (node->parent->children) {
        /* insert as last child */

        for (last_chld = node->parent->children;
             last_chld->next;
             last_chld = last_chld->next ) ;

        last_chld->next = node;

    } else {
        /* insert as first child */
        node->parent->children = node;
    }

    if(node->parent->hash) {
        g_hash_table_insert(node->parent->hash,node->name,node);
    }

    if (st->cfg->setup_node_pr) {
        st->cfg->setup_node_pr(node);
    } else {
        node->pr = NULL;
    }

    return node;
}
コード例 #3
0
ファイル: colorout.c プロジェクト: rpoisel/darktable
void gui_init(struct dt_iop_module_t *self)
{
  self->gui_data = malloc(sizeof(dt_iop_colorout_gui_data_t));
  memset(self->gui_data,0,sizeof(dt_iop_colorout_gui_data_t));
  dt_iop_colorout_gui_data_t *g = (dt_iop_colorout_gui_data_t *)self->gui_data;

  g->profiles = NULL;
  dt_iop_color_profile_t *prof = (dt_iop_color_profile_t *)g_malloc0(sizeof(dt_iop_color_profile_t));
  g_strlcpy(prof->filename, "sRGB", sizeof(prof->filename));
  g_strlcpy(prof->name, "sRGB", sizeof(prof->name));
  int pos;
  int display_pos;
  prof->pos = 0;
  prof->display_pos = 0;
  g->profiles = g_list_append(g->profiles, prof);

  prof = (dt_iop_color_profile_t *)g_malloc0(sizeof(dt_iop_color_profile_t));
  g_strlcpy(prof->filename, "adobergb", sizeof(prof->filename));
  g_strlcpy(prof->name, "adobergb", sizeof(prof->name));
  prof->pos = 1;
  prof->display_pos = 1;
  g->profiles = g_list_append(g->profiles, prof);

  prof = (dt_iop_color_profile_t *)g_malloc0(sizeof(dt_iop_color_profile_t));
  g_strlcpy(prof->filename, "X profile", sizeof(prof->filename));
  g_strlcpy(prof->name, "X profile", sizeof(prof->name));
  prof->pos = -1;
  prof->display_pos = 2;
  g->profiles = g_list_append(g->profiles, prof);

  prof = (dt_iop_color_profile_t *)g_malloc0(sizeof(dt_iop_color_profile_t));
  g_strlcpy(prof->filename, "linear_rgb", sizeof(prof->filename));
  g_strlcpy(prof->name, "linear_rgb", sizeof(prof->name));
  pos = prof->pos = 2;
  display_pos = prof->display_pos = 3;
  g->profiles = g_list_append(g->profiles, prof);

  // read {conf,data}dir/color/out/*.icc
  char datadir[DT_MAX_PATH_LEN];
  char confdir[DT_MAX_PATH_LEN];
  char dirname[DT_MAX_PATH_LEN];
  char filename[DT_MAX_PATH_LEN];
  dt_loc_get_user_config_dir(confdir, DT_MAX_PATH_LEN);
  dt_loc_get_datadir(datadir, DT_MAX_PATH_LEN);
  snprintf(dirname, DT_MAX_PATH_LEN, "%s/color/out", confdir);
  if(!g_file_test(dirname, G_FILE_TEST_IS_DIR))
    snprintf(dirname, DT_MAX_PATH_LEN, "%s/color/out", datadir);
  cmsHPROFILE tmpprof;
  const gchar *d_name;
  GDir *dir = g_dir_open(dirname, 0, NULL);
  if(dir)
  {
    while((d_name = g_dir_read_name(dir)))
    {
      snprintf(filename, DT_MAX_PATH_LEN, "%s/%s", dirname, d_name);
      tmpprof = cmsOpenProfileFromFile(filename, "r");
      if(tmpprof)
      {
        char *lang = getenv("LANG");
        if (!lang) lang = "en_US";

        dt_iop_color_profile_t *prof = (dt_iop_color_profile_t *)g_malloc0(sizeof(dt_iop_color_profile_t));
        char name[1024];
        cmsGetProfileInfoASCII(tmpprof, cmsInfoDescription, lang, lang+3, name, 1024);
        g_strlcpy(prof->name, name, sizeof(prof->name));
        g_strlcpy(prof->filename, d_name, sizeof(prof->filename));
        prof->pos = ++pos;
        prof->display_pos = ++display_pos;
        cmsCloseProfile(tmpprof);
        g->profiles = g_list_append(g->profiles, prof);
      }
    }
    g_dir_close(dir);
  }

  self->widget = gtk_vbox_new(TRUE, DT_BAUHAUS_SPACE);

  // TODO:
  g->cbox1 = dt_bauhaus_combobox_new(self);
  gtk_box_pack_start(GTK_BOX(self->widget), g->cbox1, TRUE, TRUE, 0);
  dt_bauhaus_widget_set_label(g->cbox1, _("output intent"));
  dt_bauhaus_combobox_add(g->cbox1, _("perceptual"));
  dt_bauhaus_combobox_add(g->cbox1, _("relative colorimetric"));
  dt_bauhaus_combobox_add(g->cbox1, C_("rendering intent", "saturation"));
  dt_bauhaus_combobox_add(g->cbox1, _("absolute colorimetric"));
  g->cbox4 = dt_bauhaus_combobox_new(self);
  dt_bauhaus_widget_set_label(g->cbox4, _("display intent"));
  gtk_box_pack_start(GTK_BOX(self->widget), g->cbox4, TRUE, TRUE, 0);
  dt_bauhaus_combobox_add(g->cbox4, _("perceptual"));
  dt_bauhaus_combobox_add(g->cbox4, _("relative colorimetric"));
  dt_bauhaus_combobox_add(g->cbox4, C_("rendering intent", "saturation"));
  dt_bauhaus_combobox_add(g->cbox4, _("absolute colorimetric"));
  g->cbox2 = dt_bauhaus_combobox_new(self);
  g->cbox3 = dt_bauhaus_combobox_new(self);
  g->cbox5 = dt_bauhaus_combobox_new(self);
  dt_bauhaus_widget_set_label(g->cbox2, _("output profile"));
  dt_bauhaus_widget_set_label(g->cbox5, _("softproof profile"));
  dt_bauhaus_widget_set_label(g->cbox3, _("display profile"));
  gtk_box_pack_start(GTK_BOX(self->widget), g->cbox2, TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(self->widget), g->cbox5, TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(self->widget), g->cbox3, TRUE, TRUE, 0);
  GList *l = g->profiles;
  while(l)
  {
    dt_iop_color_profile_t *prof = (dt_iop_color_profile_t *)l->data;
    if(!strcmp(prof->name, "X profile"))
    {
      // the system display profile is only suitable for display purposes
      dt_bauhaus_combobox_add(g->cbox3, _("system display profile"));
    }
    else if(!strcmp(prof->name, "linear_rgb"))
    {
      dt_bauhaus_combobox_add(g->cbox2, _("linear RGB"));
      dt_bauhaus_combobox_add(g->cbox3, _("linear RGB"));
      dt_bauhaus_combobox_add(g->cbox5, _("linear RGB"));
    }
    else if(!strcmp(prof->name, "sRGB"))
    {
      dt_bauhaus_combobox_add(g->cbox2, _("sRGB (web-safe)"));
      dt_bauhaus_combobox_add(g->cbox3, _("sRGB (web-safe)"));
      dt_bauhaus_combobox_add(g->cbox5, _("sRGB (web-safe)"));
    }
    else if(!strcmp(prof->name, "adobergb"))
    {
      dt_bauhaus_combobox_add(g->cbox2, _("Adobe RGB"));
      dt_bauhaus_combobox_add(g->cbox3, _("Adobe RGB"));
      dt_bauhaus_combobox_add(g->cbox5, _("Adobe RGB"));
    }
    else
    {
      dt_bauhaus_combobox_add(g->cbox2, prof->name);
      dt_bauhaus_combobox_add(g->cbox3, prof->name);
      dt_bauhaus_combobox_add(g->cbox5, prof->name);
    }
    l = g_list_next(l);
  }

  char tooltip[1024];
  g_object_set(G_OBJECT(g->cbox1), "tooltip-text", _("rendering intent"), (char *)NULL);
  snprintf(tooltip, 1024, _("icc profiles in %s/color/out or %s/color/out"), confdir, datadir);
  g_object_set(G_OBJECT(g->cbox2), "tooltip-text", tooltip, (char *)NULL);
  snprintf(tooltip, 1024, _("display icc profiles in %s/color/out or %s/color/out"), confdir, datadir);
  g_object_set(G_OBJECT(g->cbox3), "tooltip-text", tooltip, (char *)NULL);
  snprintf(tooltip, 1024, _("softproof icc profiles in %s/color/out or %s/color/out"), confdir, datadir);
  g_object_set(G_OBJECT(g->cbox5), "tooltip-text", tooltip, (char *)NULL);

  g_signal_connect (G_OBJECT (g->cbox1), "value-changed",
                    G_CALLBACK (intent_changed),
                    (gpointer)self);
  g_signal_connect (G_OBJECT (g->cbox4), "value-changed",
                    G_CALLBACK (display_intent_changed),
                    (gpointer)self);
  g_signal_connect (G_OBJECT (g->cbox2), "value-changed",
                    G_CALLBACK (output_profile_changed),
                    (gpointer)self);
  g_signal_connect (G_OBJECT (g->cbox3), "value-changed",
                    G_CALLBACK (display_profile_changed),
                    (gpointer)self);
  g_signal_connect (G_OBJECT (g->cbox5), "value-changed",
                    G_CALLBACK (softproof_profile_changed),
                    (gpointer)self);

  // reload the profiles when the display profile changed!
  dt_control_signal_connect(darktable.signals, DT_SIGNAL_CONTROL_PROFILE_CHANGED,
                            G_CALLBACK(_signal_profile_changed), self->dev);
}
コード例 #4
0
ファイル: history_snapshot.c プロジェクト: AlicVB/darktable
dt_undo_lt_history_t *dt_history_snapshot_item_init(void)
{
  return (dt_undo_lt_history_t *)g_malloc0(sizeof(dt_undo_lt_history_t));
}
コード例 #5
0
ファイル: gkm-crypto.c プロジェクト: Distrotech/gnome-keyring
CK_RV
gkm_crypto_sexp_to_data (gcry_sexp_t sexp, guint bits, CK_BYTE_PTR data,
                         CK_ULONG *n_data, EggPadding padding, ...)
{
	gcry_sexp_t at = NULL;
	gsize n_block, offset, len;
	gcry_mpi_t mpi = NULL;
	gpointer padded;
	guchar *block;
	va_list va;
	gboolean ret;
	gcry_error_t gcry;

	g_assert (sexp);
	g_assert (data);
	g_assert (n_data);
	g_assert (bits);

	/* First try and dig out sexp child based on arguments */
	va_start (va, padding);
	at = gkm_sexp_get_childv (sexp, va);
	va_end (va);

	/* It's expected we would find it */
	g_return_val_if_fail (at != NULL, CKR_GENERAL_ERROR);

	/* Parse out the MPI */
	mpi = gcry_sexp_nth_mpi (at, 1, GCRYMPI_FMT_USG);
	g_return_val_if_fail (at != NULL, CKR_GENERAL_ERROR);
	gcry_sexp_release (at);

	/* Print out the MPI into the end of a temporary buffer */
	n_block = (bits + 7) / 8;
	gcry = gcry_mpi_print (GCRYMPI_FMT_USG, NULL, 0, &len, mpi);
	g_return_val_if_fail (gcry == 0, CKR_GENERAL_ERROR);
	g_return_val_if_fail (len <= n_block, CKR_GENERAL_ERROR);
	offset = n_block - len;
	block = g_malloc0 (n_block);
	memset (block, 0, offset);
	gcry = gcry_mpi_print (GCRYMPI_FMT_USG, block + offset, len, &len, mpi);
	g_return_val_if_fail (gcry == 0, CKR_GENERAL_ERROR);
	g_return_val_if_fail (len == n_block - offset, CKR_GENERAL_ERROR);
	gcry_mpi_release (mpi);

	/* Pad it properly if necessary */
	if (padding != NULL) {
		ret = (padding) (g_realloc, n_block, block, n_block, &padded, &n_block);
		g_free (block);
		if (ret == FALSE)
			return CKR_DATA_LEN_RANGE;
		block = padded;
	}

	/* Now stuff it into the output buffer */
	if (n_block > *n_data)
		return CKR_BUFFER_TOO_SMALL;

	memcpy (data, block, n_block);
	*n_data = n_block;
	g_free (block);

	return CKR_OK;
}
コード例 #6
0
ファイル: hwp-hwp5-file.c プロジェクト: nakijun/libhwp
static void make_stream (HwpHWP5File *file, GError **error)
{
  GsfInput  *input        = NULL;
  GsfInfile *ole          = GSF_INFILE (file->priv->olefile);
  gint       n_root_entry = gsf_infile_num_children (ole);

  if (n_root_entry < 1)
  {
    g_set_error_literal (error,
                         HWP_FILE_ERROR,
                         HWP_FILE_ERROR_INVALID,
                         "invalid hwp file");
    return;
  }

  /* 우선 순위에 따라 스트림을 만든다 */
  input = gsf_infile_child_by_name (ole, "FileHeader");
  if (input && gsf_infile_num_children (GSF_INFILE (input)) == -1)
  {
    file->file_header_stream = input;
    input = NULL;
    parse_file_header (file);
  }
  else
  {
    goto FAIL;
  }

  input = gsf_infile_child_by_name (ole, "DocInfo");
  if (input && gsf_infile_num_children (GSF_INFILE (input)) == -1)
  {
    if (file->is_compress)
    {
      GInputStream      *gis;
      GZlibDecompressor *zd;
      GInputStream      *cis;

      gis = (GInputStream *) gsf_input_stream_new (input);
      zd  = g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_RAW);
      cis = g_converter_input_stream_new (gis, (GConverter *)   zd);
      g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (cis), TRUE);
      file->doc_info_stream = cis;

      g_object_unref (zd);
      g_object_unref (gis);

      input = NULL;
    }
    else
    {
      file->doc_info_stream = (GInputStream *) gsf_input_stream_new (input);
    }
  }
  else
  {
    goto FAIL;
  }

  if (!file->is_distribute)
    input = gsf_infile_child_by_name (ole, "BodyText");
  else
    input = gsf_infile_child_by_name (ole, "ViewText");

  if (input)
  {
    for (gint i = 0; i < gsf_infile_num_children (GSF_INFILE (input)); i++)
    {
      GsfInput *section =
                  gsf_infile_child_by_name (GSF_INFILE (input),
                                            g_strdup_printf("Section%d", i));

      if (gsf_infile_num_children (GSF_INFILE (section)) != -1)
      {
        if (GSF_IS_INPUT (section))
          g_object_unref (section);

        g_set_error_literal (error,
                             HWP_FILE_ERROR,
                             HWP_FILE_ERROR_INVALID,
                             "invalid hwp file");
        return;
      }

      if (file->is_distribute)
      {
        guint8 *data = g_malloc0 (256);
        gsf_input_read (section, 4, NULL);
        gsf_input_read (section, 256, data);
        guint32 seed = GSF_LE_GET_GUINT32 (data);
        msvc_srand (seed);
        gint n = 0, val = 0, offset;

        for (guint i = 0; i < 256; i++)
        {
          if (n == 0)
          {
            val = msvc_rand() & 0xff;
            n = (msvc_rand() & 0xf) + 1;
          }

          data[i] ^= val;

          n--;
        }

        offset = 4 + (seed & 0xf);
        gchar *key = g_malloc0 (16);
        memcpy (key, (const gchar *) data + offset, 16);
#ifdef HWP_ENABLE_DEBUG
        gchar *sha1 = g_convert ((const gchar *) data + offset, 80,
                                 "UTF-8", "UTF-16LE", NULL, NULL, error);
        printf ("sha1: %s\n", sha1);
        printf ("key: %s\n", key);
        g_free (sha1);
#endif
        g_free (data);

        EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new ();
        EVP_CIPHER_CTX_init (ctx);
        EVP_DecryptInit_ex (ctx, EVP_aes_128_ecb(), NULL,
                            (unsigned char *) key, NULL);
        g_free (key);
        EVP_CIPHER_CTX_set_padding(ctx, 0); /* no padding */

        gsf_off_t encrypted_data_len = gsf_input_remaining (section);
        guint8 const *encrypted_data = gsf_input_read (section, encrypted_data_len, NULL);

        guint8 *decrypted_data = g_malloc (encrypted_data_len);
        int decrypted_data_len, len;

        EVP_DecryptUpdate (ctx, decrypted_data, &len, encrypted_data, encrypted_data_len);
        decrypted_data_len = len;

        EVP_DecryptFinal_ex (ctx, decrypted_data + len, &len);
        decrypted_data_len += len;

        EVP_CIPHER_CTX_free (ctx);
        g_object_unref (section);

        section = gsf_input_memory_new (decrypted_data, decrypted_data_len, TRUE);
      }

      if (file->is_compress)
      {
        GInputStream      *gis;
        GZlibDecompressor *zd;
        GInputStream      *cis;

        gis = (GInputStream *) gsf_input_stream_new (section);
        zd  = g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_RAW);
        cis = g_converter_input_stream_new (gis, (GConverter *) zd);
        g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (cis), TRUE);
        g_ptr_array_add (file->section_streams, cis);
        g_object_unref (zd);
        g_object_unref (gis);
      }
      else
      {
        GInputStream *stream = (GInputStream *) gsf_input_stream_new (section);
        g_ptr_array_add (file->section_streams, stream);
      }
    } /* for */
    g_object_unref (input);
    input = NULL;
  }
  else
  {
    goto FAIL;
  }

  input = gsf_infile_child_by_name (ole, "\005HwpSummaryInformation");
  if (input && gsf_infile_num_children (GSF_INFILE (input)) == -1)
  {
    file->summary_info_stream = input;
    input = NULL;
  }
  else
  {
    goto FAIL;
  }

  input = gsf_infile_child_by_name (ole, "BinData");

  if (input)
  {
    gint n_data = gsf_infile_num_children (GSF_INFILE (input));

    for (gint i = 0; i < n_data; i++)
    {
      GsfInput *bin_data_input =
                  gsf_infile_child_by_index (GSF_INFILE (input), i);

      if (gsf_infile_num_children (GSF_INFILE (bin_data_input)) != -1)
      {
        if (GSF_IS_INPUT (bin_data_input))
          g_object_unref (bin_data_input);

        g_set_error_literal (error,
                             HWP_FILE_ERROR,
                             HWP_FILE_ERROR_INVALID,
                             "invalid hwp file");
        return;
      }

      if (file->is_compress)
      {
        GInputStream      *gis;
        GZlibDecompressor *zd;
        GInputStream      *cis;

        gis = (GInputStream *) gsf_input_stream_new (bin_data_input);
        zd  = g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_RAW);
        cis = g_converter_input_stream_new (gis, (GConverter *) zd);
        g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (cis), TRUE);
        g_ptr_array_add (file->bin_data_streams, cis);
        g_object_unref (zd);
        g_object_unref (gis);
      }
      else
      {
        GInputStream *stream = (GInputStream *) gsf_input_stream_new (bin_data_input);
        g_ptr_array_add (file->bin_data_streams, stream);
      }
    }

    g_object_unref (input);
    input = NULL;
  }

  input = gsf_infile_child_by_name (ole, "PrvText");
  if (input && gsf_infile_num_children (GSF_INFILE (input)) == -1)
  {
    file->prv_text_stream = input;
    input = NULL;
  }
  else
  {
    goto FAIL;
  }

  input = gsf_infile_child_by_name (ole, "PrvImage");
  if (input && gsf_infile_num_children (GSF_INFILE (input)) == -1)
  {
    file->prv_image_stream = input;
    input = NULL;
  }
  else
  {
    goto FAIL;
  }

  return;

  FAIL:

  if (GSF_IS_INPUT (input))
    g_object_unref (input);

  g_set_error_literal (error,
                       HWP_FILE_ERROR,
                       HWP_FILE_ERROR_INVALID,
                       "invalid hwp file");
  return;
}
コード例 #7
0
ファイル: shmsrc~.c プロジェクト: vliaskov/shmdata
static void 
shmsrc_tilde_try_pop_audio_buf (t_shmsrc_tilde *x)
{
  //g_print ("length %d\n", g_async_queue_length (x->x_audio_queue));
  x->x_current_audio_buf = g_async_queue_try_pop (x->x_audio_queue);

  if (x->x_current_audio_buf == NULL)
      return;
  
  double src_ratio;
  if (x->x_sample_duration < 1.0  || x->x_stream_sample_duration < 1.0)
    src_ratio = (double) x->x_pd_samplerate  
      / (double)x->x_current_audio_buf->sample_rate; 
  else 
    src_ratio =  x->x_stream_sample_duration / x->x_sample_duration; 

  /* g_print ("x->x_pd_samplerate %d x->x_current_audio_buf->sample_rate %d\n", x->x_pd_samplerate, x->x_current_audio_buf->sample_rate);  */
  /* g_print ("x->x_sample_duration %f x->x_stream_sample_duration %f\n", x->x_sample_duration, x->x_stream_sample_duration);  */
  /* g_print ("%f queue length %d, stream sample dur %f, sample duration %f\n",      */
  /* 	   src_ratio,       */
  /* 	   g_async_queue_length (x->x_audio_queue),      */
  /* 	   x->x_stream_sample_duration,      */
  /* 	   x->x_sample_duration);      */
  
  if (src_ratio == 1 )
    return;
  
  SRC_DATA src_data ;  
  int error, terminate ;  
  int input_len = x->x_current_audio_buf->remaining_samples;  
  
  int output_len = floor (input_len * src_ratio);  
  
  if (output_len == 0)
    return;
  
  //g_print ("%d, %d\n",output_len,input_len);
  src_data.data_in = x->x_current_audio_buf->audio_data ;  
  src_data.input_frames = input_len ;  
  
  src_data.src_ratio =  src_ratio;  
  
  
  //g_print ("outputlen %d channels %d\n", output_len, x->x_current_audio_buf->num_channels_in_buf);
  t_float *output = g_malloc0 (sizeof (t_float) 
			       * output_len 
			       * x->x_current_audio_buf->num_channels_in_buf);  
  src_data.data_out = output ;  
  src_data.output_frames = output_len;  
  
  //SRC_ZERO_ORDER_HOLD SRC_LINEAR SRC_SINC_FASTEST    
  if ((error = src_simple (&src_data, SRC_SINC_FASTEST, x->x_current_audio_buf->num_channels_in_buf))) 
    printf ("\n\nLine %d : %s\n\n", __LINE__, src_strerror (error)) ;    
  
  terminate = (int) ceil ((src_ratio >= 1.0) ? src_ratio : 1.0 / src_ratio) ;   
	      
  if (fabs (src_data.output_frames_gen - src_ratio * input_len) > 2 * terminate)   
    {	   
      printf ("\n\nLine %d : bad output data length %ld should be %d.\n", __LINE__,   
	      src_data.output_frames_gen, (int) floor (src_ratio * input_len)) ;   
      printf ("\tsrc_ratio  : %.4f\n", src_ratio) ;   
      printf ("\tinput_len  : %d\n\toutput_len : %d\n\n", input_len, output_len) ;   
    }

  if (x->x_current_audio_buf->free_audio_data)   
    g_free (x->x_current_audio_buf->audio_data);
  x->x_current_audio_buf->free_audio_data = TRUE;   
  x->x_current_audio_buf->audio_data = output;   
  x->x_current_audio_buf->remaining_samples = output_len; 
} 
コード例 #8
0
ファイル: gcompris_db.c プロジェクト: GNOME/gcompris
GList *gc_db_users_from_group_get(gint group_id)
{
  GcomprisProfile *profile = gc_profile_get_current();

  if (profile && profile->groups)
  {
    GcomprisGroup *group = g_hash_table_lookup(profile->groups, GINT_TO_POINTER(group_id));
    return group ? group->user_ids : NULL;
  }

  SUPPORT_OR_RETURN(NULL);

#ifdef USE_SQLITE
  char *zErrMsg;
  char **result;
  int rc;
  int nrow;
  int ncolumn;
  gchar *request;

  int i;
  GList *users = NULL;

  request = g_strdup_printf(USERS_FROM_GROUP(group_id));
  rc = sqlite3_get_table(gcompris_db,
			 request,
			 &result,
			 &nrow,
			 &ncolumn,
			 &zErrMsg
			 );

  if( rc!=SQLITE_OK ){
    g_error("SQL error: %s\n", zErrMsg);
  }

  g_free(request);

  if (nrow == 0){
    g_message("No users in the group id %d", group_id);
  } else {
    i = ncolumn;
    while (i < (nrow +1)*ncolumn) {
      GcomprisUser *user = g_malloc0(sizeof(GcomprisUser));

      user->user_id = atoi(result[i++]);
      user->login = g_strdup(result[i++]);
      user->lastname = g_strdup(result[i++]);
      user->firstname = g_strdup(result[i++]);
      user->birthdate = g_strdup(result[i++]);
      user->class_id = atoi(result[i++]);

      users = g_list_append(users, user);
    }
  }

  return users;
#else
  return NULL;
#endif
}
コード例 #9
0
ファイル: gcompris_db.c プロジェクト: GNOME/gcompris
GList *gc_menu_load_db(GList *boards_list)
{
  SUPPORT_OR_RETURN(NULL);

#ifdef USE_SQLITE

  GList *boards = boards_list;

  char *zErrMsg;
  char **result;
  int rc;
  int nrow;
  int ncolumn;
  int i;

  rc = sqlite3_get_table(gcompris_db,
			 BOARDS_READ,
			 &result,
			 &nrow,
			 &ncolumn,
			 &zErrMsg
			 );

  if( rc!=SQLITE_OK ){
    g_error("SQL error: %s\n", zErrMsg);
  }

  /* first ncolumns are columns labels. */
  i = ncolumn;

  while (i < (nrow +1)*ncolumn) {
    GcomprisBoard *gcomprisBoard = NULL;

    gcomprisBoard = g_malloc0 (sizeof (GcomprisBoard));

    gcomprisBoard->plugin=NULL;
    gcomprisBoard->previous_board=NULL;
    gcomprisBoard->board_ready=FALSE;
    gcomprisBoard->canvas=gc_get_canvas();

    gcomprisBoard->gmodule      = NULL;
    gcomprisBoard->gmodule_file = NULL;

    gcomprisBoard->board_id = atoi(result[i++]);
    gcomprisBoard->name = g_strdup(result[i++]);
    gcomprisBoard->section_id = atoi(result[i++]);
    gcomprisBoard->section = g_strdup(result[i++]);
    gcomprisBoard->author = g_strdup(result[i++]);
    gcomprisBoard->type = g_strdup(result[i++]);
    gcomprisBoard->mode = g_strdup(result[i++]);
    gcomprisBoard->difficulty = g_strdup(result[i++]);
    gcomprisBoard->icon_name = g_strdup(result[i++]);
    gcomprisBoard->boarddir = g_strdup(result[i++]);
    gcomprisBoard->mandatory_sound_file = g_strdup(result[i++]);
    gcomprisBoard->mandatory_sound_dataset = g_strdup(result[i++]);
    gcomprisBoard->filename = g_strdup(result[i++]);
    gcomprisBoard->title =  reactivate_newline(gettext(result[i++]));
    gcomprisBoard->description  = reactivate_newline(gettext(result[i++]));
    gcomprisBoard->prerequisite = reactivate_newline(gettext(result[i++]));
    gcomprisBoard->goal = reactivate_newline(gettext(result[i++]));
    gcomprisBoard->manual = reactivate_newline(gettext(result[i++]));
    gcomprisBoard->credit = reactivate_newline(gettext(result[i++]));
    gcomprisBoard->demo = atoi(result[i++]);

    boards = g_list_append(boards, gcomprisBoard);
    gchar *msg = g_strdup_printf(_("Loading activity from database:\n%s"),
				 gcomprisBoard->title);
    gc_status_set_msg(msg);
    g_free(msg);
  }

  sqlite3_free_table(result);

  return boards;

#endif
}
コード例 #10
0
ファイル: icsimporter.c プロジェクト: ebbywiselyn/evolution
static void
init_widgets(char *path)
{

	GtkWidget *vbox, *hbox, *dialog;
	icalcomponent_kind kind;
	icalcomponent *subcomp;
	GtkWidget *selector, *label;
	ESourceList *source_list;
	ESource *primary;
	GtkWidget *scrolled;
	ICalImporterData *icidata = g_malloc0(sizeof(*icidata));
	GtkWidget *icon, *button;
	char *label_str = NULL;
	char *markup;

	g_return_if_fail ( path != NULL);
	dialog = gtk_dialog_new_with_buttons (_("Import ICS"),
						NULL, GTK_DIALOG_DESTROY_WITH_PARENT,
						GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
						NULL);
	icidata->window = dialog;
	g_signal_connect (dialog,
			  "response",
			  G_CALLBACK (dialog_response_cb),
			  icidata);

	vbox = GTK_DIALOG(dialog)->vbox;
	hbox = gtk_hbox_new (FALSE, FALSE);
	label = gtk_label_new(NULL);

	gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 6);

	icidata->icalcomp = get_icalcomponent_from_file (path);

	subcomp = icalcomponent_get_inner(icidata->icalcomp);
	kind = icalcomponent_isa (subcomp);

	if (kind == ICAL_VTODO_COMPONENT ) {
		e_cal_get_sources (&source_list, E_CAL_SOURCE_TYPE_TODO, NULL);
		label_str = _("Select Task List");
		icidata->source_type = E_CAL_SOURCE_TYPE_TODO;
	} else if ( kind == ICAL_VEVENT_COMPONENT) {
		e_cal_get_sources (&source_list, E_CAL_SOURCE_TYPE_EVENT, NULL);
		label_str = _("Select Calendar");
		icidata->source_type = E_CAL_SOURCE_TYPE_EVENT;
	}

	markup = g_markup_printf_escaped ("<b>%s</b>", label_str);
	gtk_label_set_markup (GTK_LABEL (label), markup);
	g_free (markup);
	hbox = gtk_hbox_new (FALSE, FALSE);
	gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 6);
	gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 6);

	selector = e_source_selector_new (source_list);
	e_source_selector_show_selection (E_SOURCE_SELECTOR (selector), FALSE);
	scrolled = gtk_scrolled_window_new(NULL, NULL);
	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW (scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
	gtk_container_add((GtkContainer *)scrolled, selector);
	gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled), GTK_SHADOW_IN);
	hbox = gtk_hbox_new (FALSE, FALSE);
	gtk_box_pack_start (GTK_BOX (hbox), scrolled, TRUE, TRUE, 6);
	gtk_box_pack_start (GTK_BOX (vbox), hbox, TRUE, TRUE, 6);
	icidata->selector = selector;


	/* FIXME What if no sources? */
	primary = e_source_list_peek_source_any (source_list);
	e_source_selector_set_primary_selection (E_SOURCE_SELECTOR (selector), primary);

	g_object_unref (source_list);
	hbox = gtk_hbox_new (FALSE, FALSE);
	icon = e_icon_factory_get_image ("stock_mail-import", E_ICON_SIZE_MENU);
	gtk_box_pack_start (GTK_BOX(hbox), icon, FALSE, FALSE, 6);
	label = gtk_label_new_with_mnemonic (_("_Import"));
	gtk_box_pack_start (GTK_BOX(hbox), label, FALSE, FALSE, 6);
	gtk_widget_show(label);
	button = gtk_button_new ();
	gtk_container_add (GTK_CONTAINER (button), hbox);
	gtk_dialog_add_action_widget (GTK_DIALOG (dialog), button, GTK_RESPONSE_OK);
	gtk_widget_grab_focus (button);

	gtk_window_set_default_size (GTK_WINDOW (dialog), 210,340);
	gtk_widget_show_all (dialog);
	gtk_dialog_run (GTK_DIALOG (dialog));
	gtk_widget_destroy (dialog);
}
コード例 #11
0
ファイル: gcompris_db.c プロジェクト: GNOME/gcompris
GcomprisProfile *gc_db_get_profile_from_id(gint profile_id)
{
  SUPPORT_OR_RETURN(FALSE);

#ifdef USE_SQLITE
  GcomprisProfile *profile = NULL;

  char *zErrMsg;
  char **result;
  int rc;
  int nrow;
  int ncolumn;
  gchar *request;

  int i;
  GList *ids;
  /* get section_id */
  request = g_strdup_printf(GET_PROFILE(profile_id));


  rc = sqlite3_get_table(gcompris_db,
			 request,
			 &result,
			 &nrow,
			 &ncolumn,
			 &zErrMsg
			 );

  if( rc!=SQLITE_OK ){
    g_error("SQL error: %s\n", zErrMsg);
  }

  if (nrow != 0){
    profile = g_malloc0(sizeof(GcomprisProfile));

    profile->profile_id = profile_id;


    profile->name = g_strdup(result[3]);
    profile->directory = g_strdup(result[4]);
    profile->description = g_strdup(result[5]);
    sqlite3_free_table(result);
    g_free(request);

    request = g_strdup_printf(GET_GROUPS_IN_PROFILE(profile->profile_id));

    rc = sqlite3_get_table(gcompris_db,
			   request,
			   &result,
			   &nrow,
			   &ncolumn,
			   &zErrMsg
			   );

    if( rc!=SQLITE_OK ){
      g_error("SQL error: %s\n", zErrMsg);
    }

    g_free(request);

    if (nrow == 0){
      g_message("No users' groups for profile %s", profile->name);
      profile->group_ids = NULL;
    } else {
      ids = NULL;

      i = ncolumn;
      while (i < (nrow +1)*ncolumn) {
	int *group_id = g_malloc(sizeof(int));

	*group_id = atoi(result[i++]);
	ids = g_list_append(ids, group_id);
      }
      profile->group_ids = ids;
    }
    sqlite3_free_table(result);

    request = g_strdup_printf(GET_ACTIVITIES_OUT_OF_PROFILE(profile->profile_id));
    rc = sqlite3_get_table(gcompris_db,
			   request,
			   &result,
			   &nrow,
			   &ncolumn,
			   &zErrMsg
			   );

    if( rc!=SQLITE_OK ){
      g_error("SQL error: %s\n", zErrMsg);
    }

    g_free(request);

    if (nrow == 0){
      g_message("No activities for profile %s", profile->name);
      profile->activities = NULL;
    } else {
      ids = NULL;

      i = ncolumn;
      while (i < (nrow +1)*ncolumn) {
	int *board_id = g_malloc(sizeof(int));

	*board_id = atoi(result[i++]);
	ids = g_list_append(ids, board_id);
      }
      profile->activities = ids;
    }
    sqlite3_free_table(result);
  }

  return profile;
#endif
}
コード例 #12
0
ファイル: xenfb.c プロジェクト: jmcabandara/qemu-xen
static int xenfb_map_fb(struct XenFB *xenfb)
{
    struct xenfb_page *page = xenfb->c.page;
    char *protocol = xenfb->c.xendev.protocol;
    int n_fbdirs;
    xen_pfn_t *pgmfns = NULL;
    xen_pfn_t *fbmfns = NULL;
    void *map, *pd;
    int mode, ret = -1;

    /* default to native */
    pd = page->pd;
    mode = sizeof(unsigned long) * 8;

    if (!protocol) {
	/*
	 * Undefined protocol, some guesswork needed.
	 *
	 * Old frontends which don't set the protocol use
	 * one page directory only, thus pd[1] must be zero.
	 * pd[1] of the 32bit struct layout and the lower
	 * 32 bits of pd[0] of the 64bit struct layout have
	 * the same location, so we can check that ...
	 */
	uint32_t *ptr32 = NULL;
	uint32_t *ptr64 = NULL;
#if defined(__i386__)
	ptr32 = (void*)page->pd;
	ptr64 = ((void*)page->pd) + 4;
#elif defined(__x86_64__)
	ptr32 = ((void*)page->pd) - 4;
	ptr64 = (void*)page->pd;
#endif
	if (ptr32) {
	    if (ptr32[1] == 0) {
		mode = 32;
		pd   = ptr32;
	    } else {
		mode = 64;
		pd   = ptr64;
	    }
	}
#if defined(__x86_64__)
    } else if (strcmp(protocol, XEN_IO_PROTO_ABI_X86_32) == 0) {
	/* 64bit dom0, 32bit domU */
	mode = 32;
	pd   = ((void*)page->pd) - 4;
#elif defined(__i386__)
    } else if (strcmp(protocol, XEN_IO_PROTO_ABI_X86_64) == 0) {
	/* 32bit dom0, 64bit domU */
	mode = 64;
	pd   = ((void*)page->pd) + 4;
#endif
    }

    if (xenfb->pixels) {
        munmap(xenfb->pixels, xenfb->fbpages * XC_PAGE_SIZE);
        xenfb->pixels = NULL;
    }

    xenfb->fbpages = (xenfb->fb_len + (XC_PAGE_SIZE - 1)) / XC_PAGE_SIZE;
    n_fbdirs = xenfb->fbpages * mode / 8;
    n_fbdirs = (n_fbdirs + (XC_PAGE_SIZE - 1)) / XC_PAGE_SIZE;

    pgmfns = g_malloc0(sizeof(xen_pfn_t) * n_fbdirs);
    fbmfns = g_malloc0(sizeof(xen_pfn_t) * xenfb->fbpages);

    xenfb_copy_mfns(mode, n_fbdirs, pgmfns, pd);
    map = xc_map_foreign_pages(xen_xc, xenfb->c.xendev.dom,
			       PROT_READ, pgmfns, n_fbdirs);
    if (map == NULL)
	goto out;
    xenfb_copy_mfns(mode, xenfb->fbpages, fbmfns, map);
    munmap(map, n_fbdirs * XC_PAGE_SIZE);

    xenfb->pixels = xc_map_foreign_pages(xen_xc, xenfb->c.xendev.dom,
            PROT_READ, fbmfns, xenfb->fbpages);
    if (xenfb->pixels == NULL)
	goto out;

    ret = 0; /* all is fine */

out:
    g_free(pgmfns);
    g_free(fbmfns);
    return ret;
}
コード例 #13
0
ファイル: msix.c プロジェクト: JMR-b/qemu
/* Initialize the MSI-X structures */
int msix_init(struct PCIDevice *dev, unsigned short nentries,
              MemoryRegion *table_bar, uint8_t table_bar_nr,
              unsigned table_offset, MemoryRegion *pba_bar,
              uint8_t pba_bar_nr, unsigned pba_offset, uint8_t cap_pos)
{
    int cap;
    unsigned table_size, pba_size;
    uint8_t *config;

    /* Nothing to do if MSI is not supported by interrupt controller */
    if (!msi_supported) {
        return -ENOTSUP;
    }

    if (nentries < 1 || nentries > PCI_MSIX_FLAGS_QSIZE + 1) {
        return -EINVAL;
    }

    table_size = nentries * PCI_MSIX_ENTRY_SIZE;
    pba_size = QEMU_ALIGN_UP(nentries, 64) / 8;

    /* Sanity test: table & pba don't overlap, fit within BARs, min aligned */
    if ((table_bar_nr == pba_bar_nr &&
         ranges_overlap(table_offset, table_size, pba_offset, pba_size)) ||
        table_offset + table_size > memory_region_size(table_bar) ||
        pba_offset + pba_size > memory_region_size(pba_bar) ||
        (table_offset | pba_offset) & PCI_MSIX_FLAGS_BIRMASK) {
        return -EINVAL;
    }

    cap = pci_add_capability(dev, PCI_CAP_ID_MSIX, cap_pos, MSIX_CAP_LENGTH);
    if (cap < 0) {
        return cap;
    }

    dev->msix_cap = cap;
    dev->cap_present |= QEMU_PCI_CAP_MSIX;
    config = dev->config + cap;

    pci_set_word(config + PCI_MSIX_FLAGS, nentries - 1);
    dev->msix_entries_nr = nentries;
    dev->msix_function_masked = true;

    pci_set_long(config + PCI_MSIX_TABLE, table_offset | table_bar_nr);
    pci_set_long(config + PCI_MSIX_PBA, pba_offset | pba_bar_nr);

    /* Make flags bit writable. */
    dev->wmask[cap + MSIX_CONTROL_OFFSET] |= MSIX_ENABLE_MASK |
                                             MSIX_MASKALL_MASK;

    dev->msix_table = g_malloc0(table_size);
    dev->msix_pba = g_malloc0(pba_size);
    dev->msix_entry_used = g_malloc0(nentries * sizeof *dev->msix_entry_used);

    msix_mask_all(dev, nentries);

    memory_region_init_io(&dev->msix_table_mmio, OBJECT(dev), &msix_table_mmio_ops, dev,
                          "msix-table", table_size);
    memory_region_add_subregion(table_bar, table_offset, &dev->msix_table_mmio);
    memory_region_init_io(&dev->msix_pba_mmio, OBJECT(dev), &msix_pba_mmio_ops, dev,
                          "msix-pba", pba_size);
    memory_region_add_subregion(pba_bar, pba_offset, &dev->msix_pba_mmio);

    return 0;
}
コード例 #14
0
ファイル: writecabrillo.c プロジェクト: patlc/tlf
/** get next qso record from log
 *
 * Read next line from logfile until it is no comment.
 * Then parse the logline into a new allocated QSO data structure
 * and return that structure.
 *
 * \return ptr to new qso record (or NULL if eof)
 */
struct qso_t *get_next_record (FILE *fp)
{
    char buffer[160];
    char *tmp;
    char *sp;
    struct qso_t *ptr;
    struct tm date_n_time;

    while ((fgets(buffer, sizeof(buffer), fp)) != NULL) {

	if (!is_comment(buffer)) {
		
	    ptr = g_malloc0 (sizeof(struct qso_t));

	    /* remember whole line */
	    ptr->logline = g_strdup( buffer );

	    /* split buffer into parts for qso_t record and parse
	     * them accordingly */
	    tmp = strtok_r( buffer, " \t", &sp);

	    /* band */
	    ptr->band = atoi( tmp );


	    /* mode */
	    if ( strcasestr( tmp, "CW"))
		ptr->mode = CWMODE;
	    else if (strcasestr( tmp, "SSB" ))
		ptr->mode = SSBMODE;
	    else
		ptr->mode = DIGIMODE;

	    /* date & time */
	    memset( &date_n_time, 0, sizeof(struct tm) );

	    strptime ( strtok_r( NULL, " \t", &sp ), "%d-%b-%y", &date_n_time);
	    strptime ( strtok_r( NULL, " \t", &sp ), "%H:%M", &date_n_time);

	    ptr->year = date_n_time.tm_year + 1900;	/* convert to
							   1968..2067 */
	    ptr->month = date_n_time.tm_mon + 1;	/* tm_mon = 0..11 */
	    ptr->day   = date_n_time.tm_mday;

	    ptr->hour  = date_n_time.tm_hour;
	    ptr->min   = date_n_time.tm_min;

	    /* qso number */
	    ptr->qso_nr = atoi( strtok_r( NULL, " \t", &sp ) );

	    /* his call */
	    ptr->call = g_strdup( strtok_r( NULL, " \t", &sp ) );

	    /* RST send and received */
	    ptr->rst_s = atoi( strtok_r( NULL, " \t", &sp ) );
	    ptr->rst_r = atoi( strtok_r( NULL, " \t", &sp ) );

	    /* comment (exchange) */
	    ptr->comment = g_strndup( buffer + 54, 13 );

	    /* tx */
	    ptr->tx = (buffer[79] == '*') ? 1 : 0;

	    /* frequency */
	    ptr->freq = atof( buffer + 80 );
	    if ( ( ptr->freq < 1800. ) || ( ptr->freq >= 30000. ) ) {
		ptr->freq = 0.;
	    }

	    return ptr;
	}
    }

    return NULL;
}
コード例 #15
0
void
ToolsCore_RegisterPlugins(ToolsServiceState *state)
{
   ToolsAppProvider *fakeProv;
   ToolsAppProviderReg fakeReg;

   if (state->plugins == NULL) {
      return;
   }

   /*
    * Create "fake" app providers for the functionality provided by
    * vmtoolsd (GuestRPC channel, glib signals, custom app providers).
    */
   state->providers = g_array_new(FALSE, TRUE, sizeof (ToolsAppProviderReg));

   if (state->ctx.rpc != NULL) {
      fakeProv = g_malloc0(sizeof *fakeProv);
      fakeProv->regType = TOOLS_APP_GUESTRPC;
      fakeProv->regSize = sizeof (RpcChannelCallback);
      fakeProv->name = "GuestRPC";
      fakeProv->registerApp = ToolsCoreRegisterRPC;
      fakeProv->dumpState = ToolsCoreDumpRPC;

      fakeReg.prov = fakeProv;
      fakeReg.state = TOOLS_PROVIDER_ACTIVE;
      g_array_append_val(state->providers, fakeReg);
   }

   fakeProv = g_malloc0(sizeof *fakeProv);
   fakeProv->regType = TOOLS_APP_SIGNALS;
   fakeProv->regSize = sizeof (ToolsPluginSignalCb);
   fakeProv->name = "Signals";
   fakeProv->registerApp = ToolsCoreRegisterSignal;
   fakeProv->dumpState = ToolsCoreDumpSignal;

   fakeReg.prov = fakeProv;
   fakeReg.state = TOOLS_PROVIDER_ACTIVE;
   g_array_append_val(state->providers, fakeReg);

   fakeProv = g_malloc0(sizeof *fakeProv);
   fakeProv->regType = TOOLS_APP_PROVIDER;
   fakeProv->regSize = sizeof (ToolsAppProvider);
   fakeProv->name = "App Provider";
   fakeProv->registerApp = NULL;
   fakeProv->dumpState = NULL;

   fakeReg.prov = fakeProv;
   fakeReg.state = TOOLS_PROVIDER_ACTIVE;
   g_array_append_val(state->providers, fakeReg);

   fakeProv = g_malloc0(sizeof *fakeProv);
   fakeProv->regType = TOOLS_SVC_PROPERTY;
   fakeProv->regSize = sizeof (ToolsServiceProperty);
   fakeProv->name = "Service Properties";
   fakeProv->registerApp = ToolsCoreRegisterProperty;
   fakeProv->dumpState = ToolsCoreDumpProperty;

   fakeReg.prov = fakeProv;
   fakeReg.state = TOOLS_PROVIDER_ACTIVE;
   g_array_append_val(state->providers, fakeReg);


   /*
    * First app providers need to be identified, so that we know that they're
    * available for use by plugins who need them.
    */
   ToolsCoreForEachPlugin(state, NULL, ToolsCoreRegisterProvider);

   /*
    * Now that we know all app providers, register all the apps, activating
    * individual app providers as necessary.
    */
   ToolsCoreForEachPlugin(state, NULL, ToolsCoreRegisterApp);
}
コード例 #16
0
G_MODULE_EXPORT int
test_paint_wrapper_main (int argc, char *argv[])
{
  ClutterAlpha *alpha;
  ClutterActor *stage;
  ClutterColor  stage_color = { 0x61, 0x64, 0x8c, 0xff };
  SuperOH      *oh;
  gint          i;
  GError       *error;
  ClutterActor *real_hand;

  error = NULL;

  clutter_init_with_args (&argc, &argv,
                          NULL,
                          super_oh_entries,
                          NULL,
                          &error);
  if (error)
    {
      g_warning ("Unable to initialise Clutter:\n%s",
                 error->message);
      g_error_free (error);

      return EXIT_FAILURE;
    }

  stage = clutter_stage_get_default ();
  clutter_actor_set_size (stage, 800, 600);

  clutter_stage_set_title (CLUTTER_STAGE (stage), "Paint Test");
  clutter_stage_set_color (CLUTTER_STAGE (stage), &stage_color);

  oh = g_new(SuperOH, 1);
  oh->stage = stage;

  /* Create a timeline to manage animation */
  oh->timeline = clutter_timeline_new (6000);
  clutter_timeline_set_loop (oh->timeline, TRUE);

  /* fire a callback for frame change */
  g_signal_connect (oh->timeline, "new-frame", G_CALLBACK (frame_cb), oh);

  /* Set up some behaviours to handle scaling  */
  alpha = clutter_alpha_new_with_func (oh->timeline, my_sine_wave, NULL, NULL);

  oh->scaler_1 = clutter_behaviour_scale_new (alpha, 0.5, 0.5, 1.0, 1.0);
  oh->scaler_2 = clutter_behaviour_scale_new (alpha, 1.0, 1.0, 0.5, 0.5);

  real_hand = clutter_texture_new_from_file ("redhand.png", &error);
  if (real_hand == NULL)
    {
      g_error ("image load failed: %s", error->message);
      return EXIT_FAILURE;
    }

  /* create a new group to hold multiple actors in a group */
  oh->group = clutter_group_new();

  oh->hand = g_new (ClutterActor*, n_hands);

  oh->stage_width = clutter_actor_get_width (stage);
  oh->stage_height = clutter_actor_get_height (stage);
  oh->radius = (oh->stage_width + oh->stage_height)
             / n_hands;

  for (i = 0; i < n_hands; i++)
    {
      gint x, y, w, h;

      if (i == 0)
        oh->hand[i] = real_hand;
      else
        oh->hand[i] = clutter_clone_new (real_hand);

      clutter_actor_set_reactive (oh->hand[i], TRUE);

      clutter_actor_set_size (oh->hand[i], 200, 213);

      /* Place around a circle */
      w = clutter_actor_get_width (oh->hand[i]);
      h = clutter_actor_get_height (oh->hand[i]);

      x = oh->stage_width / 2
	+ oh->radius
	* cos (i * G_PI / (n_hands / 2))
	- w / 2;

      y = oh->stage_height / 2
	+ oh->radius
	* sin (i * G_PI / (n_hands / 2))
	- h / 2;

      clutter_actor_set_position (oh->hand[i], x, y);

      clutter_actor_move_anchor_point_from_gravity (oh->hand[i],
						   CLUTTER_GRAVITY_CENTER);

      g_signal_connect (oh->hand[i], "button-press-event",
                        G_CALLBACK (on_button_press_event),
                        oh);

      /* paint something before each hand */
      g_signal_connect (oh->hand[i],
                        "paint", G_CALLBACK (hand_pre_paint),
                        oh);

      /* paint something after each hand */
      g_signal_connect_after (oh->hand[i],
                              "paint", G_CALLBACK (hand_post_paint),
                              oh);

      /* Add to our group group */
      clutter_container_add_actor (CLUTTER_CONTAINER (oh->group), oh->hand[i]);

      if (i % 2)
	clutter_behaviour_apply (oh->scaler_1, oh->hand[i]);
      else
	clutter_behaviour_apply (oh->scaler_2, oh->hand[i]);
    }

  oh->paint_guards = g_malloc0 (sizeof (gboolean) * n_hands);

  /* Add the group to the stage */
  clutter_container_add_actor (CLUTTER_CONTAINER (stage),
                               CLUTTER_ACTOR (oh->group));

  /* Show everying ( and map window ) */
  clutter_actor_show (stage);

  g_signal_connect (stage, "key-release-event",
		    G_CALLBACK (input_cb),
		    oh);

  /* and start it */
  clutter_timeline_start (oh->timeline);

  clutter_main ();

  g_object_unref (oh->scaler_1);
  g_object_unref (oh->scaler_2);
  g_object_unref (oh->timeline);
  g_free (oh->paint_guards);
  g_free (oh->hand);
  g_free (oh);

  return 0;
}
コード例 #17
0
ファイル: virtio-ccw.c プロジェクト: artifexor/qemu
static int virtio_ccw_device_init(VirtioCcwDevice *dev, VirtIODevice *vdev)
{
    unsigned int cssid = 0;
    unsigned int ssid = 0;
    unsigned int schid;
    unsigned int devno;
    bool have_devno = false;
    bool found = false;
    SubchDev *sch;
    int ret;
    int num;
    DeviceState *parent = DEVICE(dev);

    sch = g_malloc0(sizeof(SubchDev));

    sch->driver_data = dev;
    dev->sch = sch;

    dev->vdev = vdev;
    dev->indicators = 0;

    /* Initialize subchannel structure. */
    sch->channel_prog = 0x0;
    sch->last_cmd_valid = false;
    sch->orb = NULL;
    /*
     * Use a device number if provided. Otherwise, fall back to subchannel
     * number.
     */
    if (dev->bus_id) {
        num = sscanf(dev->bus_id, "%x.%x.%04x", &cssid, &ssid, &devno);
        if (num == 3) {
            if ((cssid > MAX_CSSID) || (ssid > MAX_SSID)) {
                ret = -EINVAL;
                error_report("Invalid cssid or ssid: cssid %x, ssid %x",
                             cssid, ssid);
                goto out_err;
            }
            /* Enforce use of virtual cssid. */
            if (cssid != VIRTUAL_CSSID) {
                ret = -EINVAL;
                error_report("cssid %x not valid for virtio devices", cssid);
                goto out_err;
            }
            if (css_devno_used(cssid, ssid, devno)) {
                ret = -EEXIST;
                error_report("Device %x.%x.%04x already exists", cssid, ssid,
                             devno);
                goto out_err;
            }
            sch->cssid = cssid;
            sch->ssid = ssid;
            sch->devno = devno;
            have_devno = true;
        } else {
            ret = -EINVAL;
            error_report("Malformed devno parameter '%s'", dev->bus_id);
            goto out_err;
        }
    }

    /* Find the next free id. */
    if (have_devno) {
        for (schid = 0; schid <= MAX_SCHID; schid++) {
            if (!css_find_subch(1, cssid, ssid, schid)) {
                sch->schid = schid;
                css_subch_assign(cssid, ssid, schid, devno, sch);
                found = true;
                break;
            }
        }
        if (!found) {
            ret = -ENODEV;
            error_report("No free subchannel found for %x.%x.%04x", cssid, ssid,
                         devno);
            goto out_err;
        }
        trace_virtio_ccw_new_device(cssid, ssid, schid, devno,
                                    "user-configured");
    } else {
        cssid = VIRTUAL_CSSID;
        for (ssid = 0; ssid <= MAX_SSID; ssid++) {
            for (schid = 0; schid <= MAX_SCHID; schid++) {
                if (!css_find_subch(1, cssid, ssid, schid)) {
                    sch->cssid = cssid;
                    sch->ssid = ssid;
                    sch->schid = schid;
                    devno = schid;
                    /*
                     * If the devno is already taken, look further in this
                     * subchannel set.
                     */
                    while (css_devno_used(cssid, ssid, devno)) {
                        if (devno == MAX_SCHID) {
                            devno = 0;
                        } else if (devno == schid - 1) {
                            ret = -ENODEV;
                            error_report("No free devno found");
                            goto out_err;
                        } else {
                            devno++;
                        }
                    }
                    sch->devno = devno;
                    css_subch_assign(cssid, ssid, schid, devno, sch);
                    found = true;
                    break;
                }
            }
            if (found) {
                break;
            }
        }
        if (!found) {
            ret = -ENODEV;
            error_report("Virtual channel subsystem is full!");
            goto out_err;
        }
        trace_virtio_ccw_new_device(cssid, ssid, schid, devno,
                                    "auto-configured");
    }

    /* Build initial schib. */
    css_sch_build_virtual_schib(sch, 0, VIRTIO_CCW_CHPID_TYPE);

    sch->ccw_cb = virtio_ccw_cb;

    /* Build senseid data. */
    memset(&sch->id, 0, sizeof(SenseId));
    sch->id.reserved = 0xff;
    sch->id.cu_type = VIRTIO_CCW_CU_TYPE;
    sch->id.cu_model = dev->vdev->device_id;

    virtio_bind_device(vdev, &virtio_ccw_bindings, DEVICE(dev));
    /* Only the first 32 feature bits are used. */
    dev->host_features[0] = vdev->get_features(vdev, dev->host_features[0]);
    dev->host_features[0] |= 0x1 << VIRTIO_F_NOTIFY_ON_EMPTY;
    dev->host_features[0] |= 0x1 << VIRTIO_F_BAD_FEATURE;

    css_generate_sch_crws(sch->cssid, sch->ssid, sch->schid,
                          parent->hotplugged, 1);
    return 0;

out_err:
    dev->sch = NULL;
    g_free(sch);
    return ret;
}
コード例 #18
0
ファイル: ivshmem.c プロジェクト: JeremyAgost/qemu
static void pci_ivshmem_realize(PCIDevice *dev, Error **errp)
{
    IVShmemState *s = IVSHMEM(dev);
    uint8_t *pci_conf;
    uint8_t attr = PCI_BASE_ADDRESS_SPACE_MEMORY |
        PCI_BASE_ADDRESS_MEM_PREFETCH;

    if (!!s->server_chr + !!s->shmobj + !!s->hostmem != 1) {
        error_setg(errp,
                   "You must specify either 'shm', 'chardev' or 'x-memdev'");
        return;
    }

    if (s->hostmem) {
        MemoryRegion *mr;

        if (s->sizearg) {
            g_warning("size argument ignored with hostmem");
        }

        mr = host_memory_backend_get_memory(s->hostmem, errp);
        s->ivshmem_size = memory_region_size(mr);
    } else if (s->sizearg == NULL) {
        s->ivshmem_size = 4 << 20; /* 4 MB default */
    } else {
        char *end;
        int64_t size = qemu_strtosz(s->sizearg, &end);
        if (size < 0 || *end != '\0' || !is_power_of_2(size)) {
            error_setg(errp, "Invalid size %s", s->sizearg);
            return;
        }
        s->ivshmem_size = size;
    }

    fifo8_create(&s->incoming_fifo, sizeof(int64_t));

    /* IRQFD requires MSI */
    if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD) &&
        !ivshmem_has_feature(s, IVSHMEM_MSI)) {
        error_setg(errp, "ioeventfd/irqfd requires MSI");
        return;
    }

    /* check that role is reasonable */
    if (s->role) {
        if (strncmp(s->role, "peer", 5) == 0) {
            s->role_val = IVSHMEM_PEER;
        } else if (strncmp(s->role, "master", 7) == 0) {
            s->role_val = IVSHMEM_MASTER;
        } else {
            error_setg(errp, "'role' must be 'peer' or 'master'");
            return;
        }
    } else {
        s->role_val = IVSHMEM_MASTER; /* default */
    }

    if (s->role_val == IVSHMEM_PEER) {
        error_setg(&s->migration_blocker,
                   "Migration is disabled when using feature 'peer mode' in device 'ivshmem'");
        migrate_add_blocker(s->migration_blocker);
    }

    pci_conf = dev->config;
    pci_conf[PCI_COMMAND] = PCI_COMMAND_IO | PCI_COMMAND_MEMORY;

    pci_config_set_interrupt_pin(pci_conf, 1);

    memory_region_init_io(&s->ivshmem_mmio, OBJECT(s), &ivshmem_mmio_ops, s,
                          "ivshmem-mmio", IVSHMEM_REG_BAR_SIZE);

    /* region for registers*/
    pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY,
                     &s->ivshmem_mmio);

    memory_region_init(&s->bar, OBJECT(s), "ivshmem-bar2-container", s->ivshmem_size);
    if (s->ivshmem_64bit) {
        attr |= PCI_BASE_ADDRESS_MEM_TYPE_64;
    }

    if (s->hostmem != NULL) {
        MemoryRegion *mr;

        IVSHMEM_DPRINTF("using hostmem\n");

        mr = host_memory_backend_get_memory(MEMORY_BACKEND(s->hostmem), errp);
        vmstate_register_ram(mr, DEVICE(s));
        memory_region_add_subregion(&s->bar, 0, mr);
        pci_register_bar(PCI_DEVICE(s), 2, attr, &s->bar);
    } else if (s->server_chr != NULL) {
        /* FIXME do not rely on what chr drivers put into filename */
        if (strncmp(s->server_chr->filename, "unix:", 5)) {
            error_setg(errp, "chardev is not a unix client socket");
            return;
        }

        /* if we get a UNIX socket as the parameter we will talk
         * to the ivshmem server to receive the memory region */

        IVSHMEM_DPRINTF("using shared memory server (socket = %s)\n",
                        s->server_chr->filename);

        if (ivshmem_setup_interrupts(s) < 0) {
            error_setg(errp, "failed to initialize interrupts");
            return;
        }

        /* we allocate enough space for 16 peers and grow as needed */
        resize_peers(s, 16);
        s->vm_id = -1;

        pci_register_bar(dev, 2, attr, &s->bar);

        s->eventfd_chr = g_malloc0(s->vectors * sizeof(CharDriverState *));

        qemu_chr_add_handlers(s->server_chr, ivshmem_can_receive,
                              ivshmem_check_version, ivshmem_event, s);
    } else {
        /* just map the file immediately, we're not using a server */
        int fd;

        IVSHMEM_DPRINTF("using shm_open (shm object = %s)\n", s->shmobj);

        /* try opening with O_EXCL and if it succeeds zero the memory
         * by truncating to 0 */
        if ((fd = shm_open(s->shmobj, O_CREAT|O_RDWR|O_EXCL,
                        S_IRWXU|S_IRWXG|S_IRWXO)) > 0) {
           /* truncate file to length PCI device's memory */
            if (ftruncate(fd, s->ivshmem_size) != 0) {
                error_report("could not truncate shared file");
            }

        } else if ((fd = shm_open(s->shmobj, O_CREAT|O_RDWR,
                        S_IRWXU|S_IRWXG|S_IRWXO)) < 0) {
            error_setg(errp, "could not open shared file");
            return;
        }

        if (check_shm_size(s, fd, errp) == -1) {
            return;
        }

        create_shared_memory_BAR(s, fd, attr, errp);
    }
}
コード例 #19
0
ファイル: flush_worker.c プロジェクト: Aruiwen/cloudxy
int flush_work(gpointer data){
	int ret = 0;
	CACHE_CTRL *cctrl = (CACHE_CTRL*)data;
	GTimeVal expired;
	char *tmp_buf = (char *)g_malloc0(cctrl->block_size \
			*cctrl->flush_once_size);
	g_assert(tmp_buf);
	while (!cctrl->flush_worker_should_exit) {
		HLOG_DEBUG("-- flush worker doing --");
		g_get_current_time(&expired);
		g_time_val_add(&expired, cctrl->flush_interval * 1000 * 1000);
		g_mutex_lock(cctrl->cache_mutex);
		gboolean res = g_cond_timed_wait(cctrl->flush_waken_cond, \
				cctrl->cache_mutex, &expired);
		g_mutex_unlock(cctrl->cache_mutex); 
		HLOG_DEBUG(" time wait res for cond is :%d !",res);
		if (cctrl->flush_worker_should_exit) {
			HLOG_INFO("-- flush worker should exit --");
			break;
		}

		do {
			GSList *continue_blocks = NULL;
			ret = get_continues_blocks(cctrl, &continue_blocks);
			g_assert(ret==0);
			uint32_t blocks_count = g_slist_length(continue_blocks);
			uint32_t buff_len = blocks_count *cctrl->block_size;
			HLOG_DEBUG("--blocks_count:%d, buff_len:%d--", \
					blocks_count, buff_len);
			if (res == TRUE && buff_len == 0) {
				HLOG_ERROR("Never reach here");
				g_assert(0);
			}


			if (buff_len == 0) {
				HLOG_DEBUG("do not need flush now");
				break;
			}
			if (NULL == cctrl->write_callback_func) {
				HLOG_WARN("--not given flush callback func--");
				break;
			} 
			//char* tmp_buf = g_malloc0(buff_len);
			//g_assert(tmp_buf!=NULL);
			uint32_t start_no;
			uint32_t end_no; 
			int i = 0;
			for (i = 0; i < blocks_count; i++) {
				block_t *block = g_slist_nth_data(continue_blocks, i);
				if (i == 0) {
					start_no = block->block_no;
				}
				if (i == blocks_count-1) {
					end_no = block->block_no;
				}
				memcpy(tmp_buf + i * cctrl->block_size, \
						block->block, cctrl->block_size);
			}
			//HLOG_DEBUG("--tmp_buf:%p",tmp_buf);
			ret = cctrl->write_callback_func(cctrl->write_callback_user_param, \
					tmp_buf, start_no,end_no);
			g_assert(ret >= 0);
			//g_free(tmp_buf);
			if (ret >= 0 ) {
				HLOG_DEBUG("--signal write thread--");
				g_mutex_lock(cctrl->cache_mutex);
				__free_from_cache(cctrl, continue_blocks);
				//g_cond_broadcast(cctrl->writer_waken_cond);
				g_cond_signal(cctrl->writer_waken_cond);
				g_mutex_unlock(cctrl->cache_mutex);
				g_slist_free(continue_blocks);
				//HLOG_DEBUG("--return blocks to cache over--");
			}
		} while (get_cache_free_size(cctrl) < cctrl->flush_trigger_level \
				*cctrl->cache_size / 100 || (res == 0 && get_cache_free_size(cctrl) != 0));
	}
	g_free(tmp_buf);
	HLOG_INFO("--flush worker exit--");
	return 0;
}                        
コード例 #20
0
ファイル: snmp_bc_session.c プロジェクト: CSU-GH/okl4_3.0
static int sim_init() {

	int i;

	dbg("************************************\n");
	dbg("****** Blade Center Simulator ******\n");
	dbg("************************************\n");

	sim_hash = g_hash_table_new(g_str_hash, g_str_equal);

	if (sim_hash == NULL) {
		dbg("Cannot allocate simulation hash table\n");
		return -1;
	}

	for (i=0; sim_resource_array[i].oid != NULL; i++) {
		
		char *key;
		char *key_exists;

		SnmpMibInfoT *mibinfo;
    
		key = g_strdup(sim_resource_array[i].oid);
		if (!key) {
			dbg("Cannot allocate memory for key for oid=%s\n",
			    sim_resource_array[i].oid);
			sim_close();
			return -1;
		}
		mibinfo = g_malloc0(sizeof(SnmpMibInfoT));
		if (!mibinfo) {
			dbg("Cannot allocate memory for hash value for oid=%s", 
			    sim_resource_array[i].oid);
			sim_close();
			return -1;
		}

		key_exists = g_hash_table_lookup(sim_hash, key); 
		if (!key_exists) {
			mibinfo->type = sim_resource_array[i].mib.type;

			switch (mibinfo->type) {
			case ASN_INTEGER:
				mibinfo->value.integer = sim_resource_array[i].mib.value.integer;
				break;
			case ASN_OCTET_STR:
				strcpy(mibinfo->value.string, sim_resource_array[i].mib.value.string);
				break;
			default:
				dbg("Unknown SNMP type=%d for oid=%s\n", mibinfo->type, key);
				return -1;
			}
			g_hash_table_insert(sim_hash, key, mibinfo);
		}
		else {
			dbg("WARNING: Oid %s is defined twice\n", sim_resource_array[i].oid);
		}
	}

	return 0;
}
コード例 #21
0
ファイル: shmsrc~.c プロジェクト: vliaskov/shmdata
void 
shmsrc_tilde_on_data (shmdata_any_reader_t *reader,
		      void *shmbuf,
		      void *data,
		      int data_size,
		      unsigned long long timestamp,
		      const char *type_description, 
		      void *user_data)
{
  t_shmsrc_tilde *x = (t_shmsrc_tilde *) user_data;
  
  //do not buffer audio if dsp is off FIXME should be optionnal
  if (!canvas_dspstate)
    {
      shmdata_any_reader_free (shmbuf);
      return;
    }

  /* printf ("data %p, data size %d, timestamp %llu, type descr %s\n",   */
  /* 	  data, data_size, timestamp, type_description);   */
  GstStructure *meta_data = gst_structure_from_string (type_description, NULL);
  if (meta_data == NULL) 
    { 
      shmdata_any_reader_free (shmbuf);
      //post ("metadata is NULL\n"); 
      return; 
    } 
  if (!g_str_has_prefix (gst_structure_get_name (meta_data), "audio/")) 
    { 
      shmdata_any_reader_free (shmbuf);
      //post ("not an audio stream\n"); 
      return; 
    } //should be "audio/... 

  t_shmsrc_tilde_buf *audio_buf = g_malloc0 (sizeof (t_shmsrc_tilde_buf));

  int channels = -1; 
  int samplerate = -1; 
  int width = -1; 
  gst_structure_get (meta_data,  
   		     "rate", G_TYPE_INT, &samplerate,  
   		     "channels", G_TYPE_INT, &channels,  
   		     "width", G_TYPE_INT, &width,  
   		     NULL); 

  gst_structure_free(meta_data);

  audio_buf->num_channels_in_buf = channels; 
  if (channels > x->x_num_outlets)
    audio_buf->num_channels_to_output = x->x_num_outlets;
  else if (channels < 0)
    audio_buf->num_channels_to_output = 0;
  else 
    audio_buf->num_channels_to_output = channels;
  
  audio_buf->num_unused_channels = channels - x->x_num_outlets;
  if (audio_buf->num_unused_channels < 0)
    audio_buf->num_unused_channels = 0;

  audio_buf->sample_rate = samplerate;
  //audio_buf->sample_size = width;
  audio_buf->remaining_samples = data_size / ((width/8) * channels);
  /* g_print ("data_size %d, width %d, channels %d, samplerate %d, remaining  samples %d, cur logicial date %f \n",   */
  /* 	   data_size,    */
  /* 	   width,    */
  /* 	   channels,    */
  /* 	   samplerate,  */
  /* 	   audio_buf->remaining_samples, */
  /* 	   clock_getlogicaltime());     */
   //g_print ("on data queue size %d\n", g_async_queue_length (x->x_audio_queue));
  double audio_buf_sample_duration =  (1.0 / samplerate) * (32.*441000.); //see TIMEUNITPERSEC in m_sched.c
  audio_buf->shm_buf = shmbuf;

  //double cur_date = clock_getlogicaltime();
  /* if (x->x_stream_data_date == -1.0) */
  /*   x->x_stream_data_date = clock_getlogicaltime(); */
  if (x->x_stream_sample_duration == -1.0)
    x->x_stream_sample_duration = audio_buf_sample_duration;

  /* else */
  /* 	{ */
  /* 	  double cur_stream_dur = (cur_date - x->x_stream_data_date) / audio_buf->remaining_samples; */
  /* 	  double max_deriv = 0.001;  //FIXME make this a param */
  /* 	  if (cur_stream_dur > audio_buf_sample_duration * (1.0 + max_deriv)) */
  /* 	    cur_stream_dur = audio_buf_sample_duration * (1.0 + max_deriv); */
  /* 	  else if (cur_stream_dur < audio_buf_sample_duration * (1.0 - max_deriv)) */
  /* 	    cur_stream_dur = audio_buf_sample_duration * (1.0 - max_deriv); */

  /* 	  x->x_stream_sample_duration = audio_buf_sample_duration; */
  /* 	} */
  /*     x->x_stream_sample_duration = ceil (x->x_stream_sample_duration); */
  /*     x->x_stream_data_date = cur_date; */

  /* g_print ("rate %d, channels %d, width %d num sample=%d\n", */
  /* 	    samplerate,  */
  /* 	    channels,  */
  /* 	    width,  */
  /* 	    data_size / ((width/8) *channels));  */

  //converting to float
  audio_buf->free_audio_data = FALSE;
  audio_buf->audio_data = (t_float *)data;
  if (width == 16)
    {
      //g_print ("converting\n");
      audio_buf->free_audio_data = TRUE;
      t_float *audio_converted =  g_malloc0 (sizeof (t_float) 
					     * audio_buf->num_channels_in_buf 
					     * audio_buf->remaining_samples);
      audio_buf->audio_data = audio_converted;
      
      int n = channels *  audio_buf->remaining_samples;
      while (n--)
	{
	  *audio_converted++ = (t_float)(*(gint16 *)data * 3.051850e-05);
	  data += sizeof(gint16); 
	}
    }
  else if (width == 8)
    {
      post ("8 bit audio not supported yet");
      shmdata_any_reader_free (shmbuf);
      return;
    }
  
  audio_buf->current_pos = audio_buf->audio_data;
  g_async_queue_push (x->x_audio_queue, audio_buf);
}
コード例 #22
0
ファイル: darktable.c プロジェクト: kael-shipman/darktable
void gui_init(dt_lib_module_t *self)
{
  char filename[PATH_MAX] = { 0 };
  char datadir[PATH_MAX] = { 0 };
  /* initialize ui widgets */
  dt_lib_darktable_t *d = (dt_lib_darktable_t *)g_malloc0(sizeof(dt_lib_darktable_t));
  self->data = (void *)d;

  /* create drawing area */
  self->widget = gtk_event_box_new();

  /* connect callbacks */
  g_signal_connect(G_OBJECT(self->widget), "draw", G_CALLBACK(_lib_darktable_draw_callback), self);
  g_signal_connect(G_OBJECT(self->widget), "button-press-event",
                   G_CALLBACK(_lib_darktable_button_press_callback), self);

  /* create a cairo surface of dt icon */
  char *logo;
  dt_logo_season_t season = get_logo_season();
  if(season != DT_LOGO_SEASON_NONE)
    logo = g_strdup_printf("%%s/pixmaps/idbutton-%d.%%s", (int)season);
  else
    logo = g_strdup("%s/pixmaps/idbutton.%s");

  dt_loc_get_datadir(datadir, sizeof(datadir));
  snprintf(filename, sizeof(filename), logo, datadir, "svg");

  // first we try the SVG
  {
    GError *error = NULL;
    RsvgHandle *svg = rsvg_handle_new_from_file(filename, &error);
    if(!svg || error)
    {
      fprintf(stderr,
              "warning: can't load darktable logo from SVG file `%s', falling back to PNG version\n%s\n",
              filename, error->message);
      g_error_free(error);
      error = NULL;
      goto png_fallback;
    }

    cairo_surface_t *surface;
    cairo_t *cr;

    RsvgDimensionData dimension;
    rsvg_handle_get_dimensions(svg, &dimension);

    int width = DT_PIXEL_APPLY_DPI(dimension.width) * darktable.gui->ppd,
        height = DT_PIXEL_APPLY_DPI(dimension.height) * darktable.gui->ppd;
    int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);

    d->image_buffer = (guint8 *)calloc(stride * height, sizeof(guint8));
    surface
        = dt_cairo_image_surface_create_for_data(d->image_buffer, CAIRO_FORMAT_ARGB32, width, height, stride);
    if(cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS)
    {
      free(d->image_buffer);
      d->image_buffer = NULL;
      g_object_unref(svg);
      fprintf(stderr, "warning: can't load darktable logo from SVG file `%s', falling back to PNG version\n",
              filename);
      goto png_fallback;
    }

    cr = cairo_create(surface);
    cairo_scale(cr, darktable.gui->dpi_factor, darktable.gui->dpi_factor);
    rsvg_handle_render_cairo(svg, cr);
    cairo_destroy(cr);
    cairo_surface_flush(surface);

    d->image = surface;
    g_object_unref(svg);
  }

  goto done;

png_fallback:
  // let's fall back to the PNG
  {
    cairo_surface_t *surface;
    cairo_t *cr;

    snprintf(filename, sizeof(filename), logo, datadir, "png");
    surface = cairo_image_surface_create_from_png(filename);
    if(cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS)
    {
      fprintf(stderr, "warning: can't load darktable logo from PNG file `%s'\n", filename);
      d->image = NULL;
      goto done;
    }
    int png_width = cairo_image_surface_get_width(surface),
        png_height = cairo_image_surface_get_height(surface);

    // blow up the PNG. Ugly, but at least it has the correct size afterwards :-/
    int width = DT_PIXEL_APPLY_DPI(png_width) * darktable.gui->ppd,
        height = DT_PIXEL_APPLY_DPI(png_height) * darktable.gui->ppd;
    int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);

    d->image_buffer = (guint8 *)calloc(stride * height, sizeof(guint8));
    d->image
        = dt_cairo_image_surface_create_for_data(d->image_buffer, CAIRO_FORMAT_ARGB32, width, height, stride);
    if(cairo_surface_status(d->image) != CAIRO_STATUS_SUCCESS)
    {
      free(d->image_buffer);
      d->image_buffer = NULL;
      cairo_surface_destroy(surface);
      fprintf(stderr, "warning: can't load darktable logo from PNG file `%s'\n", filename);
      d->image = NULL;
      goto done;
    }

    cr = cairo_create(d->image);
    cairo_rectangle(cr, 0, 0, width, height);
    cairo_scale(cr, darktable.gui->dpi_factor, darktable.gui->dpi_factor);
    cairo_set_source_surface(cr, surface, 0, 0);
    cairo_fill(cr);
    cairo_destroy(cr);
    cairo_surface_flush(d->image);

    cairo_surface_destroy(surface);
  }

done:
  g_free(logo);

  d->image_width = d->image ? dt_cairo_image_surface_get_width(d->image) : 0;
  d->image_height = d->image ? dt_cairo_image_surface_get_height(d->image) : 0;

  /* set size of drawing area */
  gtk_widget_set_size_request(self->widget, d->image_width + (int)DT_PIXEL_APPLY_DPI(180),
                              d->image_height + (int)DT_PIXEL_APPLY_DPI(8));
}
コード例 #23
0
ファイル: attribute.c プロジェクト: smartfood2013/dia
static DiaObject *attribute_load(ObjectNode obj_node, int version,DiaContext *ctx)
{
  Attribute *attribute;
  Element *elem;
  DiaObject *obj;
  int i;
  AttributeNode attr;

  attribute = g_malloc0(sizeof(Attribute));
  elem = &attribute->element;
  obj = &elem->object;
  
  obj->type = &attribute_type;
  obj->ops = &attribute_ops;

  element_load(elem, obj_node, ctx);

  attribute->border_width = 0.1;
  attr = object_find_attribute(obj_node, "border_width");
  if (attr != NULL)
    attribute->border_width =  data_real(attribute_first_data(attr), ctx);

  attribute->border_color = color_black;
  attr = object_find_attribute(obj_node, "border_color");
  if (attr != NULL)
    data_color(attribute_first_data(attr), &attribute->border_color, ctx);
  
  attribute->inner_color = color_white;
  attr = object_find_attribute(obj_node, "inner_color");
  if (attr != NULL)
    data_color(attribute_first_data(attr), &attribute->inner_color, ctx);
  
  attribute->name = NULL;
  attr = object_find_attribute(obj_node, "name");
  if (attr != NULL)
    attribute->name = data_string(attribute_first_data(attr), ctx);

  attr = object_find_attribute(obj_node, "key");
  if (attr != NULL)
    attribute->key = data_boolean(attribute_first_data(attr), ctx);

  attr = object_find_attribute(obj_node, "weak_key");
  if (attr != NULL)
    attribute->weakkey = data_boolean(attribute_first_data(attr), ctx);
  
  attr = object_find_attribute(obj_node, "derived");
  if (attr != NULL)
    attribute->derived = data_boolean(attribute_first_data(attr), ctx);

  attr = object_find_attribute(obj_node, "multivalued");
  if (attr != NULL)
    attribute->multivalue = data_boolean(attribute_first_data(attr), ctx);

  if (attribute->font != NULL) {
    /* This shouldn't happen, but doesn't hurt */
    dia_font_unref(attribute->font);
    attribute->font = NULL;
  }
  attr = object_find_attribute (obj_node, "font");
  if (attr != NULL)
    attribute->font = data_font (attribute_first_data (attr), ctx);

  attribute->font_height = FONT_HEIGHT;
  attr = object_find_attribute (obj_node, "font_height");
  if (attr != NULL)
    attribute->font_height = data_real(attribute_first_data(attr), ctx);

  element_init(elem, 8, NUM_CONNECTIONS);

  for (i=0;i<NUM_CONNECTIONS;i++) {
    obj->connections[i] = &attribute->connections[i];
    attribute->connections[i].object = obj;
    attribute->connections[i].connected = NULL;
  }
  attribute->connections[8].flags = CP_FLAGS_MAIN;

  if (attribute->font == NULL)
    attribute->font = dia_font_new_from_style(DIA_FONT_MONOSPACE,
                                              attribute->font_height);

  attribute->name_width = dia_font_string_width(attribute->name,
                                                attribute->font,
                                                attribute->font_height);
  attribute_update_data(attribute);

  for (i=0;i<8;i++)
    obj->handles[i]->type = HANDLE_NON_MOVABLE;

  return &attribute->element.object;
}
コード例 #24
0
ファイル: mips_r4k.c プロジェクト: 8tab/qemu
static
void mips_r4k_init(MachineState *machine)
{
    ram_addr_t ram_size = machine->ram_size;
    const char *cpu_model = machine->cpu_model;
    const char *kernel_filename = machine->kernel_filename;
    const char *kernel_cmdline = machine->kernel_cmdline;
    const char *initrd_filename = machine->initrd_filename;
    char *filename;
    MemoryRegion *address_space_mem = get_system_memory();
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    MemoryRegion *bios;
    MemoryRegion *iomem = g_new(MemoryRegion, 1);
    MemoryRegion *isa_io = g_new(MemoryRegion, 1);
    MemoryRegion *isa_mem = g_new(MemoryRegion, 1);
    int bios_size;
    MIPSCPU *cpu;
    CPUMIPSState *env;
    ResetData *reset_info;
    int i;
    qemu_irq *i8259;
    ISABus *isa_bus;
    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];
    DriveInfo *dinfo;
    int be;

    /* init CPUs */
    if (cpu_model == NULL) {
#ifdef TARGET_MIPS64
        cpu_model = "R4000";
#else
        cpu_model = "24Kf";
#endif
    }
    cpu = cpu_mips_init(cpu_model);
    if (cpu == NULL) {
        fprintf(stderr, "Unable to find CPU definition\n");
        exit(1);
    }
    env = &cpu->env;

    reset_info = g_malloc0(sizeof(ResetData));
    reset_info->cpu = cpu;
    reset_info->vector = env->active_tc.PC;
    qemu_register_reset(main_cpu_reset, reset_info);

    /* allocate RAM */
    if (ram_size > (256 << 20)) {
        fprintf(stderr,
                "qemu: Too much memory for this machine: %d MB, maximum 256 MB\n",
                ((unsigned int)ram_size / (1 << 20)));
        exit(1);
    }
    memory_region_allocate_system_memory(ram, NULL, "mips_r4k.ram", ram_size);

    memory_region_add_subregion(address_space_mem, 0, ram);

    memory_region_init_io(iomem, NULL, &mips_qemu_ops, NULL, "mips-qemu", 0x10000);
    memory_region_add_subregion(address_space_mem, 0x1fbf0000, iomem);

    /* Try to load a BIOS image. If this fails, we continue regardless,
       but initialize the hardware ourselves. When a kernel gets
       preloaded we also initialize the hardware, since the BIOS wasn't
       run. */
    if (bios_name == NULL)
        bios_name = BIOS_FILENAME;
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
    if (filename) {
        bios_size = get_image_size(filename);
    } else {
        bios_size = -1;
    }
#ifdef TARGET_WORDS_BIGENDIAN
    be = 1;
#else
    be = 0;
#endif
    if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) {
        bios = g_new(MemoryRegion, 1);
        memory_region_init_ram(bios, NULL, "mips_r4k.bios", BIOS_SIZE,
                               &error_fatal);
        memory_region_set_readonly(bios, true);
        memory_region_add_subregion(get_system_memory(), 0x1fc00000, bios);

        load_image_targphys(filename, 0x1fc00000, BIOS_SIZE);
    } else if ((dinfo = drive_get(IF_PFLASH, 0, 0)) != NULL) {
        uint32_t mips_rom = 0x00400000;
        if (!pflash_cfi01_register(0x1fc00000, NULL, "mips_r4k.bios", mips_rom,
                                   blk_by_legacy_dinfo(dinfo),
                                   sector_len, mips_rom / sector_len,
                                   4, 0, 0, 0, 0, be)) {
            fprintf(stderr, "qemu: Error registering flash memory.\n");
	}
    } else if (!qtest_enabled()) {
	/* not fatal */
        fprintf(stderr, "qemu: Warning, could not load MIPS bios '%s'\n",
		bios_name);
    }
    g_free(filename);

    if (kernel_filename) {
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        reset_info->vector = load_kernel();
    }

    /* Init CPU internal devices */
    cpu_mips_irq_init_cpu(cpu);
    cpu_mips_clock_init(cpu);

    /* ISA bus: IO space at 0x14000000, mem space at 0x10000000 */
    memory_region_init_alias(isa_io, NULL, "isa-io",
                             get_system_io(), 0, 0x00010000);
    memory_region_init(isa_mem, NULL, "isa-mem", 0x01000000);
    memory_region_add_subregion(get_system_memory(), 0x14000000, isa_io);
    memory_region_add_subregion(get_system_memory(), 0x10000000, isa_mem);
    isa_bus = isa_bus_new(NULL, isa_mem, get_system_io(), &error_abort);

    /* The PIC is attached to the MIPS CPU INT0 pin */
    i8259 = i8259_init(isa_bus, env->irq[2]);
    isa_bus_irqs(isa_bus, i8259);

    rtc_init(isa_bus, 2000, NULL);

    pit = pit_init(isa_bus, 0x40, 0, NULL);

    serial_hds_isa_init(isa_bus, 0, MAX_SERIAL_PORTS);

    isa_vga_init(isa_bus);

    if (nd_table[0].used)
        isa_ne2000_init(isa_bus, 0x300, 9, &nd_table[0]);

    ide_drive_get(hd, ARRAY_SIZE(hd));
    for(i = 0; i < MAX_IDE_BUS; i++)
        isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i], ide_irq[i],
                     hd[MAX_IDE_DEVS * i],
		     hd[MAX_IDE_DEVS * i + 1]);

    isa_create_simple(isa_bus, "i8042");
}
コード例 #25
0
ファイル: pc_piix.c プロジェクト: Distrotech/qemu
/* PC hardware initialisation */
static void pc_init1(MachineState *machine,
                     const char *host_type, const char *pci_type)
{
    PCMachineState *pcms = PC_MACHINE(machine);
    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);
    MemoryRegion *system_memory = get_system_memory();
    MemoryRegion *system_io = get_system_io();
    int i;
    PCIBus *pci_bus;
    ISABus *isa_bus;
    PCII440FXState *i440fx_state;
    int piix3_devfn = -1;
    qemu_irq *gsi;
    qemu_irq *i8259;
    qemu_irq smi_irq;
    GSIState *gsi_state;
    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];
    BusState *idebus[MAX_IDE_BUS];
    ISADevice *rtc_state;
    MemoryRegion *ram_memory;
    MemoryRegion *pci_memory;
    MemoryRegion *rom_memory;
    PcGuestInfo *guest_info;
    ram_addr_t lowmem;

    /* Check whether RAM fits below 4G (leaving 1/2 GByte for IO memory).
     * If it doesn't, we need to split it in chunks below and above 4G.
     * In any case, try to make sure that guest addresses aligned at
     * 1G boundaries get mapped to host addresses aligned at 1G boundaries.
     * For old machine types, use whatever split we used historically to avoid
     * breaking migration.
     */
    if (machine->ram_size >= 0xe0000000) {
        lowmem = pcmc->gigabyte_align ? 0xc0000000 : 0xe0000000;
    } else {
        lowmem = 0xe0000000;
    }

    /* Handle the machine opt max-ram-below-4g.  It is basically doing
     * min(qemu limit, user limit).
     */
    if (lowmem > pcms->max_ram_below_4g) {
        lowmem = pcms->max_ram_below_4g;
        if (machine->ram_size - lowmem > lowmem &&
            lowmem & ((1ULL << 30) - 1)) {
            error_report("Warning: Large machine and max_ram_below_4g(%"PRIu64
                         ") not a multiple of 1G; possible bad performance.",
                         pcms->max_ram_below_4g);
        }
    }

    if (machine->ram_size >= lowmem) {
        pcms->above_4g_mem_size = machine->ram_size - lowmem;
        pcms->below_4g_mem_size = lowmem;
    } else {
        pcms->above_4g_mem_size = 0;
        pcms->below_4g_mem_size = machine->ram_size;
    }

    if (xen_enabled()) {
        xen_hvm_init(pcms, &ram_memory);
    }

    pc_cpus_init(pcms);

    if (kvm_enabled() && pcmc->kvmclock_enabled) {
        kvmclock_create();
    }

    if (pcmc->pci_enabled) {
        pci_memory = g_new(MemoryRegion, 1);
        memory_region_init(pci_memory, NULL, "pci", UINT64_MAX);
        rom_memory = pci_memory;
    } else {
        pci_memory = NULL;
        rom_memory = system_memory;
    }

    guest_info = pc_guest_info_init(pcms);

    guest_info->has_acpi_build = pcmc->has_acpi_build;
    guest_info->legacy_acpi_table_size = pcmc->legacy_acpi_table_size;

    guest_info->isapc_ram_fw = !pcmc->pci_enabled;
    guest_info->has_reserved_memory = pcmc->has_reserved_memory;
    guest_info->rsdp_in_ram = pcmc->rsdp_in_ram;

    if (pcmc->smbios_defaults) {
        MachineClass *mc = MACHINE_GET_CLASS(machine);
        /* These values are guest ABI, do not change */
        smbios_set_defaults("QEMU", "Standard PC (i440FX + PIIX, 1996)",
                            mc->name, pcmc->smbios_legacy_mode,
                            pcmc->smbios_uuid_encoded,
                            SMBIOS_ENTRY_POINT_21);
    }

    /* allocate ram and load rom/bios */
    if (!xen_enabled()) {
        pc_memory_init(pcms, system_memory,
                       rom_memory, &ram_memory, guest_info);
    } else if (machine->kernel_filename != NULL) {
        /* For xen HVM direct kernel boot, load linux here */
        xen_load_linux(pcms, guest_info);
    }

    gsi_state = g_malloc0(sizeof(*gsi_state));
    if (kvm_ioapic_in_kernel()) {
        kvm_pc_setup_irq_routing(pcmc->pci_enabled);
        gsi = qemu_allocate_irqs(kvm_pc_gsi_handler, gsi_state,
                                 GSI_NUM_PINS);
    } else {
        gsi = qemu_allocate_irqs(gsi_handler, gsi_state, GSI_NUM_PINS);
    }

    if (pcmc->pci_enabled) {
        pci_bus = i440fx_init(host_type,
                              pci_type,
                              &i440fx_state, &piix3_devfn, &isa_bus, gsi,
                              system_memory, system_io, machine->ram_size,
                              pcms->below_4g_mem_size,
                              pcms->above_4g_mem_size,
                              pci_memory, ram_memory);
        pcms->bus = pci_bus;
    } else {
        pci_bus = NULL;
        i440fx_state = NULL;
        isa_bus = isa_bus_new(NULL, get_system_memory(), system_io,
                              &error_abort);
        no_hpet = 1;
    }
    isa_bus_irqs(isa_bus, gsi);

    if (kvm_pic_in_kernel()) {
        i8259 = kvm_i8259_init(isa_bus);
    } else if (xen_enabled()) {
        i8259 = xen_interrupt_controller_init();
    } else {
        i8259 = i8259_init(isa_bus, pc_allocate_cpu_irq());
    }

    for (i = 0; i < ISA_NUM_IRQS; i++) {
        gsi_state->i8259_irq[i] = i8259[i];
    }
    g_free(i8259);
    if (pcmc->pci_enabled) {
        ioapic_init_gsi(gsi_state, "i440fx");
    }

    pc_register_ferr_irq(gsi[13]);

    pc_vga_init(isa_bus, pcmc->pci_enabled ? pci_bus : NULL);

    assert(pcms->vmport != ON_OFF_AUTO__MAX);
    if (pcms->vmport == ON_OFF_AUTO_AUTO) {
        pcms->vmport = xen_enabled() ? ON_OFF_AUTO_OFF : ON_OFF_AUTO_ON;
    }

    /* init basic PC hardware */
    pc_basic_device_init(isa_bus, gsi, &rtc_state, true,
                         (pcms->vmport != ON_OFF_AUTO_ON), 0x4);

    pc_nic_init(isa_bus, pci_bus);

    ide_drive_get(hd, ARRAY_SIZE(hd));
    if (pcmc->pci_enabled) {
        PCIDevice *dev;
        if (xen_enabled()) {
            dev = pci_piix3_xen_ide_init(pci_bus, hd, piix3_devfn + 1);
        } else {
            dev = pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);
        }
        idebus[0] = qdev_get_child_bus(&dev->qdev, "ide.0");
        idebus[1] = qdev_get_child_bus(&dev->qdev, "ide.1");
    } else {
        for(i = 0; i < MAX_IDE_BUS; i++) {
            ISADevice *dev;
            char busname[] = "ide.0";
            dev = isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i],
                               ide_irq[i],
                               hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);
            /*
             * The ide bus name is ide.0 for the first bus and ide.1 for the
             * second one.
             */
            busname[4] = '0' + i;
            idebus[i] = qdev_get_child_bus(DEVICE(dev), busname);
        }
    }

    pc_cmos_init(pcms, idebus[0], idebus[1], rtc_state);

    if (pcmc->pci_enabled && usb_enabled()) {
        pci_create_simple(pci_bus, piix3_devfn + 2, "piix3-usb-uhci");
    }

    if (pcmc->pci_enabled && acpi_enabled) {
        DeviceState *piix4_pm;
        I2CBus *smbus;

        smi_irq = qemu_allocate_irq(pc_acpi_smi_interrupt, first_cpu, 0);
        /* TODO: Populate SPD eeprom data.  */
        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,
                              gsi[9], smi_irq,
                              pc_machine_is_smm_enabled(pcms),
                              &piix4_pm);
        smbus_eeprom_init(smbus, 8, NULL, 0);

        object_property_add_link(OBJECT(machine), PC_MACHINE_ACPI_DEVICE_PROP,
                                 TYPE_HOTPLUG_HANDLER,
                                 (Object **)&pcms->acpi_dev,
                                 object_property_allow_set_link,
                                 OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort);
        object_property_set_link(OBJECT(machine), OBJECT(piix4_pm),
                                 PC_MACHINE_ACPI_DEVICE_PROP, &error_abort);
    }

    if (pcmc->pci_enabled) {
        pc_pci_device_init(pci_bus);
    }
}
コード例 #26
0
ファイル: gstreamer_io_peer.c プロジェクト: 0day-ci/gcc
static jboolean process_audio (GstElement *source, JNIEnv *env, jobject header)
{
  /* will contain the properties we need to put into the given GstHeader */
  AudioProperties *properties = NULL;
  
  /* GStreamer elements */
  GstElement *pipeline = NULL;
  GstElement *decoder = NULL;
  
  GstElement *typefind = NULL;
  
  GstStateChangeReturn res;

  jboolean result = JNI_FALSE;
  
  properties = (AudioProperties *) g_malloc0 (sizeof (AudioProperties));
  if (properties == NULL)
    {
      return result;
    }
  reset_properties(properties);

  /* 
   * create the decoder element, this will decode the stream and retrieve
   * its properties.
   * We connect a signal to this element, to be informed when it is done
   * in decoding the stream and to get the needed informations about the
   * audio file.
   */
  decoder = gst_element_factory_make ("decodebin", "decoder");
  if (decoder == NULL)
    {
      free_properties(properties);
      return result;
    }
  
  /* now, we create a pipeline and fill it with the other elements */
  pipeline = gst_pipeline_new ("pipeline");
  if (pipeline == NULL)
    {
      gst_object_unref (GST_OBJECT (decoder));
      free_properties(properties);   
      return result;
    }
 
  g_signal_connect (decoder, "new-decoded-pad", G_CALLBACK (new_decoded_pad),
                    pipeline);
  g_signal_connect (G_OBJECT (decoder), "element-added",
                    G_CALLBACK (element_added), properties);
  
  /*
   * we get the typefind from the decodebin to catch the additional properties
   * that the decodebin does not expose to us
   */
  typefind = gst_bin_get_by_name (GST_BIN (decoder), "typefind");
  if (typefind != NULL)
    {
      /* 
       * NOTE: the above is not a typo, we can live without the typefind,
       * just, our stream detection will not be as accurate as we would.
       * Anyway, if this fails, there is some problem, probabily a memory
       * error.
       */
       g_signal_connect (G_OBJECT (typefind), "have-type",
                         G_CALLBACK (typefind_callback), properties);
    }
  
  gst_bin_add_many (GST_BIN (pipeline), source, decoder, NULL);
  gst_element_link (source, decoder);
  
  /* 
   * now, we set the pipeline playing state to pause and traverse it
   * to get the info we need.
   */
   
  res = gst_element_set_state (pipeline, GST_STATE_PAUSED);
  if (res == GST_STATE_CHANGE_FAILURE)
    {
      gst_element_set_state (pipeline, GST_STATE_NULL);
      gst_object_unref (GST_OBJECT (pipeline));
      
      free_properties(properties);
      
      return result;
    }
  
  res = gst_element_get_state (pipeline, NULL, NULL, GST_CLOCK_TIME_NONE);
  if (res != GST_STATE_CHANGE_SUCCESS)
    {
      gst_element_set_state (pipeline, GST_STATE_NULL);
      gst_object_unref (GST_OBJECT (pipeline));
      
      free_properties(properties);
      
      return result;
    }
  
  if (fill_info (decoder, properties))
    {
      result = set_strings (env, properties, header);
    }
 
  /* free stuff */
  gst_element_set_state (pipeline, GST_STATE_NULL);
   
  free_properties (properties);
  
  gst_object_unref (GST_OBJECT (pipeline));
 
  return result;
}
コード例 #27
0
ファイル: stats_tree.c プロジェクト: ARK1988/wireshark
/* Internal function to update the burst calculation data - add entry to bucket */
static void
update_burst_calc(stat_node *node, gint value)
{
    double current_bucket;
    double burstwin;

    burst_bucket *bn;

    if (!prefs.st_enable_burstinfo) {
        return;
    }

    /* NB thebucket list should always contain at least one node - even if it is */
    /* the dummy created at init time. Head and tail should never be NULL!       */
    current_bucket= floor(node->st->now/prefs.st_burst_resolution);
    burstwin= prefs.st_burst_windowlen/prefs.st_burst_resolution;
    if (current_bucket>node->bt->bucket_no) {
        /* Must add a new bucket at the burst list tail */
        bn = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
        bn->count = value;
        bn->bucket_no = current_bucket;
        bn->start_time = node->st->now;
        bn->prev = node->bt;
        node->bt->next = bn;
        node->bt = bn;
        /* And add value to the current burst count for node */
        node->bcount += value;
        /* Check if bucket list head is now too old and must be removed */
        while (current_bucket>=(node->bh->bucket_no+burstwin)) {
            /* off with its head! */
            bn = node->bh;
            node->bh = bn->next;
            node->bh->prev = NULL;
            node->bcount -= bn->count;
            g_free(bn);
        }
    }
    else if (current_bucket<node->bh->bucket_no) {
        /* Packet must be added at head of burst list - check if not too old */
        if ((current_bucket+burstwin)>node->bt->bucket_no) {
            /* packet still within the window */
            bn = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
            bn->count = value;
            bn->bucket_no = current_bucket;
            bn->start_time = node->st->now;
            bn->next = node->bh;
            node->bh->prev = bn;
            node->bh = bn;
            /* And add value to the current burst count for node */
            node->bcount += value;
        }
    }
    else
    {
        /* Somewhere in the middle... */
        burst_bucket *search = node->bt;
        while (current_bucket<search->bucket_no) {
            search = search->prev;
        }
        if (current_bucket==search->bucket_no) {
            /* found existing bucket, increase value */
            search->count += value;
            if (search->start_time>node->st->now) {
                search->start_time = node->st->now;
            }
        }
        else {
            /* must add a new bucket after bn. */
            bn = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
            bn->count = value;
            bn->bucket_no = current_bucket;
            bn->start_time = node->st->now;
            bn->prev = search;
            bn->next = search->next;
            search->next = bn;
            bn->next->prev = bn;
        }
        node->bcount += value;
    }
    if (node->bcount>node->max_burst) {
        /* new record burst */
        node->max_burst = node->bcount;
        node->burst_time = node->bh->start_time;
    }
}
コード例 #28
0
ファイル: dummypotparallel.c プロジェクト: pigay/aran
int main (int argc, char **argv)
{
#ifdef VSG_HAVE_MPI
  VsgPRTreeParallelConfig pconfig = {{NULL,}};
#endif

  VsgVector2d lbound = {-1., -1.};
  VsgVector2d ubound = {1., 1.};
  VsgPRTree2d *prtree;
  AranSolver2d *solver;
  int ret = 0;
  guint i;
  GTimer *timer = NULL;

#ifdef VSG_HAVE_MPI
  MPI_Init (&argc, &argv);

  MPI_Comm_size (MPI_COMM_WORLD, &sz);
  MPI_Comm_rank (MPI_COMM_WORLD, &rk);
#endif

  aran_init();

  parse_args (argc, argv);

#ifdef VSG_HAVE_MPI
  pconfig.communicator = MPI_COMM_WORLD;

  pconfig.point = point_accum_vtable;

  aran_development2d_vtable_init (&pconfig.node_data, 0, order);
#endif

  points = g_ptr_array_new ();

  if (check)
    check_points = g_malloc0 (np * sizeof (PointAccum));

  prtree = 
    vsg_prtree2d_new_full (&lbound, &ubound,
			    (VsgPoint2dLocFunc) vsg_vector2d_vector2d_locfunc,
			    (VsgPoint2dDistFunc) vsg_vector2d_dist,
			    (VsgRegion2dLocFunc) NULL, maxbox);

  aran_binomial_require (2*order);

  solver = aran_solver2d_new (prtree, ARAN_TYPE_DEVELOPMENT2D,
			      aran_development2d_new (0, order),
			      (AranZeroFunc) aran_development2d_set_zero);

#ifdef VSG_HAVE_MPI
  aran_solver2d_set_parallel (solver, &pconfig);
#endif

  if (virtual_maxbox != 0)
    aran_solver2d_set_nf_isleaf (solver, _nf_isleaf_virtual_maxbox,
                                 &virtual_maxbox);

  aran_solver2d_set_functions (solver,
			       (AranParticle2ParticleFunc2d) p2p,
			       (AranParticle2MultipoleFunc2d) p2m,
			       (AranMultipole2MultipoleFunc2d) aran_development2d_m2m,
			       (AranMultipole2LocalFunc2d) aran_development2d_m2l,
			       (AranLocal2LocalFunc2d) aran_development2d_l2l,
			       (AranLocal2ParticleFunc2d)l2p);

  if (semifar_threshold < G_MAXUINT)
    {
      aran_solver2d_set_functions_full (solver,
                                        (AranParticle2ParticleFunc2d) p2p,
                                        (AranParticle2MultipoleFunc2d) p2m,
                                        (AranMultipole2MultipoleFunc2d) aran_development2d_m2m,
                                        (AranMultipole2LocalFunc2d) aran_development2d_m2l,
                                        (AranLocal2LocalFunc2d) aran_development2d_l2l,
                                        (AranLocal2ParticleFunc2d) l2p,
                                        (AranParticle2LocalFunc2d) p2l,
                                        (AranMultipole2ParticleFunc2d) m2p,
                                        semifar_threshold);

      if (semifar_threshold == 0)
        {
          PointAccum p1 = {{0.1, 0.1}, 0.1, 0., 0};
          PointAccum p2 = {{-0.1, -0.1}, 0.1, 0., 1};

          /* compute operators timings to be able to compute optimal solver parameters */
          aran_solver2d_profile_operators (solver, (AranParticleInitFunc2d) point_accum_clear_accum,
                                           &p1, &p2);

          /* alternatively, we could get timings from profile databases */
          /* aran_profile_db_read_file ("./profiledb-newtonfield3.ini", NULL); */
          /* aran_solver2d_db_profile_operators (solver, (gdouble) order); */

        }

      
    }
  if (_hilbert)
    {
      /* configure for hilbert curve order traversal */
      aran_solver2d_set_children_order_hilbert (solver);
    }

  _distribution (points, solver);

  if (_verbose)
    {
      g_printerr ("%d : solve begin\n", rk);

#ifdef VSG_HAVE_MPI
      MPI_Barrier (MPI_COMM_WORLD);
#endif

      timer = g_timer_new ();
    }

  aran_solver2d_solve (solver);

  if (_verbose)
    {
#ifdef VSG_HAVE_MPI
      MPI_Barrier (MPI_COMM_WORLD);
#endif

      g_printerr ("%d : solve ok elapsed=%f seconds\n", rk,
                  g_timer_elapsed (timer, NULL));

      g_timer_destroy (timer);
    }

  if (check)
    {
      if (sz == 1)
        {
          for (i=0; i<np; i++)
            {
              PointAccum *pi = &check_points[i];
              guint j;

              for (j=0; j<np; j++)
                {
                  if (i != j)
                    {
                      PointAccum *pj = &check_points[j];
                      gcomplex128 zd_m_zs =
                        (pi->vector.x + I*pi->vector.y) -
                        (pj->vector.x + I*pj->vector.y);

                      pi->accum += 1./zd_m_zs * pj->density;
                    }
                }
            }
        }
      else
        check_parallel_points (solver);

      aran_solver2d_foreach_point (solver, (GFunc) check_point_accum, &ret);

      if (_verbose)
        g_printerr ("%d : max err = %e\n", rk, maxerr);

      g_free (check_points);
    }

  aran_solver2d_free (solver);

#ifdef VSG_HAVE_MPI
  aran_development2d_vtable_clear (&pconfig.node_data);
#endif

  /* destroy the points */
  g_ptr_array_foreach (points, empty_array, NULL);
  g_ptr_array_free (points, TRUE);

#ifdef VSG_HAVE_MPI
  MPI_Finalize ();
#endif

  return ret;
}
コード例 #29
0
ファイル: tree.c プロジェクト: GCrean/sitecopy
GNode *build_tree_from_site(struct site *a_site)
{

    GNode *tree_root;
    struct site_node_data *tmp;
    struct site_file *current_dir, *current_file;
    
    NE_DEBUG(DEBUG_GNOME, "Called build_tree_from_site for site, %s.\n",
	  a_site->name);

    /* If this site isn't perfect, then don't try and scan the directory.
     */
    /*{
      int ret = rc_verifysite(a_site);
      if ((ret == SITE_NOLOCALDIR) || (ret == SITE_ACCESSLOCALDIR))
	return NULL;
    }*/
    
    tmp = g_malloc0(sizeof(struct site_node_data));
    tmp->name = "ROOT";

    /* Create the root node. */
    tree_root = g_node_new(tmp);

    /* For each dir in site->files, blah... */
    NE_DEBUG(DEBUG_GNOME, "Created root node, about to enter directory loop...\n");

    /* This is not very time efficient, but I'm not the one that dictates the
       * ordering of files/directories, so don't blame me.
       * What we do here is create all the directory nodes first (and the
       * directory nodes _only_), and then add the files once the dirs are known
       * to be in place.
     */
    for (current_dir = a_site->files_tail;
	 (current_dir) && (current_dir->type == file_dir);
	 current_dir = current_dir->prev)
      ;

    /* There! SPLAT! Got you, you little bastard of a bug. */
/*    if (!current_dir)
      return tree_root;*/

    if (current_dir) 
      {
	  for (current_dir = current_dir->next; 
	       current_dir;
	       current_dir = current_dir->next)
	    {
		core_tree_building_function(current_dir, tree_root);
	    }
      }
    

    for (current_file = a_site->files;
	 (current_file) && (current_file->type != file_dir);
	 current_file = current_file->next) {
	core_tree_building_function(current_file, tree_root);
    }

    /* FIXME: do files here somehow? */
    return tree_root;
}
コード例 #30
0
ファイル: syntax.c プロジェクト: GarothLongint/mc
static int
edit_read_syntax_rules (WEdit * edit, FILE * f, char **args, int args_size)
{
    FILE *g = NULL;
    char *fg, *bg, *attrs;
    char last_fg[32] = "", last_bg[32] = "", last_attrs[64] = "";
    char whole_right[512];
    char whole_left[512];
    char *l = 0;
    int save_line = 0, line = 0;
    struct context_rule **r, *c = NULL;
    int num_words = -1, num_contexts = -1;
    int result = 0;
    int alloc_contexts = MAX_CONTEXTS,
        alloc_words_per_context = MAX_WORDS_PER_CONTEXT,
        max_alloc_words_per_context = MAX_WORDS_PER_CONTEXT;

    args[0] = NULL;
    edit->is_case_insensitive = FALSE;

    strcpy (whole_left, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_01234567890");
    strcpy (whole_right, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_01234567890");

    r = edit->rules = g_malloc0 (alloc_contexts * sizeof (struct context_rule *));

    if (!edit->defines)
        edit->defines = g_tree_new ((GCompareFunc) strcmp);

    while (TRUE)
    {
        char **a;
        size_t len;
        int argc;

        line++;
        l = 0;

        len = read_one_line (&l, f);
        if (len != 0)
            xx_lowerize_line (edit, l, len);
        else
        {
            if (g == NULL)
                break;

            fclose (f);
            f = g;
            g = NULL;
            line = save_line + 1;
            MC_PTR_FREE (error_file_name);
            MC_PTR_FREE (l);
            len = read_one_line (&l, f);
            if (len == 0)
                break;
            xx_lowerize_line (edit, l, len);
        }

        argc = get_args (l, args, args_size);
        a = args + 1;
        if (args[0] == NULL)
        {
            /* do nothing */
        }
        else if (strcmp (args[0], "include") == 0)
        {
            if (g != NULL || argc != 2)
            {
                result = line;
                break;
            }
            g = f;
            f = open_include_file (args[1]);
            if (f == NULL)
            {
                MC_PTR_FREE (error_file_name);
                result = line;
                break;
            }
            save_line = line;
            line = 0;
        }
        else if (strcmp (args[0], "caseinsensitive") == 0)
        {
            edit->is_case_insensitive = TRUE;
        }
        else if (strcmp (args[0], "wholechars") == 0)
        {
            check_a;
            if (strcmp (*a, "left") == 0)
            {
                a++;
                g_strlcpy (whole_left, *a, sizeof (whole_left));
            }
            else if (strcmp (*a, "right") == 0)
            {
                a++;
                g_strlcpy (whole_right, *a, sizeof (whole_right));
            }
            else
            {
                g_strlcpy (whole_left, *a, sizeof (whole_left));
                g_strlcpy (whole_right, *a, sizeof (whole_right));
            }
            a++;
            check_not_a;
        }
        else if (strcmp (args[0], "context") == 0)
        {
            check_a;
            if (num_contexts == -1)
            {
                if (strcmp (*a, "default") != 0)
                {               /* first context is the default */
                    break_a;
                }
                a++;
                c = r[0] = g_malloc0 (sizeof (struct context_rule));
                c->left = g_strdup (" ");
                c->right = g_strdup (" ");
                num_contexts = 0;
            }
            else
            {
                /* Terminate previous context.  */
                r[num_contexts - 1]->keyword[num_words] = NULL;
                c = r[num_contexts] = g_malloc0 (sizeof (struct context_rule));
                if (strcmp (*a, "exclusive") == 0)
                {
                    a++;
                    c->between_delimiters = 1;
                }
                check_a;
                if (strcmp (*a, "whole") == 0)
                {
                    a++;
                    c->whole_word_chars_left = g_strdup (whole_left);
                    c->whole_word_chars_right = g_strdup (whole_right);
                }
                else if (strcmp (*a, "wholeleft") == 0)
                {
                    a++;
                    c->whole_word_chars_left = g_strdup (whole_left);
                }
                else if (strcmp (*a, "wholeright") == 0)
                {
                    a++;
                    c->whole_word_chars_right = g_strdup (whole_right);
                }
                check_a;
                if (strcmp (*a, "linestart") == 0)
                {
                    a++;
                    c->line_start_left = 1;
                }
                check_a;
                c->left = g_strdup (*a++);
                check_a;
                if (strcmp (*a, "linestart") == 0)
                {
                    a++;
                    c->line_start_right = 1;
                }
                check_a;
                c->right = g_strdup (*a++);
                c->first_left = *c->left;
                c->first_right = *c->right;
            }
            c->keyword = g_malloc (alloc_words_per_context * sizeof (struct key_word *));
            num_words = 1;
            c->keyword[0] = g_malloc0 (sizeof (struct key_word));
            subst_defines (edit->defines, a, &args[1024]);
            fg = *a;
            if (*a != '\0')
                a++;
            bg = *a;
            if (*a != '\0')
                a++;
            attrs = *a;
            if (*a != '\0')
                a++;
            g_strlcpy (last_fg, fg != NULL ? fg : "", sizeof (last_fg));
            g_strlcpy (last_bg, bg != NULL ? bg : "", sizeof (last_bg));
            g_strlcpy (last_attrs, attrs != NULL ? attrs : "", sizeof (last_attrs));
            c->keyword[0]->color = this_try_alloc_color_pair (fg, bg, attrs);
            c->keyword[0]->keyword = g_strdup (" ");
            check_not_a;

            alloc_words_per_context = MAX_WORDS_PER_CONTEXT;
            if (++num_contexts >= alloc_contexts)
            {
                struct context_rule **tmp;

                alloc_contexts += 128;
                tmp = g_realloc (r, alloc_contexts * sizeof (struct context_rule *));
                r = tmp;
            }
        }
        else if (strcmp (args[0], "spellcheck") == 0)
        {
            if (c == NULL)
            {
                result = line;
                break;
            }
            c->spelling = TRUE;
        }
        else if (strcmp (args[0], "keyword") == 0)
        {
            struct key_word *k;

            if (num_words == -1)
                break_a;
            check_a;
            k = r[num_contexts - 1]->keyword[num_words] = g_malloc0 (sizeof (struct key_word));
            if (strcmp (*a, "whole") == 0)
            {
                a++;
                k->whole_word_chars_left = g_strdup (whole_left);
                k->whole_word_chars_right = g_strdup (whole_right);
            }
            else if (strcmp (*a, "wholeleft") == 0)
            {
                a++;
                k->whole_word_chars_left = g_strdup (whole_left);
            }
            else if (strcmp (*a, "wholeright") == 0)
            {
                a++;
                k->whole_word_chars_right = g_strdup (whole_right);
            }
            check_a;
            if (strcmp (*a, "linestart") == 0)
            {
                a++;
                k->line_start = 1;
            }
            check_a;
            if (strcmp (*a, "whole") == 0)
            {
                break_a;
            }
            k->keyword = g_strdup (*a++);
            k->first = *k->keyword;
            subst_defines (edit->defines, a, &args[1024]);
            fg = *a;
            if (*a != '\0')
                a++;
            bg = *a;
            if (*a != '\0')
                a++;
            attrs = *a;
            if (*a != '\0')
                a++;
            if (fg == NULL)
                fg = last_fg;
            if (bg == NULL)
                bg = last_bg;
            if (attrs == NULL)
                attrs = last_attrs;
            k->color = this_try_alloc_color_pair (fg, bg, attrs);
            check_not_a;

            if (++num_words >= alloc_words_per_context)
            {
                struct key_word **tmp;

                alloc_words_per_context += 1024;

                if (alloc_words_per_context > max_alloc_words_per_context)
                    max_alloc_words_per_context = alloc_words_per_context;

                tmp = g_realloc (c->keyword, alloc_words_per_context * sizeof (struct key_word *));
                c->keyword = tmp;
            }
        }
        else if (*(args[0]) == '#')
        {
            /* do nothing for comment */
        }
        else if (strcmp (args[0], "file") == 0)
        {
            break;
        }
        else if (strcmp (args[0], "define") == 0)
        {
            char *key = *a++;
            char **argv;

            if (argc < 3)
                break_a;
            argv = g_tree_lookup (edit->defines, key);
            if (argv != NULL)
                mc_defines_destroy (NULL, argv, NULL);
            else
                key = g_strdup (key);

            argv = g_new (char *, argc - 1);
            g_tree_insert (edit->defines, key, argv);
            while (*a != NULL)
                *argv++ = g_strdup (*a++);
            *argv = NULL;
        }
        else
        {                       /* anything else is an error */