예제 #1
0
파일: dcp.c 프로젝트: bgromov/rawstudio
static RSFilterResponse *
get_image(RSFilter *filter, const RSFilterRequest *request)
{
	RSDcp *dcp = RS_DCP(filter);
	RSDcpClass *klass = RS_DCP_GET_CLASS(dcp);
	GdkRectangle *roi;
	RSFilterResponse *previous_response;
	RSFilterResponse *response;
	RS_IMAGE16 *input;
	RS_IMAGE16 *output;
	RS_IMAGE16 *tmp;

	gint j;

	RSFilterRequest *request_clone = rs_filter_request_clone(request);

	if (!dcp->use_profile)
	{
		gfloat premul[4] = {dcp->pre_mul.x, dcp->pre_mul.y, dcp->pre_mul.z, 1.0};
		rs_filter_param_set_float4(RS_FILTER_PARAM(request_clone), "premul", premul);
	}

	rs_filter_param_set_object(RS_FILTER_PARAM(request_clone), "colorspace", klass->prophoto);
	previous_response = rs_filter_get_image(filter->previous, request_clone);
	g_object_unref(request_clone);

	if (!RS_IS_FILTER(filter->previous))
		return previous_response;

	input = rs_filter_response_get_image(previous_response);
	if (!input) return previous_response;
	response = rs_filter_response_clone(previous_response);

	/* We always deliver in ProPhoto */
	rs_filter_param_set_object(RS_FILTER_PARAM(response), "colorspace", klass->prophoto);
	g_object_unref(previous_response);

	if ((roi = rs_filter_request_get_roi(request)))
	{
		/* Align so we start at even pixel counts */
		roi->width += (roi->x&1);
		roi->x -= (roi->x&1);
		roi->width = MIN(input->w - roi->x, roi->width);
		output = rs_image16_copy(input, FALSE);
		tmp = rs_image16_new_subframe(output, roi);
		bit_blt((char*)GET_PIXEL(tmp,0,0), tmp->rowstride * 2, 
			(const char*)GET_PIXEL(input,roi->x,roi->y), input->rowstride * 2, tmp->w * tmp->pixelsize * 2, tmp->h);
	}
	else
	{
		output = rs_image16_copy(input, TRUE);
		tmp = g_object_ref(output);
	}
	g_object_unref(input);
	rs_filter_response_set_image(response, output);
	g_object_unref(output);

	g_static_rec_mutex_lock(&dcp_mutex);
	init_exposure(dcp);

	guint i, y_offset, y_per_thread, threaded_h;
	guint threads = rs_get_number_of_processor_cores();
	if (tmp->h * tmp->w < 200*200)
		threads = 1;

	ThreadInfo *t = g_new(ThreadInfo, threads);

	threaded_h = tmp->h;
	y_per_thread = (threaded_h + threads-1)/threads;
	y_offset = 0;

	for (i = 0; i < threads; i++)
	{
		t[i].tmp = tmp;
		t[i].start_y = y_offset;
		t[i].start_x = 0;
		t[i].dcp = dcp;
		y_offset += y_per_thread;
		y_offset = MIN(tmp->h, y_offset);
		t[i].end_y = y_offset;
		for(j = 0; j < 256; j++)
			t[i].curve_input_values[j] = 0;
		t[i].single_thread = (threads == 1);
		if (threads == 1)
			start_single_dcp_thread(&t[0]);
		else	
			t[i].threadid = g_thread_create(start_single_dcp_thread, &t[i], TRUE, NULL);
	}

	/* Wait for threads to finish */
	for(i = 0; threads > 1 && i < threads; i++)
		g_thread_join(t[i].threadid);

	/* Settings can change now */
	g_static_rec_mutex_unlock(&dcp_mutex);

	/* If we must deliver histogram data, do it now */
	if (dcp->read_out_curve)
	{
		gint *values = g_malloc0(256*sizeof(gint));
		for(i = 0; i < threads; i++)
			for(j = 0; j < 256; j++)
				values[j] += t[i].curve_input_values[j];
		rs_curve_set_histogram_data(RS_CURVE_WIDGET(dcp->read_out_curve), values);
		g_free(values);
	}
	g_free(t);
	g_object_unref(tmp);

	return response;
}
예제 #2
0
void
cometd_loop_gthread_stop(cometd_loop* loop)
{
	g_thread_join(INTERNAL(loop)->thread);
  INTERNAL(loop)->thread = NULL;
}
OBD2Source::~OBD2Source()
{
	DebugOut() << "OBD2Source Destructor called!!!"<<endl;
	m_threadLive = false;
	g_thread_join(m_gThread);
}
예제 #4
0
파일: main.c 프로젝트: simbits/ClaudeGlass
int main (int argc, char *argv[])
{
    GCContext    gc_context;
    GMainLoop   *mainLoop;
    GKeyFile    *keyFile;
    GThread     *displayThread;
    GThread     *inputControllerThread;
    GThread     *x11EventThread;
    int          i;

    
    GCConfig config = {
        .movie_path          = DEFAULT_MOVIE_PATH,
        .mask_path           = DEFAULT_MASK_PATH,
        .controller_path     = DEFAULT_CONTROLLER_PATH,
        .seconds_per_frame   = DEFAULT_SECONDS_PER_FRAME,
        .easing_factor       = DEFAULT_EASING_FACTOR,
        .frames_per_tick     = 0,
        .diameter_controller = 0,
        .diameter_rim        = 0,
        .ctr                 = 0,
        .fpr                 = 0,
        .number_of_frames    = 0,
        .fullscreen          = TRUE,
        .timeZone            = NULL,
    };

    Movie movie = {
        .planes             = NULL,
        .frame_offset       = 0,
        .fd_movie           = -1,
        .frame              = { .pitches = { FRAME_PITCH, 0, 0 } },
        .fd_mask            = -1,
        .mask               = { .pitches = { MASK_PITCH, 0, 0 } },
        .pre_load_surface   = VDP_INVALID_HANDLE,
        .play_direction     = DIRECTION_FORWARD,
        .ticks              = 0,
        .new_frame          = FALSE,
        .ease_to            = TRUE,
    };

    keyFile = g_key_file_new();
    if (argc > 1 && g_key_file_load_from_file(keyFile, argv[1], G_KEY_FILE_NONE, NULL)) {
        if (g_key_file_has_group(keyFile, "MAIN")) {
            if (g_key_file_has_key(keyFile, "MAIN", "utc_offset", NULL))
                config.timeZone = g_time_zone_new(g_key_file_get_string(keyFile, "MAIN", "utc_offset", NULL));
            if (g_key_file_has_key(keyFile, "MAIN", "ease_to_time", NULL))
                movie.ease_to = g_key_file_get_boolean(keyFile, "MAIN", "ease_to_time", NULL);
        }
 
        if (g_key_file_has_group(keyFile, "MOVIE")) {
           if (g_key_file_has_key(keyFile, "MOVIE", "file", NULL))
              config.movie_path = g_key_file_get_string(keyFile, "MOVIE", "file", NULL);
           if (g_key_file_has_key(keyFile, "MOVIE", "mask", NULL))
              config.mask_path = g_key_file_get_string(keyFile, "MOVIE", "mask", NULL);
           if (g_key_file_has_key(keyFile, "MOVIE", "seconds_per_frame", NULL))
              config.seconds_per_frame = (float)g_key_file_get_double(keyFile, "MOVIE", "seconds_per_frame", NULL);
           if (g_key_file_has_key(keyFile, "MOVIE", "easing_factor", NULL))
              config.easing_factor = (float)g_key_file_get_integer(keyFile, "MOVIE", "easing_factor", NULL);
        }
        
        if (g_key_file_has_group(keyFile, "CONTROLLER")) {
           if (g_key_file_has_key(keyFile, "CONTROLLER", "path", NULL))
              config.controller_path = g_key_file_get_string(keyFile, "CONTROLLER", "path", NULL);

           if (g_key_file_has_key(keyFile, "CONTROLLER", "diameter_controller", NULL))
              config.diameter_controller = (float)g_key_file_get_double(keyFile, "CONTROLLER", "diameter_controller", NULL);
           if (g_key_file_has_key(keyFile, "CONTROLLER", "diameter_rim", NULL))
              config.diameter_rim = (float)g_key_file_get_double(keyFile, "CONTROLLER", "diameter_rim", NULL);
           if (g_key_file_has_key(keyFile, "CONTROLLER", "ctr", NULL))
              config.ctr = (float)g_key_file_get_double(keyFile, "CONTROLLER", "ctr", NULL);
           if (g_key_file_has_key(keyFile, "CONTROLLER", "fpr", NULL))
              config.fpr = (float)g_key_file_get_double(keyFile, "CONTROLLER", "fpr", NULL);
           if (g_key_file_has_key(keyFile, "CONTROLLER", "frames_per_tick", NULL))
              config.frames_per_tick = (float)g_key_file_get_double(keyFile, "CONTROLLER", "frames_per_tick", NULL);
        }

        if (g_key_file_has_group(keyFile, "SCREEN")) {
           if (g_key_file_has_key(keyFile, "SCREEN", "fullscreen", NULL))
              config.fullscreen = g_key_file_get_boolean(keyFile, "SCREEN", "fullscreen", NULL);
        }
        g_key_file_free(keyFile);
    }

    if (!config.timeZone)
        config.timeZone = g_time_zone_new_local();

    if (!config.frames_per_tick && 
        !(config.frames_per_tick = frames_per_tick(config.diameter_controller,
                                                   config.diameter_rim,
                                                   config.ctr,
                                                   config.fpr)))
    {
        g_warning("No valid tick settings, using default frames per tick: %f", DEFAULT_FRAMES_PER_TICK);
        config.frames_per_tick = DEFAULT_FRAMES_PER_TICK;
    }

    config.movie_size = get_file_size(config.movie_path);
    config.number_of_frames = config.movie_size / FRAME_SIZE;
    
    mainLoop = g_main_loop_new(NULL, FALSE);

    gc_context.g_main_loop        = mainLoop;
    gc_context.g_main_context     = g_main_loop_get_context(mainLoop);
    gc_context.window_size.width  = MOVIE_WIDTH;
    gc_context.window_size.height = MOVIE_HEIGHT;
    gc_context.exit               = FALSE;
    gc_context.movie_context      = &movie;
    gc_context.config             = &config;


    g_message("movie file: %s",                           config.movie_path);
    g_message("movie size: %lu",                          config.movie_size);
    g_message("movie frames: %lu",                        config.number_of_frames);
    g_message("movie mask file: %s",                      config.mask_path);
    g_message("frames per minute: %f",                    get_frames_per_minute(&gc_context));
    g_message("frames per day:    %lu",                   get_frames_per_day(&gc_context));
    g_message("frames per tick:   %f",                    config.frames_per_tick);
    g_message("number of days:    %d",                    get_number_of_days(&gc_context));
    g_message("current day:       %d",                    get_current_day(&gc_context));

    if (movie.ease_to) {
        movie.ease_to_frame = get_frame_offset(&gc_context, GO_TO_RAND_DAY, DAY_OFFSET_NOW);
        g_message("ease to frame:    %lu", movie.ease_to_frame);
    }

    x11_init(&gc_context);
    vdpau_init(&gc_context);

    load_movie(&gc_context);
    load_mask(&gc_context);

    g_cond_init(&movie.tick_cond);
    g_mutex_init(&movie.tick_lock);
    g_mutex_init(&movie.frame_lock);

    displayThread = g_thread_new("Display thread", display_thread, (gpointer)&gc_context);
    inputControllerThread = g_thread_new("Input controller thread", input_controller_thread, (gpointer)&gc_context);
    x11EventThread = g_thread_new("X11 Event thread", x11_event_thread, (gpointer)&gc_context);

    g_main_loop_run(mainLoop);

    gc_context.exit = TRUE;
    g_thread_join(displayThread); 
    g_thread_join(inputControllerThread); 
    g_thread_join(x11EventThread); 
    g_cond_clear(&movie.tick_cond);
    g_mutex_clear(&movie.tick_lock);
    g_mutex_clear(&movie.frame_lock);
    g_time_zone_unref(config.timeZone);
}
예제 #5
0
파일: main.c 프로젝트: snowasnow/DeSmuME
void
joinThread_gdb( void *thread_handle) {
  g_thread_join( thread_handle);
}
예제 #6
0
static gboolean _check_for_update_idle (GldiTask *pTask)
{
	// process the data (we don't need to wait that the thread is over, so do it now, it will let more time for the thread to finish, and therfore often save a 'usleep').
	if (pTask->bNeedsUpdate)  // data are ready to be processed -> perform the update
	{
		if (! pTask->bDiscard)  // of course if the task has been discarded before, don't do anything.
		{
			pTask->bContinue = pTask->update (pTask->pSharedMemory);
		}
		pTask->bNeedsUpdate = FALSE;  // now update is done, we won't do it any more until the next iteration, even is we loop on this function.
	}
	
	// finish the iteration, and possibly schedule the next one (the thread must be finished for this part).
	if (g_mutex_trylock (pTask->pMutex))  // if the thread is over
	{
		if (pTask->bDiscard)  // if the task has been discarded, it's the end of the journey for it.
		{
			if (pTask->pCond)
			{
				pTask->bRunThread = TRUE;
				g_cond_signal (pTask->pCond);
				g_mutex_unlock (pTask->pMutex);
				g_thread_join (pTask->pThread); // unref the thread
			}
			else
			{
				g_mutex_unlock (pTask->pMutex);
				G_THREAD_UNREF (pTask->pThread);
			}
			pTask->pThread = NULL;
			_free_task (pTask);
			return FALSE;
		}
		
		if (! pTask->pCond)  // one-shot thread => the thread is over
		{
			G_THREAD_UNREF (pTask->pThread);
			pTask->pThread = NULL;
		}
		
		pTask->iSidUpdateIdle = 0;  // set it before the unlock, as it is accessed in the thread part
		g_mutex_unlock (pTask->pMutex);
		
		// schedule the next iteration if necessary.
		if (! pTask->bContinue)
		{
			_cancel_next_iteration (pTask);
		}
		else
		{
			pTask->iFrequencyState = GLDI_TASK_FREQUENCY_NORMAL;
			_schedule_next_iteration (pTask);
		}
		pTask->bIsRunning = FALSE;
		return FALSE;  // the update is now finished, quit.
	}
	
	// if the thread is not yet over, come back in 1ms.
	g_usleep (1);  // we don't want to block the main loop until the thread is over; so just sleep 1ms to give it a chance to terminate. so it's a kind of 'sched_yield()' wihout blocking the main loop.
	return TRUE;
}
예제 #7
0
void
gimp_fonts_load (Gimp               *gimp,
                 GimpInitStatusFunc  status_callback)
{
  FcConfig *config;
  GFile    *fonts_conf;
  GList    *path;

  g_return_if_fail (GIMP_IS_FONT_LIST (gimp->fonts));

  gimp_set_busy (gimp);

  if (gimp->be_verbose)
    g_print ("Loading fonts\n");

  gimp_container_freeze (GIMP_CONTAINER (gimp->fonts));

  gimp_container_clear (GIMP_CONTAINER (gimp->fonts));

  config = FcInitLoadConfig ();

  if (! config)
    goto cleanup;

  fonts_conf = gimp_directory_file (CONF_FNAME, NULL);
  if (! gimp_fonts_load_fonts_conf (config, fonts_conf))
    goto cleanup;

  fonts_conf = gimp_sysconf_directory_file (CONF_FNAME, NULL);
  if (! gimp_fonts_load_fonts_conf (config, fonts_conf))
    goto cleanup;

  path = gimp_config_path_expand_to_files (gimp->config->font_path, FALSE);
  gimp_fonts_add_directories (config, path);
  g_list_free_full (path, (GDestroyNotify) g_object_unref);

  if (status_callback)
    {
      gint64                 end_time;
      GThread               *cache_thread;
      GimpFontsLoadFuncData  data;

      /* We perform font cache initialization in a separate thread, so
       * in the case a cache rebuild is to be done it will not block
       * the UI.
       */
      data.config = config;
      g_mutex_init (&data.mutex);
      g_cond_init (&data.cond);
      data.caching_complete = FALSE;

      cache_thread = g_thread_new ("font-cacher",
                                   (GThreadFunc) gimp_fonts_load_thread,
                                   &data);

      g_mutex_lock (&data.mutex);

      end_time = g_get_monotonic_time () + 0.1 * G_TIME_SPAN_SECOND;
      while (! data.caching_complete)
        if (! g_cond_wait_until (&data.cond, &data.mutex, end_time))
          {
            status_callback (NULL, NULL, 0.6);

            end_time += 0.1 * G_TIME_SPAN_SECOND;
            continue;
          }

      g_mutex_unlock (&data.mutex);
      g_thread_join (cache_thread);

      g_mutex_clear (&data.mutex);
      g_cond_clear (&data.cond);
    }
  else
    {
      gimp_fonts_load_func (config);
    }

  gimp_font_list_restore (GIMP_FONT_LIST (gimp->fonts));

 cleanup:
  gimp_container_thaw (GIMP_CONTAINER (gimp->fonts));
  gimp_unset_busy (gimp);
}
예제 #8
0
int
main (int argc, char **argv)
{
  gint i;
  GArray *test_objects;
  GArray *test_threads;
  const gint n_threads = 5;

  g_thread_init (NULL);
  g_print ("START: %s\n", argv[0]);
  g_log_set_always_fatal (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | g_log_set_always_fatal (G_LOG_FATAL_MASK));
  g_type_init ();

  test_objects = g_array_new (FALSE, FALSE, sizeof (GTest *));

  for (i = 0; i < n_threads; i++) {
    GTest *test;
    
    test = g_object_new (G_TYPE_TEST, NULL);
    g_array_append_val (test_objects, test);

    g_assert (test->count == test->dummy);
    g_signal_connect (test, "notify::dummy", G_CALLBACK (dummy_notify), NULL);
  }
    
  test_threads = g_array_new (FALSE, FALSE, sizeof (GThread *));

  stopping = FALSE;

  for (i = 0; i < n_threads; i++) {
    GThread *thread;
    GTest *test;

    test = g_array_index (test_objects, GTest *, i);

    thread = g_thread_create ((GThreadFunc) run_thread, test, TRUE, NULL);
    g_array_append_val (test_threads, thread);
  }
  g_usleep (3000000);

  stopping = TRUE;
  g_print ("\nstopping\n");

  /* join all threads */
  for (i = 0; i < n_threads; i++) {
    GThread *thread;

    thread = g_array_index (test_threads, GThread *, i);
    g_thread_join (thread);
  }

  g_print ("stopped\n");

  for (i = 0; i < n_threads; i++) {
    GTest *test;

    test = g_array_index (test_objects, GTest *, i);

    g_assert (test->count == test->dummy);
  }

  return 0;
}
예제 #9
0
int
main (int   argc,
      char *argv[])
{
  guint seed32, *seedp = NULL;
  gboolean ccounters = FALSE, use_memchunks = FALSE;
  guint n_threads = 1;
  const gchar *mode = "slab allocator + magazine cache", *emode = " ";
  if (argc > 1)
    n_threads = g_ascii_strtoull (argv[1], NULL, 10);
  if (argc > 2)
    {
      guint i, l = strlen (argv[2]);
      for (i = 0; i < l; i++)
        switch (argv[2][i])
          {
          case 'G': /* GLib mode */
            g_slice_set_config (G_SLICE_CONFIG_ALWAYS_MALLOC, FALSE);
            g_slice_set_config (G_SLICE_CONFIG_BYPASS_MAGAZINES, FALSE);
            mode = "slab allocator + magazine cache";
            break;
          case 'S': /* slab mode */
            g_slice_set_config (G_SLICE_CONFIG_ALWAYS_MALLOC, FALSE);
            g_slice_set_config (G_SLICE_CONFIG_BYPASS_MAGAZINES, TRUE);
            mode = "slab allocator";
            break;
          case 'M': /* malloc mode */
            g_slice_set_config (G_SLICE_CONFIG_ALWAYS_MALLOC, TRUE);
            mode = "system malloc";
            break;
          case 'O': /* old memchunks */
            use_memchunks = TRUE;
            mode = "old memchunks";
            break;
          case 'f': /* eager freeing */
            g_slice_set_config (G_SLICE_CONFIG_WORKING_SET_MSECS, 0);
            clean_memchunks = TRUE;
            emode = " with eager freeing";
            break;
          case 'c': /* print contention counters */
            ccounters = TRUE;
            break;
          case '~':
            want_corruption = TRUE; /* force occasional corruption */
            break;
          default:
            usage();
            return 1;
          }
    }
  if (argc > 3)
    prime_size = g_ascii_strtoull (argv[3], NULL, 10);
  if (argc > 4)
    {
      seed32 = g_ascii_strtoull (argv[4], NULL, 10);
      seedp = &seed32;
    }

  g_thread_init (NULL);

  if (argc <= 1)
    usage();

  {
    gchar strseed[64] = "<random>";
    GThread **threads;
    guint i;
    
    if (seedp)
      g_snprintf (strseed, 64, "%u", *seedp);
    g_print ("Starting %d threads allocating random blocks <= %u bytes with seed=%s using %s%s\n", n_threads, prime_size, strseed, mode, emode);
  
    threads = g_alloca (sizeof(GThread*) * n_threads);
    if (!use_memchunks)
      for (i = 0; i < n_threads; i++)
        threads[i] = g_thread_create (test_sliced_mem_thread, seedp, TRUE, NULL);
    else
      {
        for (i = 0; i < n_threads; i++)
          threads[i] = g_thread_create (test_memchunk_thread, seedp, TRUE, NULL);
      }
    for (i = 0; i < n_threads; i++)
      g_thread_join (threads[i]);
  
    if (ccounters)
      {
        guint n, n_chunks = g_slice_get_config (G_SLICE_CONFIG_CHUNK_SIZES);
        g_print ("    ChunkSize | MagazineSize | Contention\n");
        for (i = 0; i < n_chunks; i++)
          {
            gint64 *vals = g_slice_get_config_state (G_SLICE_CONFIG_CONTENTION_COUNTER, i, &n);
            g_print ("  %9" G_GINT64_FORMAT "   |  %9" G_GINT64_FORMAT "   |  %9" G_GINT64_FORMAT "\n", vals[0], vals[2], vals[1]);
            g_free (vals);
          }
      }
    else
      g_print ("Done.\n");
    return 0;
  }
}
예제 #10
0
파일: ivshmem-test.c 프로젝트: gkurz/qemu
static void test_ivshmem_server(void)
{
    IVState state1, state2, *s1, *s2;
    ServerThread thread;
    IvshmemServer server;
    int ret, vm1, vm2;
    int nvectors = 2;
    guint64 end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;

    ret = ivshmem_server_init(&server, tmpserver, tmpshm, true,
                              TMPSHMSIZE, nvectors,
                              g_test_verbose());
    g_assert_cmpint(ret, ==, 0);

    ret = ivshmem_server_start(&server);
    g_assert_cmpint(ret, ==, 0);

    thread.server = &server;
    ret = pipe(thread.pipe);
    g_assert_cmpint(ret, ==, 0);
    thread.thread = g_thread_new("ivshmem-server", server_thread, &thread);
    g_assert(thread.thread != NULL);

    setup_vm_with_server(&state1, nvectors);
    s1 = &state1;
    setup_vm_with_server(&state2, nvectors);
    s2 = &state2;

    /* check got different VM ids */
    vm1 = in_reg(s1, IVPOSITION);
    vm2 = in_reg(s2, IVPOSITION);
    g_assert_cmpint(vm1, >=, 0);
    g_assert_cmpint(vm2, >=, 0);
    g_assert_cmpint(vm1, !=, vm2);

    /* check number of MSI-X vectors */
    ret = qpci_msix_table_size(s1->dev);
    g_assert_cmpuint(ret, ==, nvectors);

    /* TODO test behavior before MSI-X is enabled */

    /* ping vm2 -> vm1 on vector 0 */
    ret = qpci_msix_pending(s1->dev, 0);
    g_assert_cmpuint(ret, ==, 0);
    out_reg(s2, DOORBELL, vm1 << 16);
    do {
        g_usleep(10000);
        ret = qpci_msix_pending(s1->dev, 0);
    } while (ret == 0 && g_get_monotonic_time() < end_time);
    g_assert_cmpuint(ret, !=, 0);

    /* ping vm1 -> vm2 on vector 1 */
    ret = qpci_msix_pending(s2->dev, 1);
    g_assert_cmpuint(ret, ==, 0);
    out_reg(s1, DOORBELL, vm2 << 16 | 1);
    do {
        g_usleep(10000);
        ret = qpci_msix_pending(s2->dev, 1);
    } while (ret == 0 && g_get_monotonic_time() < end_time);
    g_assert_cmpuint(ret, !=, 0);

    cleanup_vm(s2);
    cleanup_vm(s1);

    if (qemu_write_full(thread.pipe[1], "q", 1) != 1) {
        g_error("qemu_write_full: %s", g_strerror(errno));
    }

    g_thread_join(thread.thread);

    ivshmem_server_close(&server);
    close(thread.pipe[1]);
    close(thread.pipe[0]);
}
예제 #11
0
static void play_file(InputPlayback *ipb)
{
	char *filename = ipb->filename;
	int channelcnt = 1;
	FILE *f;
	struct xmp_options *opt;
	int lret;
	GtkTextIter start, end;
	
	opt = xmp_get_options(ctx);

	/* Sorry, no VFS support */
	if (memcmp(filename, "file://", 7) == 0)	/* Audacious 1.4.0 */
		filename += 7;

	_D("play_file: %s", filename);

	stop(ipb);	/* sanity check */

	if ((f = fopen(filename,"rb")) == 0) {
		ipb->playing = 0;
		return;
	}
	fclose(f);

	gtk_text_buffer_get_start_iter(text1b, &start);
	gtk_text_buffer_get_end_iter(text1b, &end);
	gtk_text_buffer_delete(text1b, &start, &end);

	xmp_plugin_audio_error = FALSE;
	ipb->playing = 1;

	opt->resol = 8;
	opt->verbosity = 3;
	opt->drv_id = "callback";

	switch (xmp_cfg.mixing_freq) {
	case 1:
		opt->freq = 22050;	/* 1:2 mixing freq */
		break;
	case 2:
		opt->freq = 11025;	/* 1:4 mixing freq */
		break;
	default:
		opt->freq = 44100;	/* standard mixing freq */
		break;
	}

	if (xmp_cfg.force8bit == 0)
		opt->resol = 16;

	if (xmp_cfg.force_mono == 0) {
		channelcnt = 2;
		opt->outfmt &= ~XMP_FMT_MONO;
	} else {
		opt->outfmt |= XMP_FMT_MONO;
	}

	if (xmp_cfg.interpolation == 1)
		opt->flags |= XMP_CTL_ITPT;
	else
		opt->flags &= ~XMP_CTL_ITPT;

	if (xmp_cfg.filter == 1)
		opt->flags |= XMP_CTL_FILTER;
	else
		opt->flags &= ~XMP_CTL_FILTER;

	opt->mix = xmp_cfg.pan_amplitude;

	play_data.ipb = ipb;
	play_data.fmt = opt->resol == 16 ? FMT_S16_NE : FMT_U8;
	play_data.nch = opt->outfmt & XMP_FMT_MONO ? 1 : 2;
	
	if (audio_open)
	    ipb->output->close_audio();
	
	if (!ipb->output->open_audio(play_data.fmt, opt->freq, play_data.nch)) {
	    ipb->error = TRUE;
	    xmp_plugin_audio_error = TRUE;
	    return;
	}
	
	audio_open = TRUE;

	xmp_open_audio(ctx);

	pipe(fd_info);
	fd_old2 = dup (fileno (stderr));
	dup2(fd_info[1], fileno (stderr));
	fflush(stderr);
	catch_thread = g_thread_create(catch_info, NULL, TRUE, NULL);

	_D("*** loading: %s", filename);
	g_static_mutex_lock(&load_mutex);
	lret =  xmp_load_module(ctx, filename);
	g_static_mutex_unlock(&load_mutex);

	if (lret < 0) {
		xmp_ip.set_info_text("Error loading mod");
		ipb->playing = 0;
		return;
	}

	_D("joining catch thread");
	g_thread_join(catch_thread);
	_D("joined");
	dup2(fileno(stderr), fd_old2);

	gtk_adjustment_set_value(GTK_TEXT_VIEW(text1)->vadjustment, 0.0);

	close(fd_info[0]);
	close(fd_info[1]);

	_D ("before panel update");

	xmp_cfg.time = lret; //xmpi_scan_module((struct xmp_context *)ctx);
	xmp_get_module_info(ctx, &ii->mi);
	strcpy(ii->filename, "");

	new_module = 1;

	_D("after panel update");

	memcpy(&xmp_cfg.mod_info, &ii->mi, sizeof (ii->mi));

#if __AUDACIOUS_PLUGIN_API__ >= 2
	ipb->set_params(ipb, ii->mi.name, lret, 0, opt->freq, channelcnt);
	ipb->playing = 1;
	ipb->eof = 0;
	ipb->error = FALSE;

	decode_thread = g_thread_self();
	ipb->set_pb_ready(ipb);
	play_loop(ipb);
#else
	xmp_ip.set_info(ii->mi.name, lret, 0, opt->freq, channelcnt);
	decode_thread = g_thread_create(play_loop, ipb, TRUE, NULL);
#endif
}
int main(int argc, char** argv)
{
	char strOpt[255];
	int ret;
	char str[STR_MAX];
	GError *gerr = NULL;

	// If application is executed by AUL, this is not needed.
	g_setenv("PKG_NAME", "com.samsung.location-api-test", 1);

	g_type_init();

#if !GLIB_CHECK_VERSION (2, 31, 0)
	if( !g_thread_supported() )
	{
		g_thread_init(NULL);
	}
#endif

	GThread *g_main;
	g_main = g_thread_create(GmainThread, NULL, TRUE, &gerr);
	if (!g_main) {
		g_printf("Error create gmain thread: Err domain[%d] Err code[%d] Err msg[%s]",
			gerr->domain, gerr->code, gerr->message);
		g_error_free(gerr);
		return 0;
	}

	json_util_init(LOCATION_API_TEST_JSON_FILE);
	g_printf("--- Start LBS Test App ---\n");
	while(1)
	{
		print_menu();
		g_printf("Select option: ");
		SelectOpt(strOpt);
		g_printf("======================================================================================\n");
		if (0 == g_strcmp0 ("x", strOpt)) {

		}
		else if (0 == g_strcmp0("1",strOpt)) {
			ret = location_init();
			GetLocationError(str, ret);
			g_printf("location_init: returned value [%s]\n", str);
		} else if (0 == g_strcmp0("2",strOpt)) {
			if (location_obj) {
				g_printf("Location object already existed: [0x%x]", (unsigned int)location_obj);
				continue;
			}
			g_printf("LOCATION_METHOD_HYBRID[0] LOCATION_METHOD_GPS[1] LOCATION_METHOD_WPS[2] LOCATION_METHOD_CPS[3]\n");
			g_printf("Select Location Method: ");
			LocationMethod method = PromptInt();
			location_obj = location_new(method);
			if(location_obj) g_printf("Success\n");
			else             g_printf("Failed\n");
		} else if (0 == g_strcmp0("3",strOpt)) {
			ret = location_free (location_obj);
			location_obj = NULL;

			g_sig_enable = 0;
			g_sig_disable = 0;
			g_sig_update = 0;
			g_sig_zonein = 0;
			g_sig_zoneout = 0;
			GetLocationError(str, ret);
			g_printf("location_free: returned value [%s]\n", str);
		} else if (0 == g_strcmp0("4",strOpt)) {
			ret = location_start(location_obj);
			GetLocationError(str, ret);
			g_printf("location_start: returned value [%s]\n", str);
		} else if (0 == g_strcmp0("5",strOpt)) {
			ret = location_stop(location_obj);
			GetLocationError(str, ret);
			g_printf("location_stop: returned value [%s]\n", str);
		} else if (0 == g_strcmp0("6",strOpt)) {
			LocationPosition *pos = NULL;
			LocationAccuracy *acc = NULL;
			ret = location_get_position(location_obj, &pos, &acc);
			GetLocationError(str, ret);
			g_printf("location_get_position: returned value [%s]\n", str);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf("time: [%d], latitude: [%f], longitude: [%f], altitude: [%f], status: [%d]\n", pos->timestamp, pos->latitude, pos->longitude, pos->altitude, pos->status);
				GetAccuracyLevel(str, acc->level);
				g_printf("level: [%s], horizontal_accuracy: [%f], vertical_accuracy: [%f]\n", str, acc->horizontal_accuracy, acc->vertical_accuracy);
			}
			if(pos) location_position_free(pos);
			if(acc) location_accuracy_free(acc);
		} else if (0 == g_strcmp0("6a",strOpt)) {
			LocationPosition *last_pos;
			LocationAccuracy *last_acc;
			int ret = 0;

			ret = location_get_last_position (location_obj, &last_pos, &last_acc);
			GetLocationError(str, ret);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf ("SYNC>> Last position> time: %d, lat: %f, long: %f, alt: %f, status: %d",
					last_pos->timestamp, last_pos->latitude, last_pos->longitude, last_pos->altitude, last_pos->status);
				g_printf ("\tAccuracy level %d (%.0f meters %.0f meters)",
					last_acc->level, last_acc->horizontal_accuracy, last_acc->vertical_accuracy);
				location_position_free(last_pos);
				location_accuracy_free(last_acc);
			} else g_warning ("SYNC>> Last position> failed. Error[%s]",str);

		}else if(0 == g_strcmp0("7",strOpt) ){
			LocationVelocity *vel = NULL;
			LocationAccuracy *acc = NULL;
			ret = location_get_velocity(location_obj, &vel, &acc);
			g_printf("location_get_velocity: returned value [%s]\n", str);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf("time: [%d], speed: [%f], direction: [%f], climb: [%f]\n", vel->timestamp, vel->speed, vel->direction, vel->climb);
				GetAccuracyLevel(str, acc->level);
				g_printf("level: [%s], horizontal_accuracy: [%f], vertical_accuracy: [%f]\n", str, acc->horizontal_accuracy, acc->vertical_accuracy);
			}
			else {
				GetLocationError(str, ret);
				g_warning ("SYNC>> velocity> failed. Error[%s]", str);
			}
			if(vel) location_velocity_free(vel);
			if(acc) location_accuracy_free(acc);
		}else if(0 == g_strcmp0("7a",strOpt) ){
			LocationVelocity *last_vel = NULL;
			LocationAccuracy *last_acc = NULL;
			ret = location_get_last_velocity (location_obj, &last_vel, &last_acc);
			GetLocationError(str, ret);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf ("SYNC>> Last velocity> time: %d, speed: %f, direction:%f, climb:%f",
					last_vel->timestamp, last_vel->speed, last_vel->direction, last_vel->climb);
				g_printf ("\tAccuracy level %d (%.0f meters %.0f meters)",
					last_acc->level, last_acc->horizontal_accuracy, last_acc->vertical_accuracy);
				location_velocity_free(last_vel);
				location_accuracy_free(last_acc);
			} else g_warning ("SYNC>> Last velocity> failed. Error[%s]", str);
		}else if(0 == g_strcmp0("8",strOpt) ){
			int ret = 0, idx = 0;
			LocationSatellite *sat = NULL;
			guint prn;
			gboolean used;
			guint elevation;
			guint azimuth;
			gint snr;

			ret =  location_get_satellite (location_obj, &sat);
			GetLocationError(str, ret);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf ("SYNC>> Current Sattelite> time = %d, satellite in view = %d, satellite in used = %d", sat->timestamp, sat->num_of_sat_inview, sat->num_of_sat_used);
				g_printf ("\tinview satellite information = ");
				for (idx=0; idx<sat->num_of_sat_inview; idx++) {
					location_satellite_get_satellite_details(sat, idx, &prn, &used, &elevation, &azimuth, &snr);
					g_printf ("\t\t[%02d] used: %d, prn: %d, elevation: %d, azimuth: %d, snr: %d", idx, used, prn, elevation, azimuth, snr);
				}
				location_satellite_free (sat);
			} else g_warning ("SYNC>> Current satellite> failed. Error[%s]", str);
		}else if(0 == g_strcmp0("8a",strOpt) ){
			int ret = 0, idx = 0;
			LocationSatellite *last_sat = NULL;
			guint prn;
			gboolean used;
			guint elevation;
			guint azimuth;
			gint snr;

			ret = location_get_last_satellite (location_obj, &last_sat);
			GetLocationError(str, ret);
			if (ret == LOCATION_ERROR_NONE) {
				g_printf ("SYNC>> Last Sattelite> time = %d, satellite in view = %d, satellite in used = %d", last_sat->timestamp, last_sat->num_of_sat_inview, last_sat->num_of_sat_used);
				g_printf ("\tinview satellite information = ");
				for (idx=0; idx<last_sat->num_of_sat_inview; idx++) {
					location_satellite_get_satellite_details(last_sat, idx, &prn, &used, &elevation, &azimuth, &snr);
					g_printf ("\t\t[%02d] used: %d, prn: %d, elevation: %d, azimuth: %d, snr: %d", idx, used, prn, elevation, azimuth, snr);
				}
				location_satellite_free (last_sat);
			} else g_warning ("SYNC>> Last satellite> failed. Error[%s]", str);
		}else if(0 == g_strcmp0("9",strOpt) ) {

			gulong distance;
			int ret = 0;
			char str[STR_MAX];
			LocationPosition pos1, pos2;

			pos1.latitude = 50.0663222;
			pos1.longitude = -5.71475;

			pos2.latitude = 58.6441;
			pos2.longitude = -3.070094;

			ret = location_get_distance(&pos1, &pos2, &distance);
			GetLocationError(str, ret);
			if(ret != LOCATION_ERROR_NONE) {
					g_printf("Fail to get position. Error[%s]\n", str);
			}
			else {
					g_printf("The approximate distance is [%lu]\n", distance);
					g_printf("cf.) It is approximately 969954.114 meter\n");
			}
		}else if(0 == g_strcmp0("10", strOpt)) {
			int method;
			char method_str[STR_MAX] = {0, };
			char input[8] = {0, };
			gboolean is_supported = FALSE;

			g_printf("0.Hybrid 1.GPS 2.WPS 3.CPS\n");
			g_printf("Select Method :");
			fgets(input, 8, stdin);
			method = atoi(input);
			switch(method) {
				case LOCATION_METHOD_HYBRID:
					is_supported = location_is_supported_method(LOCATION_METHOD_HYBRID);
					break;

				case LOCATION_METHOD_GPS:
					is_supported = location_is_supported_method(LOCATION_METHOD_GPS);
					break;

				case LOCATION_METHOD_WPS:
					is_supported = location_is_supported_method(LOCATION_METHOD_WPS);
					break;

				case LOCATION_METHOD_CPS:
					is_supported = location_is_supported_method(LOCATION_METHOD_CPS);
					break;

				default:
					break;

			}
			GetMethod(method_str, method);

			g_printf("Method[%s] is %s.", method_str, is_supported ? "supported" : "not supported");

		}else if(0 == g_strcmp0("11", strOpt)) {
			gboolean is_enabled = FALSE;
			is_enabled = location_is_enabled_gps(location_obj);
			if(is_enabled == TRUE) g_printf("GPS is turned on");
			else g_printf("GPS is turned off");
		}else if(0 == g_strcmp0("99", strOpt)) {
			int ret = 0;
			const *str = "command";
			ret = location_send_command(str);
			if(ret == 0)
				g_printf("Success to send command[%s]", str);
		}else if(0 == g_strcmp0("a1",strOpt)){
			if(location_obj && !g_sig_enable) {
				g_sig_enable = g_signal_connect (location_obj, "service-enabled", G_CALLBACK(cb_service_enabled), location_obj);
			}
		}else if(0 == g_strcmp0("a2",strOpt)){
			if(location_obj && !g_sig_disable){
				g_sig_disable = g_signal_connect (location_obj, "service-disabled", G_CALLBACK(cb_service_disabled), location_obj);
			}
		}else if(0 == g_strcmp0("a3",strOpt)){
			if(location_obj && !g_sig_update){
				g_sig_update = g_signal_connect (location_obj, "service-updated", G_CALLBACK(cb_service_updated), location_obj);
			}
		}else if(0 == g_strcmp0("a4",strOpt)){
			if(location_obj && !g_sig_zonein){
				g_sig_zonein = g_signal_connect (location_obj, "zone-in", G_CALLBACK(cb_zone_in), location_obj);
			}
		}else if(0 == g_strcmp0("a5",strOpt)){
			if(location_obj && !g_sig_zoneout){
				g_sig_zoneout = g_signal_connect (location_obj, "zone-out", G_CALLBACK(cb_zone_out), location_obj);
			}
		}else if(0 == g_strcmp0("b1",strOpt)){
			if(location_obj && g_sig_enable) {
				g_signal_handler_disconnect (location_obj, g_sig_enable);
				g_sig_enable = 0;
			}
		}else if(0 == g_strcmp0("b2",strOpt)){
			if(location_obj && g_sig_disable){
				g_signal_handler_disconnect (location_obj, g_sig_disable);
				g_sig_disable = 0;
			}
		}else if(0 == g_strcmp0("b3",strOpt)){
			if(location_obj && g_sig_update){
				g_signal_handler_disconnect (location_obj, g_sig_update);
				g_sig_update = 0;
			}
		}else if(0 == g_strcmp0("b4",strOpt)){
			if(location_obj && g_sig_zonein){
				g_signal_handler_disconnect (location_obj, g_sig_zonein);
				g_sig_zonein = 0;
			}
		}else if(0 == g_strcmp0("b5",strOpt)){
			if(location_obj && g_sig_zoneout){
				g_signal_handler_disconnect (location_obj, g_sig_zoneout);
				g_sig_zoneout = 0;
			}
		}else if(0 == g_strcmp0("c1",strOpt)){
			LocationBoundary* bound = NULL;
			int i = 0;
			int polygon_count = json_util_get_polygon_count();

			g_printf("[0].San jose(Rect) [1].Suwon HQ(Rect) [2].Seoul City(circle) ");
			for(i = 0; i < polygon_count; i++)
				g_printf("[%d].%s ", i + 3, json_util_get_polygon_name(i));

			g_printf("\nSelect Boundary: ");
			int opt = PromptInt();
			if (opt == 0) {
				LocationPosition* rb = location_position_new (0, 37.300, -121.86, 0, LOCATION_STATUS_2D_FIX);
				LocationPosition* lt = location_position_new (0, 37.360, -121.92, 0, LOCATION_STATUS_2D_FIX);
				bound = location_boundary_new_for_rect (lt, rb);
				location_position_free(rb);
				location_position_free(lt);

				location_boundary_add(location_obj, bound);

			} else if(opt == 1) {
				LocationPosition* rb = location_position_new (0, 37.255, 127.058, 0, LOCATION_STATUS_2D_FIX);
				LocationPosition* lt = location_position_new (0, 37.260, 127.045, 0, LOCATION_STATUS_2D_FIX);
				bound = location_boundary_new_for_rect (lt, rb);
				location_position_free(rb);
				location_position_free(lt);

				location_boundary_add(location_obj, bound);
			} else if(opt == 2) {
				LocationPosition *center = location_position_new(0, 37.566535, 126.977969, 0.0, LOCATION_STATUS_2D_FIX);
				double radius = 10.0;
				bound = location_boundary_new_for_circle(center, radius);

				location_boundary_add(location_obj, bound);
			} else if (opt > 2 && opt < 3 + polygon_count) {
				int index;
				int polygon_index = opt - 3;
				bound = json_util_get_polygon_boundary(polygon_index);
				location_boundary_add(location_obj, bound);

				LocationPosition * check_pos = NULL;
				gboolean ret = FALSE;
				int count = json_util_get_marker_position_count(polygon_index);
				for(index = 0; index < count; index++) {
					check_pos = json_util_get_marker_position(polygon_index, index);

					ret = location_boundary_if_inside(bound, check_pos);
					g_printf("[%s] is [%s] and the test result is [%s]\n", json_util_get_marker_name(polygon_index, index), json_util_result_zone_test(polygon_index, index), ret == TRUE? "inside": "outside");
					location_position_free(check_pos);
				}
			} else {
				g_printf("boundary is not set\n");
			}
			location_boundary_free(bound);

		}else if(0 == g_strcmp0("c2",strOpt)){
			g_printf("Get Boundary\n");
			location_boundary_foreach(location_obj, PrintBoundary, NULL);

		}else if(0 == g_strcmp0("c3",strOpt)){
			g_printf("Remove Boundary\n");
			LocationBoundary* bound = NULL;

			int i = 0;
			int polygon_count = json_util_get_polygon_count();

			g_printf("[0].San jose(Rect) [1].Suwon HQ(Rect) [2].Seoul City(circle) ");
			for(i = 0; i < polygon_count; i++)
				g_printf("[%d].%s ", i + 3, json_util_get_polygon_name(i));

			g_printf("\nSelect Boundary: ");
			int opt = PromptInt();
			if (opt == 0) {
				LocationPosition* rb = location_position_new (0, 37.300, -121.86, 0, LOCATION_STATUS_2D_FIX);
				LocationPosition* lt = location_position_new (0, 37.360, -121.92, 0, LOCATION_STATUS_2D_FIX);
				bound = location_boundary_new_for_rect (lt, rb);
				location_position_free(rb);
				location_position_free(lt);

			} else if(opt == 1) {
				LocationPosition* rb = location_position_new (0, 37.255, 127.058, 0, LOCATION_STATUS_2D_FIX);
				LocationPosition* lt = location_position_new (0, 37.260, 127.045, 0, LOCATION_STATUS_2D_FIX);
				bound = location_boundary_new_for_rect (lt, rb);
				location_position_free(rb);
				location_position_free(lt);

			} else if(opt == 2) {
				LocationPosition *center = location_position_new(0, 37.566535, 126.977969, 0.0, LOCATION_STATUS_2D_FIX);
				double radius = 10.0;
				bound = location_boundary_new_for_circle(center, radius);
				location_position_free(center);

			} else if (opt > 2 && opt < 3 + polygon_count) {
				int polygon_index = opt - 3;
				bound = json_util_get_polygon_boundary(polygon_index);
			} else {
				g_printf("Invalid value\n");
			}

			if(bound != NULL) location_boundary_remove(location_obj, bound);

		}else if(0 == g_strcmp0("c4",strOpt)){
			location_boundary_foreach(location_obj, RemoveBoundary, location_obj);
		}else if(0 == g_strcmp0("c5",strOpt)){
			char buf[255];
			g_printf("Input device name: ");
			fgets(buf, 255, stdin);
			buf[strlen(buf)-1]='\0';
			g_object_set(location_obj, "dev-name", buf, NULL);
		} else if (0 == g_strcmp0("c6", strOpt)) {
			guint interval = 1;
			g_printf("Input interval[1~120]:");
			scanf("%u", &interval);
			g_printf("changed interval to [%u]\n", interval);
			g_object_set(location_obj, "pos-interval", interval, NULL);
		} else if (0 == g_strcmp0("c7", strOpt)) {
			guint interval = 1;
			g_printf("Input interval[1~120]:");
			scanf("%u", &interval);
			g_printf("changed interval to [%u]\n", interval);
			g_object_set(location_obj, "vel-interval", interval, NULL);
		} else if (0 == g_strcmp0("c8", strOpt)) {
			guint interval = 1;
			g_printf("Input interval[1~120]:");
			scanf("%u", &interval);
			g_printf("changed interval to [%u]\n", interval);
			g_object_set(location_obj, "sat-interval", interval, NULL);
		}else if(0 == g_strcmp0("q",strOpt) ){
			g_main_loop_quit(g_mainloop);
			break;
		}
	}
	g_thread_join(g_main);
	g_printf("\n--- Exit LBS Test App ---\n");
	return 1;
}
예제 #13
0
파일: testegl.c 프로젝트: ryumiel/gst-omx
int
main (int argc, char **argv)
{
    GstBus *bus;
    GOptionContext *ctx;
    GIOChannel *io_stdin;
    GError *err = NULL;
    gboolean res;
    GOptionEntry options[] = {
        {NULL}
    };
    GThread *rthread;

    /* Clear application state */
    memset (state, 0, sizeof (*state));
    state->animate = TRUE;
    state->current_buffer = NULL;
    state->caps = NULL;

#if !GLIB_CHECK_VERSION (2, 31, 0)
    /* must initialise the threading system before using any other GLib funtion */
    if (!g_thread_supported ())
        g_thread_init (NULL);
#endif

    ctx = g_option_context_new ("[ADDITIONAL ARGUMENTS]");
    g_option_context_add_main_entries (ctx, options, NULL);
    g_option_context_add_group (ctx, gst_init_get_option_group ());
    if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
        g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
        g_option_context_free (ctx);
        g_clear_error (&err);
        exit (1);
    }
    g_option_context_free (ctx);

    if (argc != 2) {
        g_print ("Usage: %s <URI> or <PIPELINE-DESCRIPTION>\n", argv[0]);
        exit (1);
    }

    /* Initialize GStreamer */
    gst_init (&argc, &argv);

    /* initialize inter thread comunnication */
    init_intercom (state);

    TRACE_VC_MEMORY ("state 0");

    if (!(rthread = g_thread_new ("render", (GThreadFunc) render_func, NULL))) {
        g_print ("Render thread create failed\n");
        exit (1);
    }

    /* Initialize player */
    if (gst_uri_is_valid (argv[1])) {
        res = init_playbin_player (state, argv[1]);
    } else {
        res = init_parse_launch_player (state, argv[1]);
    }

    if (!res)
        goto done;

    /* Create a GLib Main Loop and set it to run */
    state->main_loop = g_main_loop_new (NULL, FALSE);

    /* Add a keyboard watch so we get notified of keystrokes */
    io_stdin = g_io_channel_unix_new (fileno (stdin));
    g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc) handle_keyboard, state);
    g_io_channel_unref (io_stdin);

  /* *INDENT-OFF* */
  g_print ("Available commands: \n"
      "  a - Toggle animation \n"
      "  p - Pause playback \n"
      "  r - Resume playback \n"
      "  l - Query position/duration\n"
      "  f - Seek 30 seconds forward \n"
      "  b - Seek 30 seconds backward \n"
      "  q - Quit \n");
  /* *INDENT-ON* */

    /* Connect the bus handlers */
    bus = gst_element_get_bus (state->pipeline);

    gst_bus_set_sync_handler (bus, (GstBusSyncHandler) bus_sync_handler, state,
                              NULL);

    gst_bus_add_signal_watch_full (bus, G_PRIORITY_HIGH);
    gst_bus_enable_sync_message_emission (bus);

    g_signal_connect (G_OBJECT (bus), "message::error", (GCallback) error_cb,
                      state);
    g_signal_connect (G_OBJECT (bus), "message::buffering",
                      (GCallback) buffering_cb, state);
    g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback) eos_cb, state);
    g_signal_connect (G_OBJECT (bus), "message::qos", (GCallback) qos_cb, state);
    g_signal_connect (G_OBJECT (bus), "message::state-changed",
                      (GCallback) state_changed_cb, state);
    gst_object_unref (bus);

    /* Make player start playing */
    gst_element_set_state (state->pipeline, GST_STATE_PLAYING);

    /* Start the mainloop */
    state->main_loop = g_main_loop_new (NULL, FALSE);
    g_main_loop_run (state->main_loop);

done:
    /* Release pipeline */
    if (state->pipeline) {
        gst_element_set_state (state->pipeline, GST_STATE_NULL);
        if (state->vsink) {
            gst_object_unref (state->vsink);
            state->vsink = NULL;
        }

        gst_object_unref (state->pipeline);
    }

    /* Unref the mainloop */
    if (state->main_loop) {
        g_main_loop_unref (state->main_loop);
    }

    /* Stop rendering thread */
    state->running = FALSE;
    g_thread_join (rthread);

    if (state->caps) {
        gst_caps_unref (state->caps);
        state->caps = NULL;
    }

    terminate_intercom (state);

    TRACE_VC_MEMORY ("at exit");
    return 0;
}
예제 #14
0
static gboolean
pragha_scanner_worker_finished (gpointer data)
{
	GtkWidget *msg_dialog;
	gchar *last_scan_time = NULL;
	PraghaPreferences *preferences;
	PraghaDatabase *database;
	GSList *list;

	PraghaScanner *scanner = data;

	/* Stop updates */

	g_source_remove(scanner->update_timeout);

	/* Ensure that the other thread has finished */
	g_thread_join (scanner->no_files_thread);

	/* If not cancelled, update database and show a dialog */
	if(!g_cancellable_is_cancelled (scanner->cancellable)) {
		/* Hide the scanner and show the dialog */

		gtk_widget_hide(scanner->hbox);
		msg_dialog = gtk_message_dialog_new(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(scanner->hbox))),
		                                    GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
		                                    GTK_MESSAGE_INFO,
		                                    GTK_BUTTONS_OK,
		                                    "%s",
		                                    _("Library scan complete"));

		g_signal_connect(G_OBJECT(msg_dialog), "response",
		                 G_CALLBACK(pragha_scanner_finished_dialog_response_cb),
		                 scanner);

		g_signal_connect(G_OBJECT(msg_dialog), "delete-event",
		                 G_CALLBACK(pragha_scanner_finished_dialog_delete),
		                 scanner);

		gtk_widget_show_all(msg_dialog);

		/* Save new database and update the library view */

		set_watch_cursor(msg_dialog);
		set_watch_cursor(scanner->hbox);

		database = pragha_database_get();

		pragha_database_begin_transaction (database);

		pragha_database_flush (database);
		g_hash_table_foreach (scanner->tracks_table,
		                      pragha_scanner_add_track_db,
		                      database);


		/* Import playlist detected. */

		for (list = scanner->playlists ; list != NULL; list = list->next)
			pragha_scanner_import_playlist(database, list->data);

		pragha_database_commit_transaction (database);

		pragha_database_change_tracks_done (database);
		g_object_unref(database);

		remove_watch_cursor(scanner->hbox);
		remove_watch_cursor(msg_dialog);

		/* Save finished time and folders scanned. */

		g_get_current_time(&scanner->last_update);
		last_scan_time = g_time_val_to_iso8601(&scanner->last_update);
		preferences = pragha_preferences_get();
		pragha_preferences_set_string(preferences,
			                     GROUP_LIBRARY,
			                     KEY_LIBRARY_LAST_SCANNED,
			                     last_scan_time);
		g_free(last_scan_time);

		pragha_preferences_set_filename_list(preferences,
			                             GROUP_LIBRARY,
			                             KEY_LIBRARY_SCANNED,
			                             scanner->folder_list);
		g_object_unref(G_OBJECT(preferences));
	}
	else {
		gtk_widget_hide(scanner->hbox);
	}

	gtk_progress_bar_set_text(GTK_PROGRESS_BAR(scanner->progress_bar), NULL);
	gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(scanner->progress_bar), 0.0);

	/* Clean memory */

	g_hash_table_remove_all(scanner->tracks_table);
	free_str_list(scanner->folder_list);
	scanner->folder_list = NULL;
	free_str_list(scanner->folder_scanned);
	scanner->folder_scanned = NULL;

	free_str_list(scanner->playlists);
	scanner->playlists = NULL;

	scanner->no_files = 0;
	scanner->files_scanned = 0;

	g_cancellable_reset (scanner->cancellable);
	scanner->update_timeout = 0;

	return FALSE;
}
예제 #15
0
/**
 * Cellular automata sample main function.
 * */
int main(int argc, char* argv[]) {

	/* Wrappers for OpenCL objects. */
	CCLContext* ctx;
	CCLDevice* dev;
	CCLImage* img1;
	CCLImage* img2;
	CCLProgram* prg;
	CCLKernel* krnl;
	CCLEvent* evt1;
	CCLEvent* evt2;
	/* Other variables. */
	CCLEventWaitList ewl = NULL;
	/* Profiler object. */
	CCLProf* prof;
	/* Output images filename. */
	char* filename;
	/* Selected device, may be given in command line. */
	int dev_idx = -1;
	/* Error handling object (must be NULL). */
	GError* err = NULL;
	/* Does selected device support images? */
	cl_bool image_ok;
	/* Initial sim state. */
	cl_uchar4* input_image;
	/* Simulation states. */
	cl_uchar4** output_images;
	/* RNG seed, may be given in command line. */
	unsigned int seed;
	/* Image file write status. */
	int file_write_status;
	/* Image format. */
	cl_image_format image_format = { CL_RGBA, CL_UNSIGNED_INT8 };
	/* Thread data. */
	struct thread_data td;
	/* Full kernel path. */
	gchar* kernel_path = NULL;

	/* Global and local worksizes. */
	size_t gws[2];
	size_t lws[2];
	/* Threads. */
	GThread* comm_thread;
	GThread* exec_thread;

	/* Check arguments. */
	if (argc >= 2) {
		/* Check if a device was specified in the command line. */
		dev_idx = atoi(argv[1]);
	}
	if (argc >= 3) {
		/* Check if a RNG seed was specified. */
		seed = atoi(argv[2]);
	} else {
		seed = (unsigned int) time(NULL);
	}

	/* Initialize RNG. */
	srand(seed);

	/* Create random initial state. */
	input_image = (cl_uchar4*)
		malloc(CA_WIDTH * CA_HEIGHT * sizeof(cl_uchar4));
	for (cl_uint i = 0; i < CA_WIDTH * CA_HEIGHT; ++i) {
		cl_uchar state = (rand() & 0x3) ? 0xFF : 0x00;
		input_image[i] = (cl_uchar4) {{ state, state, state, 0xFF }};
	}

	/* Allocate space for simulation results. */
	output_images = (cl_uchar4**)
		malloc((CA_ITERS + 1) * sizeof(cl_uchar4*));
	for (cl_uint i = 0; i < CA_ITERS + 1; ++i)
		output_images[i] = (cl_uchar4*)
			malloc(CA_WIDTH * CA_HEIGHT * sizeof(cl_uchar4));

	/* Create context using device selected from menu. */
	ctx = ccl_context_new_from_menu_full(&dev_idx, &err);
	HANDLE_ERROR(err);

	/* Get first device in context. */
	dev = ccl_context_get_device(ctx, 0, &err);
	HANDLE_ERROR(err);

	/* Ask device if it supports images. */
	image_ok = ccl_device_get_info_scalar(
		dev, CL_DEVICE_IMAGE_SUPPORT, cl_bool, &err);
	HANDLE_ERROR(err);
	if (!image_ok)
		ERROR_MSG_AND_EXIT("Selected device doesn't support images.");

	/* Create command queues. */
	queue_exec = ccl_queue_new(ctx, dev, CL_QUEUE_PROFILING_ENABLE, &err);
	HANDLE_ERROR(err);
	queue_comm = ccl_queue_new(ctx, dev, CL_QUEUE_PROFILING_ENABLE, &err);
	HANDLE_ERROR(err);

	/* Create 2D image for initial state. */
	img1 = ccl_image_new(ctx, CL_MEM_READ_WRITE,
		&image_format, NULL, &err,
		"image_type", (cl_mem_object_type) CL_MEM_OBJECT_IMAGE2D,
		"image_width", (size_t) CA_WIDTH,
		"image_height", (size_t) CA_HEIGHT,
		NULL);
	HANDLE_ERROR(err);

	/* Create another 2D image for double buffering. */
	img2 = ccl_image_new(ctx, CL_MEM_READ_WRITE,
		&image_format, NULL, &err,
		"image_type", (cl_mem_object_type) CL_MEM_OBJECT_IMAGE2D,
		"image_width", (size_t) CA_WIDTH,
		"image_height", (size_t) CA_HEIGHT,
		NULL);
	HANDLE_ERROR(err);

	/* Get location of kernel file, which should be in the same location
	 * of the bankconf executable. */
	kernel_path = ccl_ex_kernelpath_get(kernel_files[0], argv[0]);

	/* Create program from kernel source and compile it. */
	prg = ccl_program_new_from_source_file(ctx, kernel_path, &err);
	HANDLE_ERROR(err);

	ccl_program_build(prg, NULL, &err);
	HANDLE_ERROR(err);

	/* Get kernel wrapper. */
	krnl = ccl_program_get_kernel(prg, "ca", &err);
	HANDLE_ERROR(err);

	/* Determine nice local and global worksizes. */
	ccl_kernel_suggest_worksizes(krnl, dev, 2, real_ws, gws, lws, &err);
	HANDLE_ERROR(err);

	printf("\n * Global work-size: (%d, %d)\n", (int) gws[0], (int) gws[1]);
	printf(" * Local work-size: (%d, %d)\n", (int) lws[0], (int) lws[1]);

	/* Create thread communication queues. */
	comm_thread_queue = g_async_queue_new();
	exec_thread_queue = g_async_queue_new();
	host_thread_queue = g_async_queue_new();

	/* Setup thread data. */
	td.krnl = krnl;
	td.img1 = img1;
	td.img2 = img2;
	td.gws = gws;
	td.lws = lws;
	td.output_images = output_images;

	/* Create threads. */
	exec_thread = g_thread_new("exec_thread", exec_func, &td);
	comm_thread = g_thread_new("comm_thread", comm_func, &td);

	/* Start profiling. */
	prof = ccl_prof_new();
	ccl_prof_start(prof);

	/* Write initial state. */
	ccl_image_enqueue_write(img1, queue_comm, CL_TRUE,
		origin, region, 0, 0, input_image, NULL, &err);
	HANDLE_ERROR(err);

	/* Run CA_ITERS iterations of the CA. */
	for (cl_uint i = 0; i < CA_ITERS; ++i) {

		/* Send message to comms thread. */
		g_async_queue_push(comm_thread_queue, &go_msg);

		/* Send message to exec thread. */
		g_async_queue_push(exec_thread_queue, &go_msg);

		/* Get event wrappers from both threads. */
		evt1 = (CCLEvent*) g_async_queue_pop(host_thread_queue);
		evt2 = (CCLEvent*) g_async_queue_pop(host_thread_queue);

		/* Can't continue until this iteration is over. */
		ccl_event_wait_list_add(&ewl, evt1, evt2, NULL);

		/* Wait for events. */
		ccl_event_wait(&ewl, &err);
		HANDLE_ERROR(err);

	}

	/* Send message to comms thread to read last result. */
	g_async_queue_push(comm_thread_queue, &go_msg);

	/* Send stop messages to both threads. */
	g_async_queue_push(comm_thread_queue, &stop_msg);
	g_async_queue_push(exec_thread_queue, &stop_msg);

	/* Get event wrapper from comms thread. */
	evt1 = (CCLEvent*) g_async_queue_pop(host_thread_queue);

	/* Can't continue until final read is over. */
	ccl_event_wait_list_add(&ewl, evt1, NULL);
	ccl_event_wait(&ewl, &err);
	HANDLE_ERROR(err);

	/* Make sure both queues are finished. */
	ccl_queue_finish(queue_comm, &err);
	HANDLE_ERROR(err);
	ccl_queue_finish(queue_exec, &err);
	HANDLE_ERROR(err);

	/* Stop profiling timer and add queues for analysis. */
	ccl_prof_stop(prof);
	ccl_prof_add_queue(prof, "Comms", queue_comm);
	ccl_prof_add_queue(prof, "Exec", queue_exec);

	/* Allocate space for base filename. */
	filename = (char*) malloc(
		(strlen(IMAGE_FILE_PREFIX ".png") + IMAGE_FILE_NUM_DIGITS + 1) * sizeof(char));

	/* Write results to image files. */
	for (cl_uint i = 0; i < CA_ITERS; ++i) {

		/* Determine next filename. */
		sprintf(filename, "%s%0" G_STRINGIFY(IMAGE_FILE_NUM_DIGITS) "d.png", IMAGE_FILE_PREFIX, i);

		/* Save next image. */
		file_write_status = stbi_write_png(filename, CA_WIDTH, CA_HEIGHT, 4,
			output_images[i], CA_WIDTH * sizeof(cl_uchar4));

		/* Give feedback if unable to save image. */
		if (!file_write_status) {
			ERROR_MSG_AND_EXIT("Unable to save image in file.");
		}
	}

	/* Process profiling info. */
	ccl_prof_calc(prof, &err);
	HANDLE_ERROR(err);

	/* Print profiling info. */
	ccl_prof_print_summary(prof);

	/* Save profiling info. */
	ccl_prof_export_info_file(prof, "prof.tsv", &err);
	HANDLE_ERROR(err);

	/* Destroy threads. */
	g_thread_join(exec_thread);
	g_thread_join(comm_thread);

	/* Destroy thread communication queues. */
	g_async_queue_unref(comm_thread_queue);
	g_async_queue_unref(exec_thread_queue);
	g_async_queue_unref(host_thread_queue);

	/* Release host buffers. */
	free(filename);
	free(input_image);
	for (cl_uint i = 0; i < CA_ITERS + 1; ++i)
		free(output_images[i]);
	free(output_images);

	/* Release wrappers. */
	ccl_image_destroy(img1);
	ccl_image_destroy(img2);
	ccl_program_destroy(prg);
	ccl_queue_destroy(queue_comm);
	ccl_queue_destroy(queue_exec);
	ccl_context_destroy(ctx);

	/* Destroy profiler. */
	ccl_prof_destroy(prof);

	/* Check all wrappers have been destroyed. */
	g_assert(ccl_wrapper_memcheck());

	/* Terminate. */
	return 0;

}
예제 #16
0
void
on_dlg_response ( GtkDialog *dialog,
                                gint response_id,
                                gpointer user_data )
{
    FilePropertiesDialogData * data;
    PtkFileTask* task;
    gboolean mod_change;
    uid_t uid = -1;
    gid_t gid = -1;
    const char* owner_name;
    const char* group_name;
    int i;
    GList* l;
    GList* file_list;
    char* file_path;
    GtkWidget* ask_recursive;
    VFSFileInfo* file;
    GtkAllocation allocation;

    gtk_widget_get_allocation ( GTK_WIDGET( dialog ), &allocation );
    
    int width = allocation.width;
    int height = allocation.height;
    if ( width && height )
    {
        char* str = g_strdup_printf( "%d", width );
        xset_set( "app_dlg", "s", str );
        g_free( str );
        str = g_strdup_printf( "%d", height );
        xset_set( "app_dlg", "z", str );
        g_free( str );
    }

    data = ( FilePropertiesDialogData* ) g_object_get_data( G_OBJECT( dialog ),
                                                            "DialogData" );
    if ( data )
    {
        if ( data->update_label_timer )
            g_source_remove( data->update_label_timer );
        data->cancel = TRUE;

        if ( data->calc_size_thread )
            g_thread_join( data->calc_size_thread );

        if ( response_id == GTK_RESPONSE_OK )
        {
            // change file dates
            char* cmd = NULL;
            char* quoted_time;
            char* quoted_path;
            const char* new_mtime = gtk_entry_get_text( data->mtime );
            if ( !( new_mtime && new_mtime[0] ) || 
                                !g_strcmp0( data->orig_mtime, new_mtime ) )
                new_mtime = NULL;
            const char* new_atime = gtk_entry_get_text( data->atime );
            if ( !( new_atime && new_atime[0] ) || 
                                !g_strcmp0( data->orig_atime, new_atime ) )
                new_atime = NULL;
            
            if ( ( new_mtime || new_atime ) && data->file_list )
            {
                GString* gstr = g_string_new( NULL );
                for ( l = data->file_list; l; l = l->next )
                {
                    file_path = g_build_filename( data->dir_path,
                                                  ((VFSFileInfo*)l->data)->name,
                                                  NULL );
                    quoted_path = bash_quote( file_path );
                    g_string_append_printf( gstr, " %s", quoted_path );
                    g_free( file_path );
                    g_free( quoted_path );
                }
                    
                if ( new_mtime )
                {
                    quoted_time = bash_quote( new_mtime );
                    cmd = g_strdup_printf( "touch --no-dereference --no-create -m -d %s%s",
                                                                quoted_time,
                                                                gstr->str );
                }
                if ( new_atime )
                {
                    quoted_time = bash_quote( new_atime );
                    quoted_path = cmd;  // temp str
                    cmd = g_strdup_printf( "%s%stouch --no-dereference --no-create -a -d %s%s",
                                                                cmd ? cmd : "",
                                                                cmd ? "\n" : "",
                                                                quoted_time,
                                                                gstr->str );
                    g_free( quoted_path );
                }
                g_free( quoted_time );
                g_string_free( gstr, TRUE );
                if ( cmd )
                {
                    task = ptk_file_exec_new( _("Change File Date"), "/",
                                              GTK_WIDGET( dialog ), NULL );
                    task->task->exec_command = cmd;
                    task->task->exec_sync = TRUE;
                    task->task->exec_export = FALSE;
                    task->task->exec_show_output = TRUE;
                    task->task->exec_show_error = TRUE;
                    ptk_file_task_run( task );
                }
            }
        
            /* Set default action for mimetype */
            GtkWidget* open_with;
            if( ( open_with = (GtkWidget*)g_object_get_data( G_OBJECT(dialog), "open_with" ) ) )
            {
                GtkTreeModel* model = gtk_combo_box_get_model( GTK_COMBO_BOX(open_with) );
                GtkTreeIter it;

                if( model && gtk_combo_box_get_active_iter( GTK_COMBO_BOX(open_with), &it ) )
                {
                    char* action;
                    gtk_tree_model_get( model, &it, 2, &action, -1 );
                    if( action )
                    {
                        file = ( VFSFileInfo* ) data->file_list->data;
                        VFSMimeType* mime = vfs_file_info_get_mime_type( file );
                        vfs_mime_type_set_default_action( mime, action );
                        vfs_mime_type_unref( mime );
                        g_free( action );
                    }
                }
            }

            /* Check if we need chown */
            owner_name = gtk_entry_get_text( data->owner );
            if ( owner_name && *owner_name &&
                 (!data->owner_name || strcmp( owner_name, data->owner_name ) ) )
            {
                uid = uid_from_name( owner_name );
                if ( uid == -1 )
                {
                    ptk_show_error( GTK_WINDOW( dialog ), _("Error"), _( "Invalid User" ) );
                    return ;
                }
            }
            group_name = gtk_entry_get_text( data->group );
            if ( group_name && *group_name &&
                 (!data->group_name || strcmp( group_name, data->group_name ) ) )
            {
                gid = gid_from_name( group_name );
                if ( gid == -1 )
                {
                    ptk_show_error( GTK_WINDOW( dialog ), _("Error"), _( "Invalid Group" ) );
                    return ;
                }
            }

            for ( i = 0; i < N_CHMOD_ACTIONS; ++i )
            {
                if ( gtk_toggle_button_get_inconsistent( data->chmod_btns[ i ] ) )
                {
                    data->chmod_states[ i ] = 2;  /* Don't touch this bit */
                }
                else if ( data->chmod_states[ i ] != gtk_toggle_button_get_active( data->chmod_btns[ i ] ) )
                {
                    mod_change = TRUE;
                    data->chmod_states[ i ] = gtk_toggle_button_get_active( data->chmod_btns[ i ] );
                }
                else /* Don't change this bit */
                {
                    data->chmod_states[ i ] = 2;
                }
            }

            if ( uid != -1 || gid != -1 || mod_change )
            {
                file_list = NULL;
                for ( l = data->file_list; l; l = l->next )
                {
                    file = ( VFSFileInfo* ) l->data;
                    file_path = g_build_filename( data->dir_path,
                            vfs_file_info_get_name( file ), NULL );
                    file_list = g_list_prepend( file_list, file_path );
                }

                task = ptk_file_task_new( VFS_FILE_TASK_CHMOD_CHOWN,
                                          file_list,
                                          NULL,
                                          GTK_WINDOW(gtk_widget_get_parent( GTK_WIDGET( dialog ) )),
                                          NULL );
                //MOD
                ptk_file_task_set_recursive( task,
                                        gtk_toggle_button_get_active(
                                        GTK_TOGGLE_BUTTON( data->recurse ) ) );
                /*
                for ( l = data->file_list; l; l = l->next )
                {
                    file = ( VFSFileInfo* ) l->data;
                    if ( vfs_file_info_is_dir( file ) )
                    {
                        ask_recursive = gtk_message_dialog_new(
                                            GTK_WINDOW( data->dlg ),
                                            GTK_DIALOG_MODAL,
                                            GTK_MESSAGE_QUESTION,
                                            GTK_BUTTONS_YES_NO,
                                            _( "Do you want to recursively apply these changes to all files and sub-folders?" ) );
                        ptk_file_task_set_recursive( task,
                                ( GTK_RESPONSE_YES == gtk_dialog_run( GTK_DIALOG( ask_recursive ) ) ) );
                        gtk_widget_destroy( ask_recursive );
                        break;
                    }
                }
                */
                if ( mod_change )
                {
                     /* If the permissions of file has been changed by the user */
                    ptk_file_task_set_chmod( task, data->chmod_states );
                }
                /* For chown */
                ptk_file_task_set_chown( task, uid, gid );
                ptk_file_task_run( task );

                /*
                * This file list will be freed by file operation, so we don't
                * need to do this. Just set the pointer to NULL.
                */
                data->file_list = NULL;
            }
        }

        g_free( data->owner_name );
        g_free( data->group_name );
        g_free( data->orig_mtime );
        g_free( data->orig_atime );
        /*
         *NOTE: File operation chmod/chown will free the list when it's done,
         *and we only need to free it when there is no file operation applyed.
        */
        g_slice_free( FilePropertiesDialogData, data );
    }

    gtk_widget_destroy( GTK_WIDGET( dialog ) );
}
int
main (int argc, char **argv)
{
  int num_threads = 10;
  int i;
  GPtrArray *threads = g_ptr_array_new ();
  GPtrArray *surfaces = g_ptr_array_new ();

  if (argc > 1)
    num_threads = atoi (argv[1]);
  if (argc > 2)
    num_iters = atoi (argv[2]);

#if !GLIB_CHECK_VERSION (2, 35, 3)
  g_type_init();
#endif

  g_mutex_lock (&mutex);

  for (i = 0; i < num_threads; i++)
    {
      char buf[10];
      cairo_surface_t *surface = create_surface ();
      g_ptr_array_add (surfaces, surface);
      g_snprintf (buf, sizeof (buf), "%d", i);
      g_ptr_array_add (threads,
		       g_thread_new (buf,
				     thread_func,
				     surface));
    }

  /* Let them loose! */
  g_mutex_unlock (&mutex);

  for (i = 0; i < num_threads; i++)
    g_thread_join (g_ptr_array_index (threads, i));

  g_ptr_array_free (threads, TRUE);

  /* Now, draw a reference image and check results. */
  {
    cairo_surface_t *ref_surface = create_surface ();
    cairo_t *cr = cairo_create (ref_surface);
    PangoLayout *layout = create_layout (cr);
    unsigned char *ref_data = cairo_image_surface_get_data (ref_surface);
    unsigned int len = WIDTH * HEIGHT;

    draw (cr, layout, num_iters - 1);

    g_object_unref (layout);
    cairo_destroy (cr);

    /* cairo_surface_write_to_png (ref_surface, "test-pangocairo-threads-reference.png"); */

    g_assert (WIDTH == cairo_format_stride_for_width (CAIRO_FORMAT_A8, WIDTH));

    for (i = 0; i < num_threads; i++)
      {
	cairo_surface_t *surface = g_ptr_array_index (surfaces, i);
	unsigned char *data = cairo_image_surface_get_data (surface);
	if (memcmp (ref_data, data, len))
	  {
	    fprintf (stderr, "image for thread %d different from reference image.\n", i);
	    cairo_surface_write_to_png (ref_surface, "test-pangocairo-threads-reference.png");
	    cairo_surface_write_to_png (surface, "test-pangocairo-threads-failed.png");
	    return 1;
	  }
	cairo_surface_destroy (surface);
      }

    cairo_surface_destroy (ref_surface);
  }

  g_ptr_array_free (surfaces, TRUE);

  pango_cairo_font_map_set_default (NULL);

  return 0;
}
예제 #18
0
파일: stream.c 프로젝트: cxp1991/WORKING
int stream ()
{
	printf("[stream]\n");
	GThread *video_send, *send_audio, *text_receive, *audio_receive, *check_connection;

	/* Init Glib */
	g_type_init();
	gloop = g_main_loop_new(NULL, FALSE);
	io_stdin = g_io_channel_unix_new(fileno(stdin));

	/* Allocate data */
	RpiData_SendVideo = (Rpi_Data*)malloc(sizeof(Rpi_Data));
	RpiData_SendAudio = (Rpi_Data*)malloc(sizeof(Rpi_Data));
	RpiData_ReceiveAudio = (Rpi_Data*)malloc(sizeof(Rpi_Data));
	RpiData_Text = (Rpi_Data*)malloc(sizeof(Rpi_Data));

	/* Set all flag to FALSE */
	video_send_gathering_done = FALSE;
	send_audio_gathering_done = FALSE;
	receive_audio_gathering_done = FALSE;
	text_gathering_done = FALSE;

	printf("[stream]video_send_gathering_done = %d\n", video_send_gathering_done);
	printf ("		==========	STREAMING	========== \n");
	/* Init video streaming */
	video_send = g_thread_new("send video", &_video_send_main, NULL);
	//send_audio = g_thread_new("send audio", &_send_audio_main, NULL);
	//audio_receive = g_thread_new("receive audio", &_audio_receive_main, NULL);
	//text_receive = g_thread_new("text send+receive", &_text_receive_main, NULL);
	check_connection = g_thread_new("Check if android exit or not", &_check_connection, NULL);

	/* Unalocate all object */
	g_main_loop_run (gloop);

	printf("\n[stream]g_main_loop_quit (gloop);\n");

	/* Free libnice agent & gstreamer pipeline */

	/* Free send video */
	printf("[stream] Agent = %d!\n", RpiData_SendVideo->agent);
	g_object_unref(RpiData_SendVideo->agent);
	gst_object_unref (RpiData_SendVideo->bus);
	gst_element_set_state (RpiData_SendVideo->pipeline, GST_STATE_NULL);
	gst_object_unref (RpiData_SendVideo->pipeline);

//	/* Free send audio */
//	g_object_unref(RpiData_SendAudio->agent);
//	gst_object_unref (RpiData_SendAudio->bus);
//	gst_element_set_state (RpiData_SendAudio->pipeline, GST_STATE_NULL);
//	gst_object_unref (RpiData_SendAudio->pipeline);
//
//	/* Free receive audio */
//	g_object_unref(RpiData_ReceiveAudio->agent);
//	gst_object_unref (RpiData_ReceiveAudio->bus);
//	gst_element_set_state (RpiData_ReceiveAudio->pipeline, GST_STATE_NULL);
//	gst_object_unref (RpiData_ReceiveAudio->pipeline);
//
//	/* Free text */
//	g_object_unref(RpiData_Text->agent);
	//gst_object_unref (RpiData_Text->bus);
	//gst_element_set_state (RpiData_Text->pipeline, GST_STATE_NULL);
	//gst_object_unref (RpiData_Text->pipeline);

	free(RpiData_SendVideo);
//	free(RpiData_SendAudio);
//	free(RpiData_ReceiveAudio);
//	free(RpiData_Text);

	/* Free threads */
	g_thread_join (video_send);
//	g_thread_join (send_audio);
//	g_thread_join (audio_receive);
//	g_thread_join (text_receive);
	g_thread_join (check_connection);
	g_main_loop_unref (gloop);

	return 0;
}
예제 #19
0
static void
arv_gv_stream_finalize (GObject *object)
{
	ArvGvStream *gv_stream = ARV_GV_STREAM (object);

	if (gv_stream->thread != NULL) {
		ArvGvStreamThreadData *thread_data;
		char *statistic_string;

		thread_data = gv_stream->thread_data;

		thread_data->cancel = TRUE;
		g_thread_join (gv_stream->thread);

		g_object_unref (thread_data->device_address);

		statistic_string = arv_statistic_to_string (thread_data->statistic);
		arv_debug_stream (statistic_string);
		g_free (statistic_string);
		arv_statistic_free (thread_data->statistic);

		arv_debug_stream ("[GvStream::finalize] n_completed_buffers    = %u",
				  thread_data->n_completed_buffers);
		arv_debug_stream ("[GvStream::finalize] n_failures             = %u",
				  thread_data->n_failures);
		arv_debug_stream ("[GvStream::finalize] n_timeouts             = %u",
				  thread_data->n_timeouts);
		arv_debug_stream ("[GvStream::finalize] n_aborteds             = %u",
				  thread_data->n_aborteds);
		arv_debug_stream ("[GvStream::finalize] n_underruns            = %u",
				  thread_data->n_underruns);
		arv_debug_stream ("[GvStream::finalize] n_missing_frames       = %u",
				  thread_data->n_missing_frames);

		arv_debug_stream ("[GvStream::finalize] n_size_mismatch_errors = %u",
				  thread_data->n_size_mismatch_errors);

		arv_debug_stream ("[GvStream::finalize] n_received_packets     = %u",
				  thread_data->n_received_packets);
		arv_debug_stream ("[GvStream::finalize] n_missing_packets      = %u",
				  thread_data->n_missing_packets);
		arv_debug_stream ("[GvStream::finalize] n_error_packets        = %u",
				  thread_data->n_error_packets);
		arv_debug_stream ("[GvStream::finalize] n_ignored_packets      = %u",
				  thread_data->n_ignored_packets);

		arv_debug_stream ("[GvStream::finalize] n_resend_requests      = %u",
				  thread_data->n_resend_requests);
		arv_debug_stream ("[GvStream::finalize] n_resent_packets       = %u",
				  thread_data->n_resent_packets);
		arv_debug_stream ("[GvStream::finalize] n_duplicated_packets   = %u",
				  thread_data->n_duplicated_packets);

		g_free (thread_data);

		gv_stream->thread_data = NULL;
		gv_stream->thread = NULL;
	}

	g_object_unref (gv_stream->incoming_address);
	g_object_unref (gv_stream->socket);

	parent_class->finalize (object);
}
예제 #20
0
static GError *
_q_run (struct oio_events_queue_s *self, gboolean (*running) (gboolean pending))
{
	int rc;
	GError *err = NULL;
	void *zctx = NULL, *zpush = NULL, *zpull = NULL, *zagent = NULL;
	GThread *th_gq2zmq = NULL;
	struct _zmq2agent_ctx_s zmq2agent = {0};

	struct _queue_AGENT_s *q = (struct _queue_AGENT_s *)self;
	EXTRA_ASSERT (q != NULL && q->vtable == &vtable_AGENT);

	/* Pair of interconnected sockets between the gq2zmq thread and the
	   zmq2agent thread */
	if (!(zctx = zmq_init (1))) {
		err = SYSERR("ZMQ context init error");
		goto exit;
	}
	if (!(zpush = zmq_socket (zctx, ZMQ_PUSH))) {
		err = SYSERR("ZMQ socket init error (push)");
		goto exit;
	}
	if (!(zpull = zmq_socket (zctx, ZMQ_PULL))) {
		err = SYSERR("ZMQ socket init error (pull)");
		goto exit;
	}
	if (!(zagent = zmq_socket (zctx, ZMQ_DEALER))) {
		err = SYSERR("ZMQ socket init error (agent)");
		goto exit;
	}

	_zset (zpush, ZMQ_LINGER, 1000);
	_zset (zpull, ZMQ_SNDHWM, 16);
	_zset (zpull, ZMQ_RCVHWM, 16);
	_zset (zagent, ZMQ_LINGER, 1000);
	_zset (zagent, ZMQ_SNDBUF, 64*1024);
	_zset (zagent, ZMQ_RCVBUF, 64*1024);
	_zset (zagent, ZMQ_SNDHWM, 64);
	_zset (zagent, ZMQ_RCVHWM, 64);

	if (0 > (rc = zmq_bind (zpush, "inproc://events"))) {
		rc = zmq_errno ();
		err = SYSERR("ZMQ connection error (event-agent) : (%d) %s",
				rc, zmq_strerror (rc));
		goto exit;
	}
	if (0 > (rc = zmq_connect (zpull, "inproc://events"))) {
		rc = zmq_errno ();
		err = SYSERR("ZMQ connection error (event-agent) : (%d) %s",
				rc, zmq_strerror (rc));
		goto exit;
	}
	if (0 > (rc = zmq_connect (zagent, q->url))) {
		rc = zmq_errno ();
		err = SYSERR("ZMQ connection error (event-agent) : (%d) %s",
				rc, zmq_strerror (rc));
		goto exit;
	}

	/* Runs the converter for GAsyncQueue to ZMQ */
	struct _gq2zmq_ctx_s gq2zmq = {
		.queue = q->queue, .q = q, .zpush = zpush, .running = running
	};
	th_gq2zmq = g_thread_try_new("notifier-gq2zmq",
			(GThreadFunc) _gq2zmq_worker, &gq2zmq, &err);
	if (err)
		goto exit;

	/* Runs the events worker */
	zmq2agent.q = q;
	zmq2agent.zpull = zpull;
	zmq2agent.zagent = zagent;
	_zmq2agent_worker (&zmq2agent);

exit:
	if (th_gq2zmq) g_thread_join (th_gq2zmq);
	if (zmq2agent.pending_events) g_list_free_full (zmq2agent.pending_events, g_free);
	if (zagent) zmq_close (zagent);
	if (zpull) zmq_close (zpull);
	if (zpush) zmq_close (zpush);
	if (zctx) zmq_term (zctx);
	return err;
}
예제 #21
0
/*!
  \brief Shuts down any plugin allocated resources (Serial IO/threads/queues,
  etc) and deallocates anything that was allocated with plugin_init(), as well
  as de-registering any enums specific to this plugin. This allows the plugin
  to be safely uninstalled
  */
G_MODULE_EXPORT void plugin_shutdown()
{
	GThread *thread = NULL;
	GCond *cond = NULL;
	GAsyncQueue *queue = NULL;
	GHashTable *hash = NULL;
	GMutex *mutex = NULL;
	gint id = 0;

	ENTER();
	teardown_rtv();
	freeems_serial_disable();

	thread = (GThread *)DATA_GET(global_data,"packet_handler_thread");
	if (thread)
	{
		DATA_SET(global_data,"packet_handler_thread_exit",GINT_TO_POINTER(TRUE));
		g_thread_join(thread);
		DATA_SET(global_data,"packet_handler_thread",NULL);
		DATA_SET(global_data,"packet_handler_thread_exit",NULL);
	}
	queue = (GAsyncQueue *)DATA_GET(global_data,"burn_queue");
	if (queue)
	{
		deregister_packet_queue(PAYLOAD_ID,queue,RESPONSE_BURN_BLOCK_FROM_RAM_TO_FLASH);
		g_async_queue_unref(queue);
		DATA_SET(global_data,"burn_queue",NULL);
		queue = NULL;
	}
	queue = (GAsyncQueue *)DATA_GET(global_data,"FLASH_write_queue");
	if (queue)
	{
		deregister_packet_queue(PAYLOAD_ID,queue,RESPONSE_REPLACE_BLOCK_IN_FLASH);
		g_async_queue_unref(queue);
		DATA_SET(global_data,"FLASH_write_queue",NULL);
		queue = NULL;
	}
	queue = (GAsyncQueue *)DATA_GET(global_data,"RAM_write_queue");
	if (queue)
	{
		deregister_packet_queue(PAYLOAD_ID,queue,RESPONSE_UPDATE_BLOCK_IN_RAM);
		g_async_queue_unref(queue);
		DATA_SET(global_data,"RAM_write_queue",NULL);
		queue = NULL;
	}
	queue = (GAsyncQueue *)DATA_GET(global_data,"packet_queue");
	if (queue)
	{
		g_async_queue_unref(queue);
		DATA_SET(global_data,"packet_queue",NULL);
		queue = NULL;
	}
	hash = (GHashTable *)DATA_GET(global_data,"payload_id_queue_hash");
	if (hash)
		g_hash_table_destroy(hash);
	hash = NULL;
	DATA_SET(global_data,"payload_id_queue_hash",NULL);

	hash = (GHashTable *)DATA_GET(global_data,"sequence_num_queue_hash");
	if (hash)
		g_hash_table_destroy(hash);
	hash = NULL;
	DATA_SET(global_data,"sequence_num_queue_hash",NULL);

	cond = (GCond *)DATA_GET(global_data,"packet_handler_cond");
	if (cond)
		g_cond_free(cond);
	cond = NULL;
	DATA_SET(global_data,"packet_handler_cond",NULL);
	cond = (GCond *)DATA_GET(global_data,"serial_reader_cond");
	if (cond)
		g_cond_free(cond);
	cond = NULL;
	DATA_SET(global_data,"serial_reader_cond",NULL);
	mutex = (GMutex *)DATA_GET(global_data,"queue_mutex");
	if (mutex)
		g_mutex_free(mutex);
	DATA_SET(global_data,"queue_mutex",NULL);
	mutex = (GMutex *)DATA_GET(global_data,"atomic_sequence_mutex");
	if (mutex)
		g_mutex_free(mutex);
	DATA_SET(global_data,"atomic_sequence_mutex",NULL);
	mutex = (GMutex *)DATA_GET(global_data,"rtv_subscriber_mutex");
	if (mutex)
		g_mutex_free(mutex);
	DATA_SET(global_data,"rtv_subscriber_mutex",NULL);

	deregister_common_enums();
	EXIT();
	return;
}
예제 #22
0
void ThreadClass::join ()
{
    if ( ThreadId_ != NULL )
        g_thread_join ( ThreadId_ ) ;
}
예제 #23
0
파일: ssl-test.c 프로젝트: nobled/libsoup
int
main (int argc, char **argv)
{
    int opt, debug = 0, listener, sin_len, port, i;
    struct sockaddr_in sin;
    GThread *server;
    char writebuf[BUFSIZE], readbuf[BUFSIZE];
    SoupAddress *addr;
    SoupSSLCredentials *creds;
    SoupSocket *sock;
    gsize n, total;
    SoupSocketIOStatus status;
    GError *error = NULL;

    g_thread_init (NULL);
    g_type_init ();

    /* On Windows, this will call WSAStartup() */
    soup_socket_get_type ();

    while ((opt = getopt (argc, argv, "c:d:k:")) != -1) {
        switch (opt) {
        case 'c':
            ssl_cert_file = optarg;
            break;
        case 'd':
            debug = atoi (optarg);
            break;
        case 'k':
            ssl_key_file = optarg;
            break;

        case '?':
            fprintf (stderr, "Usage: %s [-d debuglevel] [-c ssl-cert-file] [-k ssl-key-file]\n",
                     argv[0]);
            break;
        }
    }

    if (debug) {
        gnutls_global_set_log_function (debug_log);
        gnutls_global_set_log_level (debug);
    }

    /* Create server socket */
    listener = socket (AF_INET, SOCK_STREAM, 0);
    if (listener == -1) {
        SOCKET_PRINT_ERROR ("creating listening socket");
        exit (1);
    }

    memset (&sin, 0, sizeof (sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;

    if (bind (listener, (struct sockaddr *) &sin, sizeof (sin))  == -1) {
        SOCKET_PRINT_ERROR ("binding listening socket");
        exit (1);
    }

    if (listen (listener, 1) == -1) {
        SOCKET_PRINT_ERROR ("listening on socket");
        exit (1);
    }

    sin_len = sizeof (sin);
    getsockname (listener, (struct sockaddr *)&sin, (void *)&sin_len);
    port = ntohs (sin.sin_port);

    /* Create the client */
    addr = soup_address_new ("127.0.0.1", port);
    creds = soup_ssl_get_client_credentials (NULL);
    sock = soup_socket_new (SOUP_SOCKET_REMOTE_ADDRESS, addr,
                            SOUP_SOCKET_FLAG_NONBLOCKING, FALSE,
                            SOUP_SOCKET_SSL_CREDENTIALS, creds,
                            NULL);
    g_object_unref (addr);
    status = soup_socket_connect_sync (sock, NULL);
    if (status != SOUP_STATUS_OK) {
        g_error ("Could not create client socket: %s",
                 soup_status_get_phrase (status));
    }

    soup_socket_start_ssl (sock, NULL);

    /* Now spawn server thread */
    server = g_thread_create (server_thread, GINT_TO_POINTER (listener),
                              TRUE, NULL);

    /* Synchronous client test */
    for (i = 0; i < BUFSIZE; i++)
        writebuf[i] = i & 0xFF;

    total = 0;
    while (total < BUFSIZE) {
        status = soup_socket_write (sock, writebuf + total,
                                    BUFSIZE - total, &n,
                                    NULL, &error);
        if (status != SOUP_SOCKET_OK)
            g_error ("Sync write got status %d: %s", status,
                     error ? error->message : "(unknown)");
        total += n;
    }

    total = 0;
    while (total < BUFSIZE) {
        status = soup_socket_read (sock, readbuf + total,
                                   BUFSIZE - total, &n,
                                   NULL, &error);
        if (status != SOUP_SOCKET_OK)
            g_error ("Sync read got status %d: %s", status,
                     error ? error->message : "(unknown)");
        total += n;
    }

    if (memcmp (writebuf, readbuf, BUFSIZE) != 0)
        g_error ("Sync read didn't match write");

    printf ("SYNCHRONOUS SSL TEST PASSED\n");

    /* Switch socket to async and do it again */

    g_object_set (sock,
                  SOUP_SOCKET_FLAG_NONBLOCKING, TRUE,
                  NULL);

    g_idle_add (start_writing, sock);
    loop = g_main_loop_new (NULL, TRUE);
    g_main_loop_run (loop);
    g_main_loop_unref (loop);
    g_main_context_unref (g_main_context_default ());

    printf ("ASYNCHRONOUS SSL TEST PASSED\n");

    g_object_unref (sock);
    soup_ssl_free_client_credentials (creds);
    g_thread_join (server);

    /* Success */
    return 0;
}
예제 #24
0
static gboolean mpegts_demuxer_sink_event(GstPad *pad, GstObject *parent, GstEvent *event)
{
    MpegTSDemuxer *demuxer = MPEGTS_DEMUXER(parent);
    gboolean      result = TRUE;

    switch (GST_EVENT_TYPE(event))
    {
        case GST_EVENT_EOS:
#ifdef DEBUG_OUTPUT
            g_print("MpegTS sinkEvent: EOS\n");
#endif
            g_mutex_lock(&demuxer->lock);
            demuxer->is_eos = TRUE;
            g_cond_signal(&demuxer->add_cond); // Signal read callback to read up remaining data.
            g_mutex_unlock(&demuxer->lock);

            gst_event_unref(event);
            break;

        case GST_EVENT_FLUSH_START:
#ifdef DEBUG_OUTPUT
            g_print("MpegTS sinkEvent: FLUSH_START ...");
#endif
            result = gst_pad_event_default(demuxer->sinkpad, parent, event);

            g_mutex_lock(&demuxer->lock);
            demuxer->is_flushing = TRUE;
            g_cond_signal(&demuxer->del_cond); // Signal _chain() and read callback to wake them up and update state.
            g_cond_signal(&demuxer->add_cond);
            g_mutex_unlock(&demuxer->lock);

            if (demuxer->reader_thread)
            {
                g_thread_join(demuxer->reader_thread);
                demuxer->reader_thread = NULL;
            }

#ifdef DEBUG_OUTPUT
            g_print("done.\n");
#endif
            break;

        case GST_EVENT_FLUSH_STOP: // Stop flushing buffers.
            g_mutex_lock(&demuxer->lock);
            mpegts_demuxer_flush(demuxer);
            demuxer->is_flushing = FALSE; // Unset flag so chain function accepts buffers.
            g_mutex_unlock(&demuxer->lock);
            result = gst_pad_event_default(demuxer->sinkpad, parent, event);

#ifdef DEBUG_OUTPUT
            g_print("MpegTS sinkEvent: FLUSH_STOP\n");
#endif
            break;

        case GST_EVENT_SEGMENT:
        {
            GstSegment segment;
            gst_event_copy_segment(event, &segment);
            gst_event_unref(event);

            g_mutex_lock(&demuxer->lock);
            if (!demuxer->is_closing)
            {
#ifdef DEBUG_OUTPUT
                g_print("MpegTS sinkEvent: NEW_SEGMENT, time=%.2f\n",
                        time != GST_CLOCK_TIME_NONE ? (double)time/GST_SECOND : -1.0);
#endif
                if (segment.format == GST_FORMAT_TIME)
                {
                    gst_segment_copy_into(&segment, &demuxer->audio.segment);
                    gst_segment_copy_into(&segment, &demuxer->video.segment);
                }

                demuxer->audio.discont = demuxer->video.discont = TRUE;
                demuxer->is_eos = FALSE;
                demuxer->is_last_buffer_send = FALSE;
                demuxer->is_reading = TRUE;

                if (!demuxer->reader_thread)
                {
                    demuxer->reader_thread = g_thread_new(NULL, mpegts_demuxer_process_input, demuxer);
#ifdef DEBUG_OUTPUT
                    g_print("MpegTS: Process_input thread created\n");
#endif
                }
                else
                    post_message(demuxer, "Demuxer thread is not null", GST_MESSAGE_ERROR, GST_CORE_ERROR, GST_CORE_ERROR_THREAD);
            }
            g_mutex_unlock(&demuxer->lock);
            break;
        }

        default:
            result = mpegts_demuxer_push_to_sources(demuxer, event);
            break;
    }

    return result;
}
예제 #25
0
파일: test8.c 프로젝트: Pecisk/eds-gtasks
gint main (gint argc, gchar **argv)
{
	CamelSession *session;
	gint i, j, index;
	gchar *path;
	CamelStore *store;
	CamelService *service;
	GThread *threads[MAX_THREADS];
	struct _threadinfo *info;
	CamelFolder *folder;
	GPtrArray *uids;
	GError *error = NULL;

	camel_test_init (argc, argv);
	camel_test_provider_init (1, local_drivers);

	/* clear out any camel-test data */
	system ("/bin/rm -rf /tmp/camel-test");

	session = camel_test_session_new ("/tmp/camel-test");

	for (j = 0; j < G_N_ELEMENTS (local_providers); j++) {
		for (index = 0; index < 2; index++) {
			gchar *uid;

			path = g_strdup_printf ("method %s %s", local_providers[j], index?"indexed":"nonindexed");
			camel_test_start (path);
			test_free (path);

			push ("trying %s index %d", local_providers[j], index);
			uid = g_strdup_printf ("test-uid-%d", j);
			path = g_strdup_printf ("%s:///tmp/camel-test/%s", local_providers[j], local_providers[j]);
			service = camel_session_add_service (
				session, uid, path,
				CAMEL_PROVIDER_STORE, &error);
			g_free (uid);
			check_msg (error == NULL, "%s", error->message);
			check (CAMEL_IS_STORE (service));
			store = CAMEL_STORE (service);
			test_free (path);

			if (index == 0)
				folder = camel_store_get_folder_sync (
					store, "testbox",
					CAMEL_STORE_FOLDER_CREATE,
					NULL, &error);
			else
				folder = camel_store_get_folder_sync (
					store, "testbox",
					CAMEL_STORE_FOLDER_CREATE |
					CAMEL_STORE_FOLDER_BODY_INDEX,
					NULL, &error);
			check_msg (error == NULL, "%s", error->message);
			g_clear_error (&error);

			for (i = 0; i < MAX_THREADS; i++) {
				GError *error = NULL;

				info = g_malloc (sizeof (*info));
				info->id = i * MAX_MESSAGES;
				info->folder = folder;

				threads[i] = g_thread_new (NULL, worker, info);
			}

			for (i = 0; i < MAX_THREADS; i++) {
				if (threads[i]) {
					info = g_thread_join (threads[i]);
					g_free (info);
				}
			}
			pull ();

			push ("deleting remaining messages");
			uids = camel_folder_get_uids (folder);
			for (i = 0; i < uids->len; i++) {
				camel_folder_delete_message (folder, uids->pdata[i]);
			}
			camel_folder_free_uids (folder, uids);

			camel_folder_expunge_sync (folder, NULL, &error);
			check_msg (error == NULL, "%s", error->message);

			check_unref (folder, 1);

			camel_store_delete_folder_sync (
				store, "testbox", NULL, &error);
			check_msg (error == NULL, "%s", error->message);
			g_clear_error (&error);

			check_unref (store, 1);

			pull ();

			camel_test_end ();
		}
	}

	g_object_unref (session);

	return 0;
}
static void JoinHelperThread(GThread *thread) {
  GError *error = (GError *) g_thread_join(thread);
  g_assert_no_error(error);
}
예제 #27
0
int main(void)
{
  NiceAgent *lagent = NULL, *ragent = NULL;
  GThread *stun_thread = NULL;
  NiceAddress baseaddr;
  GSource *src;
  int sock;

  g_type_init();

  global_cancellable = g_cancellable_new ();
  src = g_cancellable_source_new (global_cancellable);
  g_source_set_dummy_callback (src);
  g_source_attach (src, NULL);
  g_source_unref (src);

  sock = listen_socket (&stun_port);

  if (sock == -1) {
    g_assert_not_reached ();
  }


#if !GLIB_CHECK_VERSION(2,31,8)
  g_thread_init (NULL);
  stun_thread = g_thread_create (stun_thread_func, GINT_TO_POINTER (sock),
      TRUE, NULL);
 stun_mutex_ptr = g_mutex_new ();
 stun_signal_ptr = g_cond_new ();
#else
  stun_thread = g_thread_new ("listen for STUN requests",
      stun_thread_func, GINT_TO_POINTER (sock));
#endif

  // Once the the thread is forked, we want to listen for a signal 
  // that the socket was opened successfully
  g_mutex_lock (stun_thread_mutex_ptr);
  g_cond_wait (stun_thread_signal_ptr, stun_thread_mutex_ptr); 

  lagent = nice_agent_new (NULL, NICE_COMPATIBILITY_RFC5245);
  ragent = nice_agent_new (NULL, NICE_COMPATIBILITY_RFC5245);

  g_object_set (G_OBJECT (lagent), "controlling-mode", TRUE, NULL);
  g_object_set (G_OBJECT (ragent), "controlling-mode", FALSE, NULL);

  g_object_set (G_OBJECT (lagent), "upnp", USE_UPNP, NULL);
  g_object_set (G_OBJECT (ragent), "upnp", USE_UPNP, NULL);

  g_object_set (G_OBJECT (lagent), "stun-server", "127.0.0.1", NULL);
  g_object_set (G_OBJECT (lagent), "stun-server-port", stun_port, NULL);

  g_object_set_data (G_OBJECT (lagent), "other-agent", ragent);
  g_object_set_data (G_OBJECT (ragent), "other-agent", lagent);

  g_assert (nice_address_set_from_string (&baseaddr, "127.0.0.1"));
  nice_agent_add_local_address (lagent, &baseaddr);
  nice_agent_add_local_address (ragent, &baseaddr);

  g_signal_connect(G_OBJECT(lagent), "candidate-gathering-done",
                   G_CALLBACK(cb_candidate_gathering_done), LEFT_AGENT);
  g_signal_connect(G_OBJECT(ragent), "candidate-gathering-done",
                   G_CALLBACK(cb_candidate_gathering_done), RIGHT_AGENT);
  g_signal_connect(G_OBJECT(lagent), "component-state-changed",
                   G_CALLBACK(cb_component_state_changed), LEFT_AGENT);
  g_signal_connect(G_OBJECT(ragent), "component-state-changed",
                   G_CALLBACK(cb_component_state_changed), RIGHT_AGENT);

  standard_test (lagent, ragent);
  bad_credentials_test (lagent, ragent);
  bad_candidate_test (lagent, ragent);
  new_candidate_test (lagent, ragent);

  // Do this to make sure the STUN thread exits
  exit_stun_thread = TRUE;
  drop_stun_packets = TRUE;
  send_dummy_data ();

  g_object_unref (lagent);
  g_object_unref (ragent);

  g_thread_join (stun_thread);
#if !GLIB_CHECK_VERSION(2,31,8)
  g_mutex_free (stun_mutex_ptr);
  g_cond_free (stun_signal_ptr);
#endif
  g_object_unref (global_cancellable);

  return 0;
}
void janus_source_destroy(void) {
	if (!g_atomic_int_get(&initialized))
		return;
	g_atomic_int_set(&stopping, 1);

	g_async_queue_push(messages, &exit_message);
	if (handler_thread != NULL) {
		g_thread_join(handler_thread);
		handler_thread = NULL;
	}

	g_hash_table_foreach(sessions, janus_source_close_session_func, NULL);
	socket_utils_destroy();

	janus_source_deattach_rtsp_queue_callback(rtsp_server_data);
	
	janus_source_rtsp_clean_and_quit_main_loop(rtsp_server_data);
	
	if (handler_rtsp_thread != NULL) {
		g_thread_join(handler_rtsp_thread);
		handler_rtsp_thread = NULL;
	}
  
	g_free(rtsp_server_data);
	rtsp_server_data = NULL;

	if (keepalive != NULL) {
		g_thread_join(keepalive);
		keepalive = NULL;
	}

	if(keepalive == NULL){
		janus_source_remove_pid_from_registry();
	}

	if (watchdog != NULL) {
		g_thread_join(watchdog);
		watchdog = NULL;
	}

	/* FIXME We should destroy the sessions cleanly */
	janus_mutex_lock(&sessions_mutex);
	g_hash_table_destroy(sessions);
	janus_mutex_unlock(&sessions_mutex);
	g_async_queue_unref(messages);
	messages = NULL;
	sessions = NULL;
	
    /* Free configuration fields */
  if (keepalive_service_url) {
    g_free(keepalive_service_url);
    keepalive_service_url = NULL;
  }
  
	g_free(status_service_url);
	status_service_url = NULL;
 
	g_free(rtsp_interface_ip);
	rtsp_interface_ip = NULL;
 
	curl_cleanup(curl_handle);
	
	g_atomic_int_set(&initialized, 0);
	g_atomic_int_set(&stopping, 0);
	JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_SOURCE_NAME);
}
int
main (int argc, char **argv)
{
    gint i;
    GTest *test1, *test2;
    GArray *test_threads;
    const gint n_threads = 1;

#ifdef SYMBIAN
    g_log_set_handler (NULL,  G_LOG_FLAG_FATAL| G_LOG_FLAG_RECURSION | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG, &mrtLogHandler, NULL);
    g_set_print_handler(mrtPrintHandler);
#endif /*SYMBIAN*/

    g_thread_init (NULL);

#ifndef SYMBIAN
    g_print ("START: %s\n", argv[0]);
#else

#ifdef VERBOSE
    g_print ("START: %s\n", argv[0]);
#endif

#endif /*SYMBIAN*/
    g_log_set_always_fatal (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | g_log_set_always_fatal (G_LOG_FATAL_MASK));
    g_type_init ();

    test1 = g_object_new (G_TYPE_TEST, NULL);
    test2 = g_object_new (G_TYPE_TEST, NULL);

    g_signal_connect (test1, "notify::test-prop", G_CALLBACK (notify), NULL);
    g_signal_connect (test1, "test-signal1", G_CALLBACK (notify), NULL);
    g_signal_connect (test1, "test-signal2", G_CALLBACK (notify), NULL);




#ifndef SYMBIAN
    test_threads = g_array_new (FALSE, FALSE, sizeof (GThread *));

    stopping = FALSE;

    for (i = 0; i < n_threads; i++) {
        GThread *thread;

        thread = g_thread_create ((GThreadFunc) run_thread, test1, TRUE, NULL);
        g_array_append_val (test_threads, thread);

        thread = g_thread_create ((GThreadFunc) run_thread, test2, TRUE, NULL);
        g_array_append_val (test_threads, thread);
    }
    g_usleep (500000);

    stopping = TRUE;

    g_print ("\nstopping\n");

    /* join all threads */
    for (i = 0; i < 2 * n_threads; i++) {
        GThread *thread;

        thread = g_array_index (test_threads, GThread *, i);
        g_thread_join (thread);
    }

    g_print ("stopped:%d\n",TESTNUM);
#else

#ifdef MULTITHREAD

    test_threads = g_array_new (FALSE, FALSE, sizeof (GThread *));
    stopping = FALSE;
    TESTNUM=1;
    notifynum=0;
    handlernum=0;
    for (i = 0; i < n_threads; i++)
    {
        GThread *thread;

        thread = g_thread_create ((GThreadFunc) run_thread, test1, TRUE, NULL);
        g_array_append_val (test_threads, thread);

        thread = g_thread_create ((GThreadFunc) run_thread, test2, TRUE, NULL);
        g_array_append_val (test_threads, thread);
    }
    g_usleep (500000);

    stopping = TRUE;

#ifdef VERBOSE
    g_print ("\nstopping\n");
#endif
    /* join all threads */
    for (i = 0; i < 2 * n_threads; i++)
    {
        GThread *thread;

        thread = g_array_index (test_threads, GThread *, i);
        g_thread_join (thread);
    }

    g_assert(notifynum != 0);
    g_assert(handlernum == 0);

    g_array_free (test_threads, TRUE);

#ifdef VERBOSE
    g_print ("Signals.c: completed for TESTNUM = %d\n",TESTNUM);
#endif



    test_threads = g_array_new (FALSE, FALSE, sizeof (GThread *));
    stopping = FALSE;
    TESTNUM=2;
    notifynum=0;
    handlernum=0;

    for (i = 0; i < n_threads; i++)
    {
        GThread *thread;

        thread = g_thread_create ((GThreadFunc) run_thread, test1, TRUE, NULL);
        g_array_append_val (test_threads, thread);

        thread = g_thread_create ((GThreadFunc) run_thread, test2, TRUE, NULL);
        g_array_append_val (test_threads, thread);
    }
    g_usleep (500000);

    stopping = TRUE;

#ifdef VERBOSE
    g_print ("\nstopping\n");
#endif
    /* join all threads */
    for (i = 0; i < 2 * n_threads; i++)
    {
        GThread *thread;

        thread = g_array_index (test_threads, GThread *, i);
        g_thread_join (thread);
    }

    g_assert(notifynum != 0);
    g_assert(handlernum != 0);

    g_array_free (test_threads, TRUE);

#ifdef VERBOSE
    g_print ("Signals.c: completed for TESTNUM = %d\n",TESTNUM);
#endif


    test_threads = g_array_new (FALSE, FALSE, sizeof (GThread *));
    stopping = FALSE;
    TESTNUM=3;
    notifynum=0;
    handlernum=0;

    for (i = 0; i < n_threads; i++)
    {
        GThread *thread;

        thread = g_thread_create ((GThreadFunc) run_thread, test1, TRUE, NULL);
        g_array_append_val (test_threads, thread);

        thread = g_thread_create ((GThreadFunc) run_thread, test2, TRUE, NULL);
        g_array_append_val (test_threads, thread);
    }
    g_usleep (5000000);

    stopping = TRUE;

#ifdef VERBOSE
    g_print ("\nstopping\n");
#endif
    /* join all threads */
    for (i = 0; i < 2 * n_threads; i++)
    {
        GThread *thread;

        thread = g_array_index (test_threads, GThread *, i);
        g_thread_join (thread);
    }

    g_assert(notifynum != 0);
    g_assert(handlernum == 0);

    g_array_free (test_threads, TRUE);

#ifdef VERBOSE
    g_print ("Signals.c: completed for TESTNUM = %d\n",TESTNUM);
#endif

#else	/* ! MULTITHREAD*/


    TESTNUM=1;
#ifdef VERBOSE
    g_print ("\nStarting with TESTNUM=%d\n",TESTNUM);
#endif

    notifynum=0;
    handlernum=0;
    run_thread(test1);
    g_assert(notifynum == LOOP +1);
    g_assert(handlernum ==0);

    notifynum=0;
    handlernum=0;
    run_thread(test2);
    g_assert(notifynum == 0);
    g_assert(handlernum == 0);

    TESTNUM=2;
#ifdef VERBOSE
    g_print ("\nStarting with TESTNUM=%d\n",TESTNUM);
#endif

    notifynum=0;
    handlernum=0;
    run_thread(test1);
    g_assert(notifynum == LOOP+1);
    g_assert(handlernum == LOOP+1);

    notifynum=0;
    handlernum=0;
    run_thread(test2);
    g_assert(notifynum == 0);
    g_assert(handlernum == LOOP+1);

    TESTNUM=3;
#ifdef VERBOSE
    g_print ("\nStarting with TESTNUM=%d\n",TESTNUM);
#endif

    notifynum=0;
    handlernum=0;
    run_thread(test1);
    g_assert(notifynum == LOOP +1);
    g_assert(handlernum ==0);

    notifynum=0;
    handlernum=0;
    run_thread(test2);
    g_assert(notifynum == 0);
    g_assert(handlernum == 0);

    g_assert(g_signal_has_handler_pending(G_OBJECT(test1),g_signal_lookup("test-signal2",G_TYPE_TEST),NULL,TRUE)==TRUE);
    g_assert(g_signal_has_handler_pending(G_OBJECT(test2),g_signal_lookup("test-signal2",G_TYPE_TEST),NULL,TRUE)==FALSE);

    g_assert(g_signal_handler_is_connected(G_OBJECT(test1),g_signal_lookup("test-signal1",G_TYPE_TEST))==TRUE);
    g_assert(g_signal_handler_is_connected(G_OBJECT(test2),g_signal_lookup("test-signal2",G_TYPE_TEST))==FALSE);

    handlernum=g_signal_lookup("test-signal1",G_TYPE_TEST);
#ifdef VERBOSE
    g_print("Signal id: %d\n",handlernum);
#endif

    g_signal_connect (test2, "test-signal1", G_CALLBACK (notify), NULL);

    hookid=g_signal_add_emission_hook(handlernum,NULL,(GSignalEmissionHook) hook_function,NULL,NULL);

#ifdef VERBOSE
    g_print("Hookid: %d\n",hookid);
#endif
    /********************/

#ifdef TEST_STOP_EMISSION
    /*
    notifynum=0;
    handlernum=0;
    g_print("The following call stops signal emission\n");
    g_signal_stop_emission(G_OBJECT(test1),g_signal_lookup("test-signal1",G_TYPE_TEST),0);

    g_print("The following call should abort and it is normal\n");
    run_thread(test1);
    printf("Notifynum: %d and Handlernum: %d\n",notifynum,handlernum);

    */
    notifynum=0;
    handlernum=0;
    g_signal_stop_emission_by_name(G_OBJECT(test1),"test-signal1");
//run_thread(test1);
    g_print("Notifynum: %d and Handlernum: %d\n",notifynum,handlernum);


#endif /*TEST_STOP_EMISSION*/

    /*******************/


    handlernum=0;
    g_signal_emit(G_OBJECT (test1), g_test_signals[TEST_SIGNAL1], 0, 0);
    g_signal_emit(G_OBJECT (test2), g_test_signals[TEST_SIGNAL1], 0, 0);
    g_assert(handlernum==2);


    g_signal_remove_emission_hook(g_signal_lookup("test-signal1",G_TYPE_TEST),hookid);

#ifdef VERBOSE
    g_print("Emitting signal again after removing emission hook\n");
#endif

    handlernum=0;
    g_signal_emit (G_OBJECT (test1), g_test_signals[TEST_SIGNAL1], 0, 0);
    g_signal_emit (G_OBJECT (test2), g_test_signals[TEST_SIGNAL1], 0, 0);
    g_assert(handlernum==0);

    g_assert (strcmp ("test-signal1", g_signal_name (g_signal_lookup("test-signal1",G_TYPE_TEST))) == 0);
    g_assert (strcmp ("test-signal2", g_signal_name (g_signal_lookup("test-signal2",G_TYPE_TEST))) == 0);


    memset(&gv,0,sizeof(gv));
    g_value_init(&gv,G_TYPE_OBJECT);
    g_value_set_object(&gv,test1);

    gi=0;
    g_signal_list_ids(G_OBJECT_TYPE(test1),&gi);
    g_assert(g_signal_lookup("test-signal1",G_TYPE_TEST)==gi);

    notifynum=0;
    g_signal_emitv (&gv, g_test_signals[TEST_SIGNAL1], 0, &gv);
    g_assert(notifynum==1);

    g_signal_query(g_signal_lookup("test-signal1",G_TYPE_TEST),&gq);
    g_assert(strcmp("test-signal1",gq.signal_name)==0);
    g_assert(g_signal_lookup("test-signal1",G_TYPE_TEST)==gq.signal_id);


    g_assert(g_signal_handler_find(G_OBJECT(test1), G_SIGNAL_RUN_LAST,g_signal_lookup("test-signal2",G_TYPE_TEST),NULL,NULL,NULL,NULL)==2);


    notifynum=g_signal_handlers_block_matched(G_OBJECT(test1),G_SIGNAL_MATCH_FUNC,g_signal_lookup("test-signal2",G_TYPE_TEST),NULL,NULL,(gpointer)G_CALLBACK(notify),NULL);
    handlernum=g_signal_handlers_unblock_matched(G_OBJECT(test1),G_SIGNAL_MATCH_FUNC,g_signal_lookup("test-signal2",G_TYPE_TEST),NULL,NULL,(gpointer)G_CALLBACK(notify),NULL);
    g_assert(notifynum==handlernum);

#endif /*MULTITHREAD*/


#ifdef VERBOSE
    g_printf ("\nsignals-multithread.c: Completed all tests\n");
#endif

#endif /*SYMBIAN*/



#if SYMBIAN
    testResultXml("signals-singlethread");
#endif /* EMULATOR */

    return 0;
}
예제 #30
0
int main(void)
{
  NiceAgent *lagent = NULL, *ragent = NULL;
  GThread *stun_thread = NULL;
  NiceAddress baseaddr;

  g_type_init();

  global_mainloop = g_main_loop_new (NULL, FALSE);

#if !GLIB_CHECK_VERSION(2,31,8)
  g_thread_init (NULL);
  stun_thread = g_thread_create (stun_thread_func,
                                 global_mainloop,
                                 TRUE, NULL);
 stun_mutex_ptr = g_mutex_new ();
 stun_signal_ptr = g_cond_new ();
#else
  stun_thread = g_thread_new ("listen for STUN requests",
                              stun_thread_func, NULL);
#endif

  lagent = nice_agent_new (g_main_loop_get_context (global_mainloop),
      NICE_COMPATIBILITY_RFC5245);
  ragent = nice_agent_new (g_main_loop_get_context (global_mainloop),
      NICE_COMPATIBILITY_RFC5245);

  g_object_set (G_OBJECT (lagent), "controlling-mode", TRUE, NULL);
  g_object_set (G_OBJECT (ragent), "controlling-mode", FALSE, NULL);

  g_object_set (G_OBJECT (lagent), "upnp", USE_UPNP, NULL);
  g_object_set (G_OBJECT (ragent), "upnp", USE_UPNP, NULL);

  g_object_set (G_OBJECT (lagent), "stun-server", "127.0.0.1", NULL);
  g_object_set (G_OBJECT (lagent), "stun-server-port", IPPORT_STUN, NULL);

  g_object_set_data (G_OBJECT (lagent), "other-agent", ragent);
  g_object_set_data (G_OBJECT (ragent), "other-agent", lagent);

  g_assert (nice_address_set_from_string (&baseaddr, "127.0.0.1"));
  nice_agent_add_local_address (lagent, &baseaddr);
  nice_agent_add_local_address (ragent, &baseaddr);

  g_signal_connect(G_OBJECT(lagent), "candidate-gathering-done",
                   G_CALLBACK(cb_candidate_gathering_done), LEFT_AGENT);
  g_signal_connect(G_OBJECT(ragent), "candidate-gathering-done",
                   G_CALLBACK(cb_candidate_gathering_done), RIGHT_AGENT);
  g_signal_connect(G_OBJECT(lagent), "component-state-changed",
                   G_CALLBACK(cb_component_state_changed), LEFT_AGENT);
  g_signal_connect(G_OBJECT(ragent), "component-state-changed",
                   G_CALLBACK(cb_component_state_changed), RIGHT_AGENT);

  standard_test (lagent, ragent);
  bad_credentials_test (lagent, ragent);
  bad_candidate_test (lagent, ragent);
  new_candidate_test (lagent, ragent);

  // Do this to make sure the STUN thread exits
  exit_stun_thread = TRUE;
  drop_stun_packets = TRUE;
  send_dummy_data ();

  g_object_unref (lagent);
  g_object_unref (ragent);

  g_thread_join (stun_thread);
#if !GLIB_CHECK_VERSION(2,31,8)
  g_mutex_free (stun_mutex_ptr);
  g_cond_free (stun_signal_ptr);
#endif
  g_main_loop_unref (global_mainloop);

  return 0;
}