Beispiel #1
0
void
gimp_plug_in_close (GimpPlugIn *plug_in,
                    gboolean    kill_it)
{
  g_return_if_fail (GIMP_IS_PLUG_IN (plug_in));
  g_return_if_fail (plug_in->open);

  plug_in->open = FALSE;

  if (plug_in->pid)
    {
#ifndef G_OS_WIN32
      gint status;
#endif

      /*  Ask the filter to exit gracefully,
          but not if it is closed because of a broken pipe.  */
      if (kill_it && ! plug_in->hup)
        {
          gp_quit_write (plug_in->my_write, plug_in);

          /*  give the plug-in some time (10 ms)  */
          g_usleep (10000);
        }

      /* If necessary, kill the filter. */

#ifndef G_OS_WIN32

      if (kill_it)
        {
          if (plug_in->manager->gimp->be_verbose)
            g_print ("Terminating plug-in: '%s'\n",
                     gimp_file_get_utf8_name (plug_in->file));

          /*  If the plug-in opened a process group, kill the group instead
           *  of only the plug-in, so we kill the plug-in's children too
           */
          if (getpgid (0) != getpgid (plug_in->pid))
            status = kill (- plug_in->pid, SIGKILL);
          else
            status = kill (plug_in->pid, SIGKILL);
        }

      /* Wait for the process to exit. This will happen
       * immediately if it was just killed.
       */
      waitpid (plug_in->pid, &status, 0);

#else /* G_OS_WIN32 */

      if (kill_it)
        {
          /* Trying to avoid TerminateProcess (does mostly work).
           * Otherwise some of our needed DLLs may get into an
           * unstable state (see Win32 API docs).
           */
          DWORD dwExitCode = STILL_ACTIVE;
          DWORD dwTries    = 10;

          while (dwExitCode == STILL_ACTIVE &&
                 GetExitCodeProcess ((HANDLE) plug_in->pid, &dwExitCode) &&
                 (dwTries > 0))
            {
              Sleep (10);
              dwTries--;
            }

          if (dwExitCode == STILL_ACTIVE)
            {
              if (plug_in->manager->gimp->be_verbose)
                g_print ("Terminating plug-in: '%s'\n",
                         gimp_file_get_utf8_name (plug_in->file));

              TerminateProcess ((HANDLE) plug_in->pid, 0);
            }
        }

#endif /* G_OS_WIN32 */

      g_spawn_close_pid (plug_in->pid);
      plug_in->pid = 0;
    }

  /* Remove the input handler. */
  if (plug_in->input_id)
    {
      g_source_remove (plug_in->input_id);
      plug_in->input_id = 0;
    }

  /* Close the pipes. */
  if (plug_in->my_read != NULL)
    {
      g_io_channel_unref (plug_in->my_read);
      plug_in->my_read = NULL;
    }
  if (plug_in->my_write != NULL)
    {
      g_io_channel_unref (plug_in->my_write);
      plug_in->my_write = NULL;
    }
  if (plug_in->his_read != NULL)
    {
      g_io_channel_unref (plug_in->his_read);
      plug_in->his_read = NULL;
    }
  if (plug_in->his_write != NULL)
    {
      g_io_channel_unref (plug_in->his_write);
      plug_in->his_write = NULL;
    }

  gimp_wire_clear_error ();

  while (plug_in->temp_proc_frames)
    {
      GimpPlugInProcFrame *proc_frame = plug_in->temp_proc_frames->data;

#ifdef GIMP_UNSTABLE
      g_printerr ("plug-in '%s' aborted before sending its "
                  "temporary procedure return values\n",
                  gimp_object_get_name (plug_in));
#endif

      if (proc_frame->main_loop &&
          g_main_loop_is_running (proc_frame->main_loop))
        {
          g_main_loop_quit (proc_frame->main_loop);
        }

      /* pop the frame here, because normally this only happens in
       * gimp_plug_in_handle_temp_proc_return(), which can't
       * be called after plug_in_close()
       */
      gimp_plug_in_proc_frame_pop (plug_in);
    }

  if (plug_in->main_proc_frame.main_loop &&
      g_main_loop_is_running (plug_in->main_proc_frame.main_loop))
    {
#ifdef GIMP_UNSTABLE
      g_printerr ("plug-in '%s' aborted before sending its "
                  "procedure return values\n",
                  gimp_object_get_name (plug_in));
#endif

      g_main_loop_quit (plug_in->main_proc_frame.main_loop);
    }

  if (plug_in->ext_main_loop &&
      g_main_loop_is_running (plug_in->ext_main_loop))
    {
#ifdef GIMP_UNSTABLE
      g_printerr ("extension '%s' aborted before sending its "
                  "extension_ack message\n",
                  gimp_object_get_name (plug_in));
#endif

      g_main_loop_quit (plug_in->ext_main_loop);
    }

  /* Unregister any temporary procedures. */
  while (plug_in->temp_procedures)
    gimp_plug_in_remove_temp_proc (plug_in, plug_in->temp_procedures->data);

  gimp_plug_in_manager_remove_open_plug_in (plug_in->manager, plug_in);
}
Beispiel #2
0
void migrate(QOSState *from, QOSState *to, const char *uri)
{
    const char *st;
    QDict *rsp, *sub;
    bool running;

    set_context(from);

    /* Is the machine currently running? */
    rsp = qmp_execute(from->qts, "query-status");
    g_assert(qdict_haskey(rsp, "return"));
    sub = qdict_get_qdict(rsp, "return");
    g_assert(qdict_haskey(sub, "running"));
    running = qdict_get_bool(sub, "running");
    qobject_unref(rsp);

    /* Issue the migrate command. */
    rsp = qtest_qmp(from->qts,
                    "{ 'execute': 'migrate', 'arguments': { 'uri': %s }}",
                    uri);
    g_assert(qdict_haskey(rsp, "return"));
    qobject_unref(rsp);

    /* Wait for STOP event, but only if we were running: */
    if (running) {
        qtest_qmp_eventwait(from->qts, "STOP");
    }

    /* If we were running, we can wait for an event. */
    if (running) {
        migrate_allocator(from->alloc, to->alloc);
        set_context(to);
        qtest_qmp_eventwait(to->qts, "RESUME");
        return;
    }

    /* Otherwise, we need to wait: poll until migration is completed. */
    while (1) {
        rsp = qmp_execute(from->qts, "query-migrate");
        g_assert(qdict_haskey(rsp, "return"));
        sub = qdict_get_qdict(rsp, "return");
        g_assert(qdict_haskey(sub, "status"));
        st = qdict_get_str(sub, "status");

        /* "setup", "active", "completed", "failed", "cancelled" */
        if (strcmp(st, "completed") == 0) {
            qobject_unref(rsp);
            break;
        }

        if ((strcmp(st, "setup") == 0) || (strcmp(st, "active") == 0)) {
            qobject_unref(rsp);
            g_usleep(5000);
            continue;
        }

        fprintf(stderr, "Migration did not complete, status: %s\n", st);
        g_assert_not_reached();
    }

    migrate_allocator(from->alloc, to->alloc);
    set_context(to);
}
Beispiel #3
0
static GstFlowReturn
gst_identity_transform_ip (GstBaseTransform * trans, GstBuffer * buf)
{
  GstFlowReturn ret = GST_FLOW_OK;
  GstIdentity *identity = GST_IDENTITY (trans);
  GstClockTime runtimestamp = G_GINT64_CONSTANT (0);
  gsize size;

  size = gst_buffer_get_size (buf);

  if (identity->check_imperfect_timestamp)
    gst_identity_check_imperfect_timestamp (identity, buf);
  if (identity->check_imperfect_offset)
    gst_identity_check_imperfect_offset (identity, buf);

  /* update prev values */
  identity->prev_timestamp = GST_BUFFER_TIMESTAMP (buf);
  identity->prev_duration = GST_BUFFER_DURATION (buf);
  identity->prev_offset_end = GST_BUFFER_OFFSET_END (buf);
  identity->prev_offset = GST_BUFFER_OFFSET (buf);

  if (identity->error_after >= 0) {
    identity->error_after--;
    if (identity->error_after == 0)
      goto error_after;
  }

  if (identity->drop_probability > 0.0) {
    if ((gfloat) (1.0 * rand () / (RAND_MAX)) < identity->drop_probability)
      goto dropped;
  }

  if (identity->dump) {
    GstMapInfo info;

    gst_buffer_map (buf, &info, GST_MAP_READ);
    gst_util_dump_mem (info.data, info.size);
    gst_buffer_unmap (buf, &info);
  }

  if (!identity->silent) {
    gst_identity_update_last_message_for_buffer (identity, "chain", buf, size);
  }

  if (identity->datarate > 0) {
    GstClockTime time = gst_util_uint64_scale_int (identity->offset,
        GST_SECOND, identity->datarate);

    GST_BUFFER_PTS (buf) = GST_BUFFER_DTS (buf) = time;
    GST_BUFFER_DURATION (buf) = size * GST_SECOND / identity->datarate;
  }

  if (identity->signal_handoffs)
    g_signal_emit (identity, gst_identity_signals[SIGNAL_HANDOFF], 0, buf);

  if (trans->segment.format == GST_FORMAT_TIME)
    runtimestamp = gst_segment_to_running_time (&trans->segment,
        GST_FORMAT_TIME, GST_BUFFER_TIMESTAMP (buf));

  if ((identity->sync) && (trans->segment.format == GST_FORMAT_TIME)) {
    GstClock *clock;

    GST_OBJECT_LOCK (identity);
    if ((clock = GST_ELEMENT (identity)->clock)) {
      GstClockReturn cret;
      GstClockTime timestamp;

      timestamp = runtimestamp + GST_ELEMENT (identity)->base_time;

      /* save id if we need to unlock */
      identity->clock_id = gst_clock_new_single_shot_id (clock, timestamp);
      GST_OBJECT_UNLOCK (identity);

      cret = gst_clock_id_wait (identity->clock_id, NULL);

      GST_OBJECT_LOCK (identity);
      if (identity->clock_id) {
        gst_clock_id_unref (identity->clock_id);
        identity->clock_id = NULL;
      }
      if (cret == GST_CLOCK_UNSCHEDULED)
        ret = GST_FLOW_EOS;
    }
    GST_OBJECT_UNLOCK (identity);
  }

  identity->offset += size;

  if (identity->sleep_time && ret == GST_FLOW_OK)
    g_usleep (identity->sleep_time);

  if (identity->single_segment && (trans->segment.format == GST_FORMAT_TIME)
      && (ret == GST_FLOW_OK)) {
    GST_BUFFER_PTS (buf) = GST_BUFFER_DTS (buf) = runtimestamp;
    GST_BUFFER_OFFSET (buf) = GST_CLOCK_TIME_NONE;
    GST_BUFFER_OFFSET_END (buf) = GST_CLOCK_TIME_NONE;
  }

  return ret;

  /* ERRORS */
error_after:
  {
    GST_ELEMENT_ERROR (identity, CORE, FAILED,
        (_("Failed after iterations as requested.")), (NULL));
    return GST_FLOW_ERROR;
  }
dropped:
  {
    if (!identity->silent) {
      gst_identity_update_last_message_for_buffer (identity, "dropping", buf,
          size);
    }
    /* return DROPPED to basetransform. */
    return GST_BASE_TRANSFORM_FLOW_DROPPED;
  }
}
Beispiel #4
0
int main(int argc,char **argv)
{
	FacqSource *src = NULL;
	FacqSink *sink = NULL;
	FacqStream *stream = NULL;
	GError *err = NULL;
	FacqChanlist *chanlist = NULL;
	FacqOperation *plug = NULL;        

#if GLIB_MINOR_VERSION < 36
        g_type_init();
#endif
#if GLIB_MINOR_VERSION < 32
	g_thread_init(NULL);
#endif

	facq_log_enable();
	facq_log_set_mask(FACQ_LOG_MSG_TYPE_DEBUG);
	facq_log_toggle_out(FACQ_LOG_OUT_STDOUT,NULL);

	src = FACQ_SOURCE(facq_source_soft_new(FACQ_FUNC_TYPE_COS,5,10,0.01,3,&err));

	//src = FACQ_SOURCE(facq_source_comedi_sync_new(0,0,0,500000000,0,0,&err));
	//chanlist = facq_chanlist_new();
	//facq_chanlist_add_chan(chanlist,0,0,AREF_GROUND,0,CHAN_INPUT);
	//facq_chanlist_add_chan(chanlist,1,0,0,0,CHAN_INPUT);
	//facq_chanlist_add_chan(chanlist,2,0,0,0,CHAN_INPUT);
	//src = FACQ_SOURCE(facq_source_comedi_async_new(0,0,0,chanlist,0.01,&err));
	//src = FACQ_SOURCE(facq_source_nidaq_new("Dev1",chanlist,200000,0.000004000,10.0,-10.0,&err));

	if(!src || err)
		goto error;
	sink = FACQ_SINK(facq_sink_file_new("test.baf",&err));
	//chanlist = facq_chanlist_new();
	//facq_chanlist_add_chan(chanlist,0,0,0,0,CHAN_OUTPUT);
	//sink = FACQ_SINK(facq_sink_nidaq_new("Dev1",chanlist,10,-10,&err));
	if(!sink || err)
		goto error;
	
	//plug = FACQ_OPERATION(facq_operation_plug_new("127.0.0.1",3000));

	stream = facq_stream_new("New Stream",32,stop_callback,error_callback,NULL);
	facq_stream_set_source(stream,src);
	//facq_stream_append_operation(stream,plug);
	facq_stream_set_sink(stream,sink);

	if(!facq_stream_start(stream,&err)){
		goto error;
	}
	g_usleep(10*G_USEC_PER_SEC);
	facq_stream_stop(stream);
	facq_stream_free(stream);
	facq_file_to_human("test.baf","test.baf.txt",&err);
	if(err)
		goto error;
	facq_log_disable();
	return 0;

	error:
	if(err)
		facq_log_write(err->message,FACQ_LOG_MSG_TYPE_DEBUG);
	facq_log_disable();
	return 1;
}
Beispiel #5
0
/* make sure our script gets called with the right parameters */
static void
test_pb_utils_install_plugins_do_callout (gchar ** details,
    GstInstallPluginsContext * ctx, const gchar * script,
    GstInstallPluginsReturn expected_result)
{
#ifdef G_OS_UNIX
  GstInstallPluginsReturn ret;
  GError *err = NULL;
  gchar *path;

  path = g_strdup_printf ("%s/gst-plugins-base-unit-test-helper.%s.%lu",
      g_get_tmp_dir (), (g_get_user_name ())? g_get_user_name () : "nobody",
      (gulong) getpid ());

  if (!g_file_set_contents (path, script, -1, &err)) {
    GST_DEBUG ("Failed to write test script to %s: %s", path, err->message);
    g_error_free (err);
    goto done;
  }

  if (chmod (path, S_IRUSR | S_IWUSR | S_IXUSR) != 0) {
    GST_DEBUG ("Could not set mode u+rwx on '%s'", path);
    goto done;
  }

  /* test gst_install_plugins_supported() I */
  g_setenv ("GST_INSTALL_PLUGINS_HELPER", "/i/do/not/ex.ist!", 1);
  fail_if (gst_install_plugins_supported ());

  GST_LOG ("setting GST_INSTALL_PLUGINS_HELPER to '%s'", path);
  g_setenv ("GST_INSTALL_PLUGINS_HELPER", path, 1);

  /* test gst_install_plugins_supported() II */
  fail_unless (gst_install_plugins_supported ());

  /* test sync callout */
  ret = gst_install_plugins_sync (details, ctx);
  fail_unless (ret == GST_INSTALL_PLUGINS_HELPER_MISSING ||
      ret == expected_result,
      "gst_install_plugins_sync() failed with unexpected ret %d, which is "
      "neither HELPER_MISSING nor %d", ret, expected_result);

  /* test async callout */
  marker = -333;
  ret = gst_install_plugins_async (details, ctx, result_cb,
      (gpointer) & marker);
  fail_unless (ret == GST_INSTALL_PLUGINS_HELPER_MISSING ||
      ret == GST_INSTALL_PLUGINS_STARTED_OK,
      "gst_install_plugins_async() failed with unexpected ret %d", ret);
  if (ret == GST_INSTALL_PLUGINS_STARTED_OK) {
    while (marker == -333) {
      g_usleep (500);
      g_main_context_iteration (NULL, FALSE);
    }
    /* and check that the callback was called with the expected code */
    fail_unless_equals_int (marker, expected_result);
  }

done:

  unlink (path);
  g_free (path);
#endif /* G_OS_UNIX */
}
Beispiel #6
0
/* Stop or Pause thread. */
static void *_espeak_stop_or_pause(void *nothing)
{
	int ret;

	log_msg(OTTS_LOG_INFO, "Espeak: Stop or pause thread starting.......");

	/* Block all signals to this thread. */
	set_speaking_thread_parameters();

	while (!espeak_close_requested) {
		/* If semaphore not set, set suspended lock and suspend until it is signaled. */
		if (0 != sem_trywait(espeak_stop_or_pause_semaphore)) {
			pthread_mutex_lock
			    (&espeak_stop_or_pause_suspended_mutex);
			sem_wait(espeak_stop_or_pause_semaphore);
			pthread_mutex_unlock
			    (&espeak_stop_or_pause_suspended_mutex);
		}
		log_msg(OTTS_LOG_INFO, "Espeak: Stop or pause semaphore on.");
		if (espeak_close_requested)
			break;
		if (!espeak_stop_requested) {
			/* This sometimes happens after wake-up from suspend-to-disk.  */
			log_msg(OTTS_LOG_WARN,
				"Espeak: Warning: spurious wake-up  of stop thread.");
			continue;
		}

		pthread_mutex_lock(&playback_queue_mutex);
		pthread_cond_broadcast(&playback_queue_condition);
		pthread_mutex_unlock(&playback_queue_mutex);

		if (module_audio_id) {
			log_msg(OTTS_LOG_WARN, "Espeak: Stopping audio.");
			ret = opentts_audio_stop(module_audio_id);
			DBG_WARN(ret == 0,
				 "spd_audio_stop returned non-zero value.");
			while (is_thread_busy(&espeak_play_suspended_mutex)) {
				ret = opentts_audio_stop(module_audio_id);
				DBG_WARN(ret == 0,
					 "spd_audio_stop returned non-zero value.");
				g_usleep(5000);
			}
		} else {
			while (is_thread_busy(&espeak_play_suspended_mutex)) {
				g_usleep(5000);
			}
		}

		log_msg(OTTS_LOG_INFO,
			"Espeak: Waiting for synthesis to stop.");
		ret = espeak_Cancel();
		DBG_WARN(ret == EE_OK, "Espeak: error in espeak_Cancel().");

		log_msg(OTTS_LOG_DEBUG, "Espeak: Clearing playback queue.");
		espeak_clear_playback_queue();

		int save_pause_state = espeak_pause_state;
		pthread_mutex_lock(&espeak_state_mutex);
		espeak_state_reset();
		pthread_mutex_unlock(&espeak_state_mutex);

		if (save_pause_state == ESPEAK_PAUSE_MARK_REPORTED) {
			module_report_event_pause();
		} else {
			module_report_event_stop();
		}

		log_msg(OTTS_LOG_INFO,
			"Espeak: Stop or pause thread ended.......\n");
	}
	pthread_exit(NULL);
}
Beispiel #7
0
void pull (struct tilda_window_ *tw, enum pull_state state)
{
    DEBUG_FUNCTION ("pull");
    DEBUG_ASSERT (tw != NULL);
    DEBUG_ASSERT (state == PULL_UP || state == PULL_DOWN || state == PULL_TOGGLE);

    gint i;

    if (tw->current_state == UP && state != PULL_UP)
    {
        /* Keep things here just like they are. If you use gtk_window_present() here, you
         * will introduce some weird graphical glitches. Also, calling gtk_window_move()
         * before showing the window avoids yet more glitches. You should probably not use
         * gtk_window_show_all() here, as it takes a long time to execute.
         *
         * Overriding the user time here seems to work a lot better than calling
         * gtk_window_present_with_time() here, or at the end of the function. I have
         * no idea why, they should do the same thing. */
        gdk_x11_window_set_user_time (GTK_WIDGET(tw->window)->window,
                                      tomboy_keybinder_get_current_event_time());
        gtk_window_move (GTK_WINDOW(tw->window), config_getint ("x_pos"), config_getint ("y_pos"));
        gtk_widget_show (GTK_WIDGET(tw->window));

        /* Nasty code to make metacity behave. Starting at metacity-2.22 they "fixed" the
         * focus stealing prevention to make the old _NET_WM_USER_TIME hack
         * not work anymore. This is working for now... */
        tilda_window_set_active (tw);

        /* The window should maintain its properties when it is merely hidden, but it does
         * not. If you delete the following call, the window will not remain visible
         * on all workspaces after pull()ing it up and down a number of times.
         *
         * Note that the "Always on top" property doesn't seem to go away, only this
         * property (Show on all desktops) does... */
        if (config_getbool ("pinned"))
            gtk_window_stick (GTK_WINDOW (tw->window));

        if (config_getbool ("animation"))
        {
            for (i=0; i<16; i++)
            {
                gtk_window_move (GTK_WINDOW(tw->window), posIV[2][i], posIV[0][i]);
                gtk_window_resize (GTK_WINDOW(tw->window), posIV[3][i], posIV[1][i]);

                process_all_pending_gtk_events ();
                g_usleep (config_getint ("slide_sleep_usec"));
            }
        }

        debug_printf ("pull(): MOVED DOWN\n");
        tw->current_state = DOWN;
    }
    else if (state != PULL_DOWN)
    {
        if (config_getbool ("animation"))
        {
            for (i=15; i>=0; i--)
            {
                gtk_window_move (GTK_WINDOW(tw->window), posIV[2][i], posIV[0][i]);
                gtk_window_resize (GTK_WINDOW(tw->window), posIV[3][i], posIV[1][i]);

                process_all_pending_gtk_events ();
                g_usleep (config_getint ("slide_sleep_usec"));
            }
        }

        /* All we have to do at this point is hide the window.
         * Case 1 - Animation on:  The window has shrunk, just hide it
         * Case 2 - Animation off: Just hide the window */
        gtk_widget_hide (GTK_WIDGET(tw->window));

        debug_printf ("pull(): MOVED UP\n");
        tw->current_state = UP;
    }
}
Beispiel #8
0
void *
volume_thread(void * arg) {

	volume_t * vol = (volume_t *)arg;

	GList * node;

	float * samples = NULL;
	unsigned long numread;
	float chunk_power = 0.0f;
	float rms;
	unsigned long i;


	AQUALUNG_THREAD_DETACH();

	for (node = vol->queue; node; node = node->next) {

		vol->item = (vol_item_t *)node->data;

		if (process_volume_setup(vol)) {
			continue;
		}

		if ((samples = (float *)malloc(vol->chunk_size * vol->fdec->fileinfo.channels * sizeof(float))) == NULL) {

			fprintf(stderr, "volume_thread(): malloc() error\n");
			file_decoder_close(vol->fdec);
			file_decoder_delete(vol->fdec);
			free(vol->rms);
			break;
		}

		do {
			numread = file_decoder_read(vol->fdec, samples, vol->chunk_size);
			vol->chunks_read++;
			
			/* calculate signal power of chunk and feed it in the rms envelope */
			if (numread > 0) {
				for (i = 0; i < numread * vol->fdec->fileinfo.channels; i++) {
					chunk_power += samples[i] * samples[i];
				}
				chunk_power /= numread * vol->fdec->fileinfo.channels;
				
				rms = rms_env_process(vol->rms, chunk_power);
				
				if (rms > vol->result) {
					vol->result = rms;
				}
			}
			
			while (vol->paused && !vol->cancelled) {
				g_usleep(500000);
			}

		} while (numread == vol->chunk_size && !vol->cancelled);

		if (!vol->cancelled) {
					
			vol->result = 20.0f * log10f(vol->result);
					
#ifdef HAVE_MPEG
			/* compensate for anti-clip vol.reduction in dec_mpeg.c/mpeg_output() */
			if (vol->fdec->file_lib == MAD_LIB) {
				vol->result += 1.8f;
			}
#endif /* HAVE_MPEG */

			if (vol->type == VOLUME_SEPARATE) {

				AQUALUNG_MUTEX_LOCK(vol->wait_mutex);
				aqualung_idle_add(vol_store_result_sep, vol);
				AQUALUNG_COND_WAIT(vol->thread_wait, vol->wait_mutex);
				AQUALUNG_MUTEX_UNLOCK(vol->wait_mutex);

			} else if (vol->type == VOLUME_AVERAGE) {

				vol->n_volumes++;
				if ((vol->volumes = realloc(vol->volumes, vol->n_volumes * sizeof(float))) == NULL) {
					fprintf(stderr, "volume_thread(): realloc error\n");
					return NULL;
				}
				vol->volumes[vol->n_volumes - 1] = vol->result;
			}
		}

		file_decoder_close(vol->fdec);
		file_decoder_delete(vol->fdec);
		free(vol->rms);

		free(samples);

		if (vol->cancelled) {
			break;
		}
	}

	if (!vol->cancelled && vol->type == VOLUME_AVERAGE) {
		AQUALUNG_MUTEX_LOCK(vol->wait_mutex);
		aqualung_idle_add(vol_store_result_avg, vol);
		AQUALUNG_COND_WAIT(vol->thread_wait, vol->wait_mutex);
		AQUALUNG_MUTEX_UNLOCK(vol->wait_mutex);
	}

	for (node = vol->queue; node; node = node->next) {
		vol_item_free((vol_item_t *)node->data);
	}

	aqualung_idle_add(volume_finalize, vol);


	return NULL;
}
Beispiel #9
0
static int dev_open(struct sr_dev_inst *sdi)
{
	struct sr_dev_driver *di = sdi->driver;
	struct sr_usb_dev_inst *usb;
	struct dev_context *devc;
	int ret;
	int64_t timediff_us, timediff_ms;

	devc = sdi->priv;
	usb = sdi->conn;

	/*
	 * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
	 * milliseconds for the FX2 to renumerate.
	 */
	ret = SR_ERR;
	if (devc->fw_updated > 0) {
		sr_info("Waiting for device to reset.");
		/* Takes >= 300ms for the FX2 to be gone from the USB bus. */
		g_usleep(300 * 1000);
		timediff_ms = 0;
		while (timediff_ms < MAX_RENUM_DELAY_MS) {
			if ((ret = fx2lafw_dev_open(sdi, di)) == SR_OK)
				break;
			g_usleep(100 * 1000);

			timediff_us = g_get_monotonic_time() - devc->fw_updated;
			timediff_ms = timediff_us / 1000;
			sr_spew("Waited %" PRIi64 "ms.", timediff_ms);
		}
		if (ret != SR_OK) {
			sr_err("Device failed to renumerate.");
			return SR_ERR;
		}
		sr_info("Device came back after %" PRIi64 "ms.", timediff_ms);
	} else {
		sr_info("Firmware upload was not needed.");
		ret = fx2lafw_dev_open(sdi, di);
	}

	if (ret != SR_OK) {
		sr_err("Unable to open device.");
		return SR_ERR;
	}

	ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
	if (ret != 0) {
		switch (ret) {
		case LIBUSB_ERROR_BUSY:
			sr_err("Unable to claim USB interface. Another "
			       "program or driver has already claimed it.");
			break;
		case LIBUSB_ERROR_NO_DEVICE:
			sr_err("Device has been disconnected.");
			break;
		default:
			sr_err("Unable to claim interface: %s.",
			       libusb_error_name(ret));
			break;
		}

		return SR_ERR;
	}

	if (devc->cur_samplerate == 0) {
		/* Samplerate hasn't been set; default to the slowest one. */
		devc->cur_samplerate = devc->samplerates[0];
	}

	return SR_OK;
}
Beispiel #10
0
int32_t dt_camera_capture_job_run(dt_job_t *job)
{
  dt_camera_capture_t *t=(dt_camera_capture_t*)job->param;
  int total = t->brackets ? t->count * t->brackets : t->count;
  char message[512]= {0};
  double fraction=0;
  snprintf(message, 512, ngettext ("capturing %d image", "capturing %d images", total), total );

  /* try to get exp program mode for nikon */
  char *expprogram = (char *)dt_camctl_camera_get_property(darktable.camctl, NULL, "expprogram");

  /* if fail, lets try fetching mode for cannon */
  if(!expprogram)
    expprogram = (char *)dt_camctl_camera_get_property(darktable.camctl, NULL, "autoexposuremode");

  /* Fetch all values for shutterspeed and initialize current value */
  GList *values=NULL;
  gconstpointer original_value=NULL;
  const char *cvalue = dt_camctl_camera_get_property(darktable.camctl, NULL, "shutterspeed");
  const char *value = dt_camctl_camera_property_get_first_choice(darktable.camctl, NULL, "shutterspeed");

  /* get values for bracketing */
  if (t->brackets && expprogram && expprogram[0]=='M' && value && cvalue)
  {
    do
    {
      // Add value to list
      values = g_list_append(values, g_strdup(value));
      // Check if current values is the same as original value, then lets store item ptr
      if (strcmp(value,cvalue) == 0)
        original_value = g_list_last(values)->data;
    }
    while ((value = dt_camctl_camera_property_get_next_choice(darktable.camctl, NULL, "shutterspeed")) != NULL);
  }
  else
  {
    /* if this was an intended bracket capture bail out */
    if(t->brackets)
    {
      dt_control_log(_("please set your camera to manual mode first!"));
      return 1;
    }
  }

  /* create the bgjob plate */
  const guint *jid  = dt_control_backgroundjobs_create(darktable.control, 0, message);

  GList *current_value = g_list_find(values,original_value);
  for(uint32_t i=0; i<t->count; i++)
  {
    // Delay if active
    if(t->delay)
      g_usleep(t->delay*G_USEC_PER_SEC);

    for(uint32_t b=0; b<(t->brackets*2)+1; b++)
    {
      // If bracket capture, lets set change shutterspeed
      if (t->brackets)
      {
        if (b == 0)
        {
          // First bracket, step down time with (steps*brackets), also check so we never set the longest shuttertime which would be bulb mode
          for(uint32_t s=0; s<(t->steps*t->brackets); s++)
            if (g_list_next(current_value) && g_list_next(g_list_next(current_value)))
              current_value = g_list_next(current_value);
        }
        else
        {
          // Step up with (steps)
          for(uint32_t s=0; s<t->steps; s++)
            if(g_list_previous(current_value))
              current_value = g_list_previous(current_value);
        }
      }

      // set the time property for bracket capture
      if (t->brackets && current_value)
        dt_camctl_camera_set_property_string(darktable.camctl, NULL, "shutterspeed", current_value->data);

      // Capture image
      dt_camctl_camera_capture(darktable.camctl,NULL);

      fraction += 1.0/total;
      dt_control_backgroundjobs_progress(darktable.control, jid, fraction);
    }

    // lets reset to original value before continue
    if (t->brackets)
    {
      current_value = g_list_find(values,original_value);
      dt_camctl_camera_set_property_string(darktable.camctl, NULL, "shutterspeed", current_value->data);
    }
  }

  dt_control_backgroundjobs_destroy(darktable.control, jid);


  // free values
  if(values)
  {
    g_list_free_full(values, g_free);
  }

  return 0;
}
Beispiel #11
0
static GstFlowReturn
gst_identity_transform_ip (GstBaseTransform * trans, GstBuffer * buf)
{
  GstFlowReturn ret = GST_FLOW_OK;
  GstIdentity *identity = GST_IDENTITY (trans);
  GstClockTime runtimestamp = G_GINT64_CONSTANT (0);

  if (identity->check_perfect)
    gst_identity_check_perfect (identity, buf);
  if (identity->check_imperfect_timestamp)
    gst_identity_check_imperfect_timestamp (identity, buf);
  if (identity->check_imperfect_offset)
    gst_identity_check_imperfect_offset (identity, buf);

  /* update prev values */
  identity->prev_timestamp = GST_BUFFER_TIMESTAMP (buf);
  identity->prev_duration = GST_BUFFER_DURATION (buf);
  identity->prev_offset_end = GST_BUFFER_OFFSET_END (buf);
  identity->prev_offset = GST_BUFFER_OFFSET (buf);

  if (identity->error_after >= 0) {
    identity->error_after--;
    if (identity->error_after == 0) {
      GST_ELEMENT_ERROR (identity, CORE, FAILED,
          (_("Failed after iterations as requested.")), (NULL));
      return GST_FLOW_ERROR;
    }
  }

  if (identity->drop_probability > 0.0) {
    if ((gfloat) (1.0 * rand () / (RAND_MAX)) < identity->drop_probability) {
      if (!identity->silent) {
        GST_OBJECT_LOCK (identity);
        g_free (identity->last_message);
        identity->last_message =
            g_strdup_printf
            ("dropping   ******* (%s:%s)i (%d bytes, timestamp: %"
            GST_TIME_FORMAT ", duration: %" GST_TIME_FORMAT ", offset: %"
            G_GINT64_FORMAT ", offset_end: % " G_GINT64_FORMAT
            ", flags: %d) %p", GST_DEBUG_PAD_NAME (trans->sinkpad),
            GST_BUFFER_SIZE (buf), GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
            GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf),
            GST_BUFFER_OFFSET_END (buf), GST_BUFFER_FLAGS (buf), buf);
        GST_OBJECT_UNLOCK (identity);
        gst_identity_notify_last_message (identity);
      }
      /* return DROPPED to basetransform. */
      return GST_BASE_TRANSFORM_FLOW_DROPPED;
    }
  }

  if (identity->dump) {
    gst_util_dump_mem (GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
  }

  if (!identity->silent) {
    GST_OBJECT_LOCK (identity);
    g_free (identity->last_message);
    identity->last_message =
        g_strdup_printf ("chain   ******* (%s:%s)i (%d bytes, timestamp: %"
        GST_TIME_FORMAT ", duration: %" GST_TIME_FORMAT ", offset: %"
        G_GINT64_FORMAT ", offset_end: % " G_GINT64_FORMAT ", flags: %d) %p",
        GST_DEBUG_PAD_NAME (trans->sinkpad), GST_BUFFER_SIZE (buf),
        GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
        GST_TIME_ARGS (GST_BUFFER_DURATION (buf)),
        GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET_END (buf),
        GST_BUFFER_FLAGS (buf), buf);
    GST_OBJECT_UNLOCK (identity);
    gst_identity_notify_last_message (identity);
  }

  if (identity->datarate > 0) {
    GstClockTime time = gst_util_uint64_scale_int (identity->offset,
        GST_SECOND, identity->datarate);

    GST_BUFFER_TIMESTAMP (buf) = time;
    GST_BUFFER_DURATION (buf) =
        GST_BUFFER_SIZE (buf) * GST_SECOND / identity->datarate;
  }

  if (identity->signal_handoffs)
    g_signal_emit (identity, gst_identity_signals[SIGNAL_HANDOFF], 0, buf);

  if (trans->segment.format == GST_FORMAT_TIME)
    runtimestamp = gst_segment_to_running_time (&trans->segment,
        GST_FORMAT_TIME, GST_BUFFER_TIMESTAMP (buf));

  if ((identity->sync) && (trans->segment.format == GST_FORMAT_TIME)) {
    GstClock *clock;

    GST_OBJECT_LOCK (identity);
    if ((clock = GST_ELEMENT (identity)->clock)) {
      GstClockReturn cret;
      GstClockTime timestamp;

      timestamp = runtimestamp + GST_ELEMENT (identity)->base_time;

      /* save id if we need to unlock */
      /* FIXME: actually unlock this somewhere in the state changes */
      identity->clock_id = gst_clock_new_single_shot_id (clock, timestamp);
      GST_OBJECT_UNLOCK (identity);

      cret = gst_clock_id_wait (identity->clock_id, NULL);

      GST_OBJECT_LOCK (identity);
      if (identity->clock_id) {
        gst_clock_id_unref (identity->clock_id);
        identity->clock_id = NULL;
      }
      if (cret == GST_CLOCK_UNSCHEDULED)
        ret = GST_FLOW_UNEXPECTED;
    }
    GST_OBJECT_UNLOCK (identity);
  }

  identity->offset += GST_BUFFER_SIZE (buf);

  if (identity->sleep_time && ret == GST_FLOW_OK)
    g_usleep (identity->sleep_time);

  if (identity->single_segment && (trans->segment.format == GST_FORMAT_TIME)
      && (ret == GST_FLOW_OK)) {
    GST_BUFFER_TIMESTAMP (buf) = runtimestamp;
    GST_BUFFER_OFFSET (buf) = GST_CLOCK_TIME_NONE;
    GST_BUFFER_OFFSET_END (buf) = GST_CLOCK_TIME_NONE;
  }

  return ret;
}
Beispiel #12
0
static void
test_gpoll (void)
{
  SOCKET sockets[NUM_POLLEES];
  GPollFD fds[NUM_POLLFDS];
  SOCKET opp_sockets[NUM_POLLEES];
  gint i;
  gint activatable;
  gint64 times[REPEAT][2];
#define BUCKET_COUNT 25
  gint64 bucket_limits[BUCKET_COUNT] = {3, 5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 70, 80, 90, 100, 120, 150, 180, 220, 280, 350, 450, 600, 800, 1000};
  gint   buckets[BUCKET_COUNT];
  gint64 times_avg = 0, times_min = G_MAXINT64, times_max = 0;

  prepare_sockets (sockets, opp_sockets, fds, NUM_POLLEES);
  prepare_fds (sockets, fds, NUM_POLLEES);

  times_avg = 0;
  times_min = G_MAXINT64;
  times_max = 0;
  memset (buckets, 0, sizeof (gint) * BUCKET_COUNT);

  for (i = 0; i < REPEAT; i++)
    {
      gint r;
      gint64 diff;

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      times[i][0] = g_get_monotonic_time ();
      r = g_poll (fds, NUM_POLLFDS, 0);
      times[i][1] = g_get_monotonic_time ();
      g_assert (r == 0);
      diff = times[i][1] - times[i][0];
      if (times_min > diff)
        times_min = diff;
      if (times_max < diff)
        times_max = diff;
      times_avg += diff;
      bucketize (diff, buckets, bucket_limits, BUCKET_COUNT);
    }

  times_avg /= NUM_POLLEES;
  g_print ("\nempty poll time:\n%4lldns - %4lldns, average %4lldns\n", times_min, times_max, times_avg);
  print_buckets (buckets, bucket_limits, BUCKET_COUNT);

  times_avg = 0;
  times_min = G_MAXINT64;
  times_max = 0;
  memset (buckets, 0, sizeof (gint) * BUCKET_COUNT);

  activatable = 0;

  for (i = 0; i < REPEAT; i++)
    {
      gint r, s, v, t;
      gint64 diff;
      MSG msg;
      gboolean found_app;

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      s = send (opp_sockets[activatable], (const char *) &t, 1, 0);
      g_assert (PostMessage (NULL, WM_APP, 1, 2));
      /* This is to ensure that all sockets catch up, otherwise some might not poll active */
      g_usleep (G_USEC_PER_SEC / 1000);

      times[i][0] = g_get_monotonic_time ();
      r = g_poll (fds, NUM_POLLFDS, 1000);
      times[i][1] = g_get_monotonic_time ();

      check_fds (sockets, fds, NUM_POLLEES);
      v = recv (sockets[activatable], (char *) &t, 1, 0);
      found_app = FALSE;
      while (!found_app && PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
        if (msg.message == WM_APP && msg.wParam == 1 && msg.lParam == 2)
          found_app = TRUE;
      g_assert (s == 1);
      g_assert (r == 2);
      g_assert (v == 1);
      g_assert (found_app);

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      r = g_poll (fds, NUM_POLLFDS, 0);
      check_fds (sockets, fds, NUM_POLLEES);
      g_assert (r == 0);
      diff = times[i][1] - times[i][0];
      if (times_min > diff)
        times_min = diff;
      if (times_max < diff)
        times_max = diff;
      times_avg += diff;
      activatable = (activatable + 1) % NUM_POLLEES;
      bucketize (diff, buckets, bucket_limits, BUCKET_COUNT);
    }

  times_avg /= NUM_POLLEES;
  g_print ("1-socket + msg poll time:\n%4lldns - %4lldns, average %4lldns\n", times_min, times_max, times_avg);
  print_buckets (buckets, bucket_limits, BUCKET_COUNT);

  times_avg = 0;
  times_min = G_MAXINT64;
  times_max = 0;
  memset (buckets, 0, sizeof (gint) * BUCKET_COUNT);

  activatable = 0;

  for (i = 0; i < REPEAT; i++)
    {
      gint r, s, v, t;
      gint64 diff;

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      s = send (opp_sockets[activatable], (const char *) &t, 1, 0);

      g_usleep (G_USEC_PER_SEC / 1000);

      times[i][0] = g_get_monotonic_time ();
      r = g_poll (fds, NUM_POLLFDS, 1000);
      times[i][1] = g_get_monotonic_time ();

      check_fds (sockets, fds, NUM_POLLEES);
      v = recv (sockets[activatable], (char *) &t, 1, 0);
      g_assert (s == 1);
      g_assert (r == 1);
      g_assert (v == 1);

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      r = g_poll (fds, NUM_POLLFDS, 0);
      check_fds (sockets, fds, NUM_POLLEES);
      g_assert (r == 0);

      diff = times[i][1] - times[i][0];
      if (times_min > diff)
        times_min = diff;
      if (times_max < diff)
        times_max = diff;
      times_avg += diff;
      activatable = (activatable + 1) % NUM_POLLEES;
      bucketize (diff, buckets, bucket_limits, BUCKET_COUNT);
    }

  times_avg /= NUM_POLLEES;
  g_print ("1-socket poll time:\n%4lldns - %4lldns, average %4lldns\n", times_min, times_max, times_avg);
  print_buckets (buckets, bucket_limits, BUCKET_COUNT);

  times_avg = 0;
  times_min = G_MAXINT64;
  times_max = 0;
  memset (buckets, 0, sizeof (gint) * BUCKET_COUNT);

  for (i = 0; i < REPEAT; i++)
    {
      gint r, s, v, t;
      gint64 diff;
      gint j;

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      s = v = 0;

      for (j = 0; j < NUM_POLLEES / 2; j++)
        s += send (opp_sockets[j], (const char *) &t, 1, 0) == 1 ? 1 : 0;

      g_usleep (G_USEC_PER_SEC / 1000);

      times[i][0] = g_get_monotonic_time ();
      r = g_poll (fds, NUM_POLLFDS, 1000);
      times[i][1] = g_get_monotonic_time ();
      check_fds (sockets, fds, NUM_POLLEES);
      for (j = 0; j < NUM_POLLEES / 2; j++)
        v += recv (sockets[j], (char *) &t, 1, 0) == 1 ? 1 : 0;
      g_assert (s == NUM_POLLEES / 2);
      g_assert (r == NUM_POLLEES / 2);
      g_assert (v == NUM_POLLEES / 2);

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      r = g_poll (fds, NUM_POLLFDS, 0);
      check_fds (sockets, fds, NUM_POLLEES);
      g_assert (r == 0);

      diff = times[i][1] - times[i][0];
      if (times_min > diff)
        times_min = diff;
      if (times_max < diff)
        times_max = diff;
      times_avg += diff;
      bucketize (diff, buckets, bucket_limits, BUCKET_COUNT);
    }

  times_avg /= NUM_POLLEES;
  g_print ("half-socket poll time:\n%4lldns - %4lldns, average %4lldns\n", times_min, times_max, times_avg);
  print_buckets (buckets, bucket_limits, BUCKET_COUNT);

  times_avg = 0;
  times_min = G_MAXINT64;
  times_max = 0;
  memset (buckets, 0, sizeof (gint) * BUCKET_COUNT);

  for (i = 0; i < REPEAT; i++)
    {
      gint r, s, v, t;
      gint64 diff;
      gint j;
      MSG msg;
      gboolean found_app;

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      s = v = 0;

      for (j = 0; j < NUM_POLLEES / 2; j++)
        s += send (opp_sockets[j], (const char *) &t, 1, 0) == 1 ? 1 : 0;
      g_assert (PostMessage (NULL, WM_APP, 1, 2));

      /* This is to ensure that all sockets catch up, otherwise some might not poll active */
      g_usleep (G_USEC_PER_SEC / 1000);

      times[i][0] = g_get_monotonic_time ();
      r = g_poll (fds, NUM_POLLFDS, 1000);
      times[i][1] = g_get_monotonic_time ();
      check_fds (sockets, fds, NUM_POLLEES);
      for (j = 0; j < NUM_POLLEES / 2; j++)
        v += recv (sockets[j], (char *) &t, 1, 0) == 1 ? 1 : 0;
      found_app = FALSE;
      while (!found_app && PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
        if (msg.message == WM_APP && msg.wParam == 1 && msg.lParam == 2)
          found_app = TRUE;
      g_assert (s == NUM_POLLEES / 2);
      g_assert (r == NUM_POLLEES / 2 + 1);
      g_assert (v == NUM_POLLEES / 2);
      g_assert (found_app);

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      r = g_poll (fds, NUM_POLLFDS, 0);
      check_fds (sockets, fds, NUM_POLLEES);
      g_assert (r == 0);

      diff = times[i][1] - times[i][0];
      if (times_min > diff)
        times_min = diff;
      if (times_max < diff)
        times_max = diff;
      times_avg += diff;
      bucketize (diff, buckets, bucket_limits, BUCKET_COUNT);
    }

  times_avg /= NUM_POLLEES;
  g_print ("half-socket + msg poll time:\n%4lldns - %4lldns, average %4lldns\n", times_min, times_max, times_avg);
  print_buckets (buckets, bucket_limits, BUCKET_COUNT);

  times_avg = 0;
  times_min = G_MAXINT64;
  times_max = 0;
  memset (buckets, 0, sizeof (gint) * BUCKET_COUNT);

  for (i = 0; i < REPEAT; i++)
    {
      gint r, s, v, t;
      gint64 diff;
      gint j;

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      s = v = 0;

      for (j = 0; j < NUM_POLLEES; j++)
        s += send (opp_sockets[j], (const char *) &t, 1, 0) == 1 ? 1 : 0;

      g_usleep (G_USEC_PER_SEC / 1000);

      times[i][0] = g_get_monotonic_time ();
      r = g_poll (fds, NUM_POLLFDS, 1000);
      times[i][1] = g_get_monotonic_time ();
      check_fds (sockets, fds, NUM_POLLEES);
      for (j = 0; j < NUM_POLLEES; j++)
        v += recv (sockets[j], (char *) &t, 1, 0) == 1 ? 1 : 0;
      g_assert (s == NUM_POLLEES);
      g_assert (r == NUM_POLLEES);
      g_assert (v == NUM_POLLEES);

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      r = g_poll (fds, NUM_POLLFDS, 0);
      check_fds (sockets, fds, NUM_POLLEES);
      g_assert (r == 0);

      diff = times[i][1] - times[i][0];
      if (times_min > diff)
        times_min = diff;
      if (times_max < diff)
        times_max = diff;
      times_avg += diff;
      bucketize (diff, buckets, bucket_limits, BUCKET_COUNT);
    }

  times_avg /= NUM_POLLEES;
  g_print ("%d-socket poll time: \n%4lldns - %4lldns, average %4lldns\n", NUM_POLLEES, times_min, times_max, times_avg);
  print_buckets (buckets, bucket_limits, BUCKET_COUNT);

  activatable = 0;
  times_avg = 0;
  times_min = G_MAXINT64;
  times_max = 0;
  memset (buckets, 0, sizeof (gint) * BUCKET_COUNT);

  for (i = 0; i < REPEAT; i++)
    {
      gint r, s, v, t;
      gint64 diff;
      gint j;
      MSG msg;
      gboolean found_app;

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      s = v = 0;

      for (j = 0; j < activatable; j++)
        s += send (opp_sockets[j], (const char *) &t, 1, 0) == 1 ? 1 : 0;
      g_assert (PostMessage (NULL, WM_APP, 1, 2));

      g_usleep (G_USEC_PER_SEC / 1000);

      times[i][0] = g_get_monotonic_time ();
      r = g_poll (fds, NUM_POLLFDS, 1000);
      times[i][1] = g_get_monotonic_time ();
      check_fds (sockets, fds, NUM_POLLEES);
      for (j = 0; j < activatable; j++)
        v += recv (sockets[j], (char *) &t, 1, 0) == 1 ? 1 : 0;
      found_app = FALSE;
      while (!found_app && PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
        if (msg.message == WM_APP && msg.wParam == 1 && msg.lParam == 2)
          found_app = TRUE;
      g_assert (s == activatable);
      g_assert (r == activatable + 1);
      g_assert (v == activatable);
      g_assert (found_app);

      reset_fds (fds, NUM_POLLEES);
      reset_fds_msg (fds, NUM_POLLFDS);
      r = g_poll (fds, NUM_POLLFDS, 0);
      check_fds (sockets, fds, NUM_POLLEES);
      g_assert (r == 0);

      diff = times[i][1] - times[i][0];
      if (times_min > diff)
        times_min = diff;
      if (times_max < diff)
        times_max = diff;
      times_avg += diff;
      bucketize (diff, buckets, bucket_limits, BUCKET_COUNT);
      activatable = (activatable + 1) % NUM_POLLEES;
    }

  times_avg /= NUM_POLLEES;
  g_print ("variable socket number + msg poll time: \n%4lldns - %4lldns, average %4lldns\n", times_min, times_max, times_avg);
  print_buckets (buckets, bucket_limits, BUCKET_COUNT);

  cleanup_sockets (sockets, opp_sockets, NUM_POLLEES);
}
Beispiel #13
0
static int32_t dt_camera_capture_job_run(dt_job_t *job)
{
  dt_camera_capture_t *params = dt_control_job_get_params(job);
  int total;
  char message[512]= {0};
  double fraction=0;

  total = params->total = params->brackets ? params->count * params->brackets : params->count;
  snprintf(message, sizeof(message), ngettext ("capturing %d image", "capturing %d images", total), total );

  pthread_mutex_init(&params->mutex, NULL);
  pthread_cond_init(&params->done, NULL);

  // register listener
  dt_camctl_listener_t *listener;
  listener = g_malloc0(sizeof(dt_camctl_listener_t));
  listener->data = params;
  listener->image_downloaded = _camera_capture_image_downloaded;
  listener->request_image_path = _camera_request_image_path;
  listener->request_image_filename = _camera_request_image_filename;
  dt_camctl_register_listener(darktable.camctl, listener);

  /* try to get exp program mode for nikon */
  char *expprogram = (char *)dt_camctl_camera_get_property(darktable.camctl, NULL, "expprogram");

  /* if fail, lets try fetching mode for cannon */
  if(!expprogram)
    expprogram = (char *)dt_camctl_camera_get_property(darktable.camctl, NULL, "autoexposuremode");

  /* Fetch all values for shutterspeed and initialize current value */
  GList *values=NULL;
  gconstpointer original_value=NULL;
  const char *cvalue = dt_camctl_camera_get_property(darktable.camctl, NULL, "shutterspeed");
  const char *value = dt_camctl_camera_property_get_first_choice(darktable.camctl, NULL, "shutterspeed");

  /* get values for bracketing */
  if (params->brackets && expprogram && expprogram[0]=='M' && value && cvalue)
  {
    do
    {
      // Add value to list
      values = g_list_append(values, g_strdup(value));
      // Check if current values is the same as original value, then lets store item ptr
      if (strcmp(value,cvalue) == 0)
        original_value = g_list_last(values)->data;
    }
    while ((value = dt_camctl_camera_property_get_next_choice(darktable.camctl, NULL, "shutterspeed")) != NULL);
  }
  else
  {
    /* if this was an intended bracket capture bail out */
    if(params->brackets)
    {
      dt_control_log(_("please set your camera to manual mode first!"));
      pthread_mutex_lock(&params->mutex);
      pthread_cond_wait(&params->done, &params->mutex);
      pthread_mutex_unlock(&params->mutex);
      pthread_mutex_destroy(&params->mutex);
      pthread_cond_destroy(&params->done);
      dt_import_session_destroy(params->shared.session);
      dt_camctl_unregister_listener(darktable.camctl, listener);
      g_free(listener);
      free(params);
      return 1;
    }
  }

  /* create the bgjob plate */
  const guint *jid  = dt_control_backgroundjobs_create(darktable.control, 0, message);

  GList *current_value = g_list_find(values,original_value);
  for(uint32_t i=0; i < params->count; i++)
  {
    // Delay if active
    if(params->delay)
      g_usleep(params->delay*G_USEC_PER_SEC);

    for(uint32_t b=0; b < (params->brackets*2)+1; b++)
    {
      // If bracket capture, lets set change shutterspeed
      if (params->brackets)
      {
        if (b == 0)
        {
          // First bracket, step down time with (steps*brackets), also check so we never set the longest shuttertime which would be bulb mode
          for(uint32_t s=0; s < (params->steps * params->brackets); s++)
            if (g_list_next(current_value) && g_list_next(g_list_next(current_value)))
              current_value = g_list_next(current_value);
        }
        else
        {
          // Step up with (steps)
          for(uint32_t s=0; s < params->steps; s++)
            if(g_list_previous(current_value))
              current_value = g_list_previous(current_value);
        }
      }

      // set the time property for bracket capture
      if (params->brackets && current_value)
        dt_camctl_camera_set_property_string(darktable.camctl, NULL, "shutterspeed", current_value->data);

      // Capture image
      dt_camctl_camera_capture(darktable.camctl,NULL);

      fraction += 1.0/total;
      dt_control_backgroundjobs_progress(darktable.control, jid, fraction);
    }

    // lets reset to original value before continue
    if (params->brackets)
    {
      current_value = g_list_find(values,original_value);
      dt_camctl_camera_set_property_string(darktable.camctl, NULL, "shutterspeed", current_value->data);
    }
  }

  /* wait for last image capture before exiting job */
  pthread_mutex_lock(&params->mutex);
  pthread_cond_wait(&params->done, &params->mutex);
  pthread_mutex_unlock(&params->mutex);
  pthread_mutex_destroy(&params->mutex);
  pthread_cond_destroy(&params->done);

  /* cleanup */
  dt_control_backgroundjobs_destroy(darktable.control, jid);
  dt_import_session_destroy(params->shared.session);
  dt_camctl_unregister_listener(darktable.camctl, listener);
  g_free(listener);

  // free values
  if(values)
  {
    g_list_free_full(values, g_free);
  }
  free(params);
  return 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;
}
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;
}
Beispiel #16
0
int
main()
{
  g_type_init();
  if (!g_thread_supported ()) g_thread_init (NULL);

  g_print("Testing skip lists");

  skip_list_t *list  = skip_list_new(8, 0.65);
  skip_list_t *list2 = skip_list_new(6, 0.3);

  /* for-each test */
  int i;
  for (i = 0; i < 50; ++i)
    {
      gint key = skip_list_insert_random(list);
      skip_list_insert(list2, key, GINT_TO_POINTER(key));
    }
  skip_list_foreach (list, (GFunc)assert_present, list2);
  g_print("...");

  for (i = 0; i < 50; ++i)
    {
      gint next = skip_list_insert_random(list);
      gint popped = skip_list_pop_first(list);
    }
  g_assert(skip_list_self_consistent(list));

  /* pop test */
  for (i = 0; i < 500; ++i)
    {
      gint next   = skip_list_insert_random(list);
      gint popped = GPOINTER_TO_INT(skip_list_pop(list, next));
      g_assert(popped == next);
    }
  g_assert(skip_list_self_consistent(list));
  g_print("...");

  /* lookup test */
  for (i = 0; i < 500; ++i)
    {
      gint next   = skip_list_insert_random(list);
      gint looked = GPOINTER_TO_INT(skip_list_lookup(list, next));
      g_assert(looked == next);
    }
  g_assert(skip_list_self_consistent(list));
  g_print("...");

  g_print("OK\n");

  g_print("Testing skiplist thread safety");

  GError *error = NULL;
  g_thread_create((GThreadFunc)skip_list_jitter, list, FALSE, &error);
  g_assert(error == NULL);

  static const int n_trial = 500;
  gint n_success = 0;

  for (i = 0; i < n_trial; ++i)
    {
      g_usleep(10000);
      g_assert(skip_list_length(list) < (jitter_length_min + 5));
      gint key = g_random_int_range(0, 100);
      gpointer retrieve = skip_list_lookup(list, key);
      g_assert((retrieve == NULL) || (GPOINTER_TO_INT(retrieve) == key));
      if (retrieve != NULL) ++n_success;
      if ((i % (n_trial / 20)) == 0) g_print(".");
    }

  /* chances of _no_ successes are vanishingly small */
  g_assert(n_success > 0);

  g_print("OK (%d / %d)\n", n_success, n_trial);

  return 0;
}
static gpointer
skype_command_client_thread(SkypeCommandClient *dcc) {
  struct sockaddr_un addr;
  socklen_t addr_len;
  int connection_attempts = 1;

  /* intialize address structure */
  addr.sun_family = AF_UNIX;
  g_snprintf(addr.sun_path,
	     sizeof(addr.sun_path),
	     "%s/.skype/command_socket",
	     g_get_home_dir());
  addr_len = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path);

  while (1) {
    GIOChannel *chan = NULL;
    GError *gerr = NULL;
    int sock;
    gboolean failflag = TRUE;

    do {
      int flags;

      if (0 > (sock = socket(PF_UNIX, SOCK_STREAM, 0))) {
	/* WTF */
	break;
      }

      /* set timeout on socket, to protect against
	 bad servers */
      {
	struct timeval tv = {3, 0};
	if (0 > setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
			   &tv, sizeof(struct timeval)) ||
	    0 > setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO,
			   &tv, sizeof(struct timeval))) {
	  /* debug("setsockopt failed"); */
	  break;
	}
      }

      /* set native non-blocking, for connect timeout */
      {
	if ((flags = fcntl(sock, F_GETFL, 0)) < 0 ||
	    fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) {
	  /* debug("fcntl failed"); */
	  break;
	}
      }

      /* if there was an error we have to try again later */
      if (connect(sock, (struct sockaddr *) &addr, addr_len) < 0) {
	if (errno == EINPROGRESS) {
	  fd_set writers;
	  struct timeval tv = {1, 0};

	  FD_ZERO(&writers);
	  FD_SET(sock, &writers);

	  /* if nothing was ready after 3 seconds, fail out homie */
	  if (select(sock+1, NULL, &writers, NULL, &tv) == 0) {
	    /* debug("connection timeout"); */
	    break;
	  }

	  if (connect(sock, (struct sockaddr *) &addr, addr_len) < 0) {
	    /*	    debug("couldn't connect to command server after 1 second"); */
	    break;
	  }
	}
	/* errno != EINPROGRESS */
	else {
	  /*	  debug("bad connection"); */
	  break;
	}
      }

      /* set back to blocking */
      if (fcntl(sock, F_SETFL, flags) < 0) {
	/* debug("fcntl2 failed"); */
	break;
      }

      failflag = FALSE;
    } while (0);

    if (failflag) {
      ConnectionAttempt *ca = g_new(ConnectionAttempt, 1);
      ca->dcc = dcc;
      ca->connect_attempt = connection_attempts;
      g_idle_add((GSourceFunc) on_connection_attempt, ca);
      if (sock >= 0) {
	close(sock);
      }
      g_usleep(G_USEC_PER_SEC);
      connection_attempts++;
      continue;
    }
    else {
      connection_attempts = 0;
    }

    /* connected */
    debug("command client connected");

    chan = g_io_channel_unix_new(sock);
    g_io_channel_set_close_on_unref(chan, TRUE);
    g_io_channel_set_line_term(chan, "\n", -1);

#define SET_CONNECTED_STATE(s)     {			\
      g_mutex_lock(dcc->command_connected_mutex);	\
      dcc->command_connected = s;			\
      g_mutex_unlock(dcc->command_connected_mutex);	\
    }

    SET_CONNECTED_STATE(TRUE);

    g_idle_add((GSourceFunc) on_connect, dcc);

    while (1) {
      SkypeCommand *dc;

      while (1) {
	GTimeVal gtv;

	g_get_current_time(&gtv);
	g_time_val_add(&gtv, G_USEC_PER_SEC / 10);
	/* get a request from nautilus */
	dc = g_async_queue_timed_pop(dcc->command_queue, &gtv);
	if (dc != NULL) {
	  break;
	}
	else {
	  if (check_connection(chan) == FALSE) {
	    goto BADCONNECTION;
	  }
	}
      }

      /* this pointer should be unique */
      if ((gpointer (*)(SkypeCommandClient *data)) dc == &skype_command_client_thread) {
	debug("got a reset request");
	goto BADCONNECTION;
      }

      switch (dc->request_type) {
      case GET_FILE_INFO: {
	debug("doing file info command");
	do_file_info_command(chan, (SkypeFileInfoCommand *) dc, &gerr);
      }
	break;
      case GENERAL_COMMAND: {
	debug("doing general command");
	do_general_command(chan, (SkypeGeneralCommand *) dc, &gerr);
      }
	break;
      default: 
	g_assert_not_reached();
	break;
      }
      
      debug("done.");

      if (gerr != NULL) {
	//	debug("COMMAND ERROR*****************************");
	/* mark this request as never to be completed */
	end_request(dc);

	debug("command error: %s", gerr->message);
	
	g_error_free(gerr);
      BADCONNECTION:
	/* grab all the rest of the data off the async queue and mark it
	   never to be completed, who knows how long we'll be disconnected */
	while ((dc = g_async_queue_try_pop(dcc->command_queue)) != NULL) {
	  end_request(dc);
	}

	g_io_channel_unref(chan);

	SET_CONNECTED_STATE(FALSE);

	/* call the disconnect handler */
	g_idle_add((GSourceFunc) on_disconnect, dcc);

	break;
      }
    }
    
#undef SET_CONNECTED_STATE
  }
  
  return NULL;
}
Beispiel #18
0
static GRealThreadPool*
g_thread_pool_wait_for_new_pool (void)
{
  GRealThreadPool *pool;
  gint local_wakeup_thread_serial;
  guint local_max_unused_threads;
  gint local_max_idle_time;
  gint last_wakeup_thread_serial;
  gboolean have_relayed_thread_marker = FALSE;

  local_max_unused_threads = g_atomic_int_get (&max_unused_threads);
  local_max_idle_time = g_atomic_int_get (&max_idle_time);
  last_wakeup_thread_serial = g_atomic_int_get (&wakeup_thread_serial);

  g_atomic_int_inc (&unused_threads);

  do
    {
      if (g_atomic_int_get (&unused_threads) >= local_max_unused_threads)
        {
          /* If this is a superfluous thread, stop it. */
          pool = NULL;
        }
      else if (local_max_idle_time > 0)
        {
          /* If a maximal idle time is given, wait for the given time. */
          DEBUG_MSG (("thread %p waiting in global pool for %f seconds.",
                      g_thread_self (), local_max_idle_time / 1000.0));

          pool = g_async_queue_timeout_pop (unused_thread_queue,
					    local_max_idle_time * 1000);
        }
      else
        {
          /* If no maximal idle time is given, wait indefinitely. */
          DEBUG_MSG (("thread %p waiting in global pool.", g_thread_self ()));
          pool = g_async_queue_pop (unused_thread_queue);
        }

      if (pool == wakeup_thread_marker)
        {
          local_wakeup_thread_serial = g_atomic_int_get (&wakeup_thread_serial);
          if (last_wakeup_thread_serial == local_wakeup_thread_serial)
            {
              if (!have_relayed_thread_marker)
              {
                /* If this wakeup marker has been received for
                 * the second time, relay it.
                 */
                DEBUG_MSG (("thread %p relaying wakeup message to "
                            "waiting thread with lower serial.",
                            g_thread_self ()));

                g_async_queue_push (unused_thread_queue, wakeup_thread_marker);
                have_relayed_thread_marker = TRUE;

                /* If a wakeup marker has been relayed, this thread
                 * will get out of the way for 100 microseconds to
                 * avoid receiving this marker again.
                 */
                g_usleep (100);
              }
            }
          else
            {
              if (g_atomic_int_add (&kill_unused_threads, -1) > 0)
                {
                  pool = NULL;
                  break;
                }

              DEBUG_MSG (("thread %p updating to new limits.",
                          g_thread_self ()));

              local_max_unused_threads = g_atomic_int_get (&max_unused_threads);
              local_max_idle_time = g_atomic_int_get (&max_idle_time);
              last_wakeup_thread_serial = local_wakeup_thread_serial;

              have_relayed_thread_marker = FALSE;
            }
        }
    }
  while (pool == wakeup_thread_marker);

  g_atomic_int_add (&unused_threads, -1);

  return pool;
}
Beispiel #19
0
static void *migration_thread(void *opaque)
{
    MigrationState *s = opaque;
    int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
    int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
    int64_t initial_bytes = 0;
    int64_t max_size = 0;
    int64_t start_time = initial_time;
    bool old_vm_running = false;

    DPRINTF("beginning savevm\n");
    qemu_savevm_state_begin(s->file, &s->params);

    s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
    migrate_set_state(s, MIG_STATE_SETUP, MIG_STATE_ACTIVE);

    DPRINTF("setup complete\n");

    while (s->state == MIG_STATE_ACTIVE) {
        int64_t current_time;
        uint64_t pending_size;

        if (!qemu_file_rate_limit(s->file)) {
            DPRINTF("iterate\n");
            pending_size = qemu_savevm_state_pending(s->file, max_size);
            DPRINTF("pending size %" PRIu64 " max %" PRIu64 "\n",
                    pending_size, max_size);
            if (pending_size && pending_size >= max_size) {
                qemu_savevm_state_iterate(s->file);
            } else {
                int ret;

                DPRINTF("done iterating\n");
                qemu_mutex_lock_iothread();
                start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
                qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
                old_vm_running = runstate_is_running();

                ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
                if (ret >= 0) {
                    qemu_file_set_rate_limit(s->file, INT64_MAX);
                    qemu_savevm_state_complete(s->file);
                }
                qemu_mutex_unlock_iothread();

                if (ret < 0) {
                    migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
                    break;
                }

                if (!qemu_file_get_error(s->file)) {
                    migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_COMPLETED);
                    break;
                }
            }
        }

        if (qemu_file_get_error(s->file)) {
            migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
            break;
        }
        current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
        if (current_time >= initial_time + BUFFER_DELAY) {
            uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
            uint64_t time_spent = current_time - initial_time;
            double bandwidth = transferred_bytes / time_spent;
            max_size = bandwidth * migrate_max_downtime() / 1000000;

            s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
                    ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;

            DPRINTF("transferred %" PRIu64 " time_spent %" PRIu64
                    " bandwidth %g max_size %" PRId64 "\n",
                    transferred_bytes, time_spent, bandwidth, max_size);
            /* if we haven't sent anything, we don't want to recalculate
               10000 is a small enough number for our purposes */
            if (s->dirty_bytes_rate && transferred_bytes > 10000) {
                s->expected_downtime = s->dirty_bytes_rate / bandwidth;
            }

            qemu_file_reset_rate_limit(s->file);
            initial_time = current_time;
            initial_bytes = qemu_ftell(s->file);
        }
        if (qemu_file_rate_limit(s->file)) {
            /* usleep expects microseconds */
            g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
        }
    }

    qemu_mutex_lock_iothread();
    if (s->state == MIG_STATE_COMPLETED) {
        int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
        s->total_time = end_time - s->total_time;
        s->downtime = end_time - start_time;
        runstate_set(RUN_STATE_POSTMIGRATE);
    } else {
        if (old_vm_running) {
            vm_start();
        }
    }
    qemu_bh_schedule(s->cleanup_bh);
    qemu_mutex_unlock_iothread();

    return NULL;
}
Beispiel #20
0
static gpointer      _gpsdClientRead(gpointer dummy)
// start gpsd client - loop forever
// return if _ais_list is NULL or 10 failed attempt to connect
{
    int nWait = 0;

    g_print("s52ais:_gpsdClientRead(): start looping ..\n");
    __builtin_bzero(&_gpsdata, sizeof(_gpsdata));

    //*
    while (0 != gps_open(GPSD_HOST, GPSD_PORT, &_gpsdata)) {   // android (gpsd 2.96)
        g_print("s52ais:_gpsdClientRead(): no gpsd running or network error, wait 1 sec: %d, %s\n", errno, gps_errstr(errno));

        // try to connect to GPSD server, bailout after 10 failed attempt
        g_static_mutex_lock(&_ais_list_mutex);
        if ((NULL==_ais_list) || (10 <= ++nWait)) {
            g_print("s52ais:_gpsdClientRead() no AIS list (main exited) or no GPSD server.. terminate _gpsClientRead thread\n");

            g_static_mutex_unlock(&_ais_list_mutex);

            return NULL;
        }
        g_static_mutex_unlock(&_ais_list_mutex);

        g_usleep(1000 * 1000); // 1.0 sec
    }

    if (-1 == gps_stream(&_gpsdata, WATCH_ENABLE|WATCH_NEWSTYLE, NULL)) {
        g_print("s52ais:_gpsdClientRead():gps_stream() failed .. exiting\n");
        return NULL;
    }
    //*/


    // debug
    //gps_enable_debug(3, stderr);
    //gps_enable_debug(8, stderr);

    // heart of the client
    for (;;) {
        g_static_mutex_lock(&_ais_list_mutex);
        if (NULL == _ais_list) {
            g_print("s52ais:_gpsdClientRead() no AIS list .. main exited .. terminate gpsRead thread\n");
            goto exit;
        }
        g_static_mutex_unlock(&_ais_list_mutex);

        if (FALSE == gps_waiting(&_gpsdata,  500*1000)) {    // wait 0.5 sec     (500*1000 uSec)
            //g_print("s52ais:_gpsdClientRead():gps_waiting() timed out\n");

            g_static_mutex_lock(&_ais_list_mutex);
            _updateTimeTag();
            g_static_mutex_unlock(&_ais_list_mutex);

        } else {
            errno = 0;

            int ret = gps_read(&_gpsdata);
            if (0 < ret) {
                // no error
                //g_print("s52ais:_gpsdClientRead():gps_read() ..\n");

                // handle AIS data
                g_static_mutex_lock(&_ais_list_mutex);
                _updateAISdata(&_gpsdata);
                g_static_mutex_unlock(&_ais_list_mutex);

                continue;
            }

            if (0 == ret) {
                g_print("s52ais:_gpsdClientRead():gps_read(): NO DATA .. [ret=0, errno=%i]\n", errno);
                continue;
            } else {
                g_print("s52ais:_gpsdClientRead():gps_read(): socket error 4 .. GPSD died [ret=%i, errno=%i]\n", ret, errno);

                goto exit;
            }
        }
    }

exit:
    // exit thread
    g_static_mutex_unlock(&_ais_list_mutex);

    gps_stream(&_gpsdata, WATCH_DISABLE, NULL);
    gps_close(&_gpsdata);

    return dummy;
}
Beispiel #21
0
EcuState detect_ecu(gint fd)
{
	gint res = 0;
	gint size = 1024;
	guchar buf[1024];
	guchar *ptr = buf;
	gint total_read = 0;
	gint total_wanted = 0;
	gint zerocount = 0;
	gchar  *message = NULL;

	/* Probe for response 
	 * First check for signature (running state)
	 * If that fails, see if we are in bootloader mode already
	 */

	res = write (fd,"S",1);
	flush_serial(fd,BOTH);
	if (res != 1)
		output("Failure sending signature request!\n",FALSE);
	g_usleep(300000); /* 300ms timeout */
	total_read = 0;
	total_wanted = size;
	zerocount = 0;
	while ((total_read < total_wanted ) && (total_wanted-total_read) > 0 )
	{
		total_read += res = read(fd,
				ptr+total_read,
				total_wanted-total_read);

		/* If we get nothing back (i.e. timeout, assume done)*/
		if (res <= 0)
			zerocount++;

		if (zerocount > 1)
			break;
	}
	if (total_read > 0)
	{
		message = g_strndup(((gchar *)buf),total_read);
		/* Check for "what" or "Boot" */
		if (g_strrstr_len(message,total_read, "what"))
		{
			g_free(message);
			return IN_BOOTLOADER;
		}
		else if (g_strrstr_len(message,total_read, "Boot"))
		{
			g_free(message);
			return IN_BOOTLOADER;
		}
		else	
		{
			output(g_strdup_printf("ECU signature: \"%s\"\n",message),TRUE);
			g_free(message);
			return  LIVE_MODE;
		}
	}

	return NOT_LISTENING;
}
Beispiel #22
0
/*!
  \brief write_data() physically sends the data to the ECU.
  \param message is the pointer to an Io_Message structure
  */
G_MODULE_EXPORT gboolean write_data(Io_Message *message)
{
	static GMutex *serio_mutex = NULL;
	static Serial_Params *serial_params = NULL;
	static Firmware_Details *firmware = NULL;
	static gfloat *factor = NULL;
	OutputData *output = (OutputData *)message->payload;
	gint res = 0;
	gchar * err_text = NULL;
	guint i = 0;
	gint j = 0;
	gint len = 0;
	guint8 * buffer = NULL;
	gint burst_len = 0;
	gboolean notifies = FALSE;
	gint notif_divisor = 32;
	WriteMode mode = MTX_CMD_WRITE;
	gboolean retval = TRUE;
	DBlock *block = NULL;
	static GMutex mutex;
	static void (*store_new_block)(gpointer) = NULL;
	static void (*set_ecu_data)(gpointer,gint *) = NULL;

	ENTER();

	if (!firmware)
		firmware = (Firmware_Details *)DATA_GET(global_data,"firmware");
	if (!serial_params)
		serial_params = (Serial_Params *)DATA_GET(global_data,"serial_params");
	if (!serio_mutex)
		serio_mutex = (GMutex *)DATA_GET(global_data,"serio_mutex");
	if (!factor)
		factor = (gfloat *)DATA_GET(global_data,"sleep_correction");
	if (!set_ecu_data)
		get_symbol("set_ecu_data",(void **)&set_ecu_data);
	if (!store_new_block)
		get_symbol("store_new_block",(void **)&store_new_block);

	g_return_val_if_fail(firmware,FALSE);
	g_return_val_if_fail(serial_params,FALSE);
	g_return_val_if_fail(serio_mutex,FALSE);
	g_return_val_if_fail(factor,FALSE);
	g_return_val_if_fail(set_ecu_data,FALSE);
	g_return_val_if_fail(store_new_block,FALSE);

	g_mutex_lock(&mutex);
	g_mutex_lock(serio_mutex);

	if (output)
		mode = (WriteMode)(GINT)DATA_GET(output->data,"mode");

	if (DATA_GET(global_data,"offline"))
	{
		switch (mode)
		{
			case MTX_SIMPLE_WRITE:
				set_ecu_data(output->data,NULL);
				break;
			case MTX_CHUNK_WRITE:
				store_new_block(output->data);
				break;
			case MTX_CMD_WRITE:
				break;
		}
		g_mutex_unlock(serio_mutex);
		g_mutex_unlock(&mutex);
		EXIT();
		return TRUE;		/* can't write anything if offline */
	}
	if (!DATA_GET(global_data,"connected"))
	{
		g_mutex_unlock(serio_mutex);
		g_mutex_unlock(&mutex);
		EXIT();
		return FALSE;		/* can't write anything if disconnected */
	}

	/* For MS3 1.1 which uses a CRC32 wrapped serial stream, we can't easily
	 * do the old way as it had a bunch of fugly worarounds for ECU editions 
	 * that couldn't handle bursts and needed to be artificially throttled.
	 */
	if(DATA_GET(message->data,"burst_write"))
	{
		buffer = (guint8 *)DATA_GET(message->data,"burst_buffer");
		if (!buffer)
		{
			MTXDBG(CRITICAL|SERIAL_WR,_("MS3 CRC32 burst blob is not stored in the OutputData->data structure, ABORTING\n"));
			EXIT();
			return FALSE;
		}
		burst_len = (GINT)DATA_GET(message->data,"burst_len");
		QUIET_MTXDBG(SERIAL_WR,_("Writing MS3 burst write %i bytes\n"),burst_len);
		res = write_wrapper(serial_params->fd,buffer,burst_len, &len);
		/* Send write command */
		if (!res)
		{
			MTXDBG((Dbg_Class)(SERIAL_WR|CRITICAL),_("Error writing MS3 burst block ERROR \"%s\"!!!\n"),err_text);
			retval = FALSE;
		}
	}

	else
	{
		g_return_val_if_fail(message,FALSE);
		g_return_val_if_fail(message->sequence,FALSE);
		g_return_val_if_fail(message->sequence->len > 0,FALSE);
		
		for (i=0;i<message->sequence->len;i++)
		{
			block = g_array_index(message->sequence,DBlock *,i);
			/*	printf("Block pulled\n");*/
			if (block->type == ACTION)
			{
				/*		printf("Block type of ACTION!\n");*/
				if (block->action == SLEEP)
				{
					/*			printf("Sleeping for %i usec\n", block->arg);*/
					MTXDBG(SERIAL_WR,_("Sleeping for %i microseconds \n"),block->arg);
					g_usleep((*factor)*block->arg);
				}
			}
			else if (block->type == DATA)
			{
				/*		printf("Block type of DATA!\n");*/
				if (block->len > 100)
					notifies = TRUE;
				/* ICK bad form man, writing one byte at a time,  due to ECU's that can't take full wire speed without
				   dropping chars due to uber tiny buffers */
				for (j=0;j<block->len;j++)
				{
					/*printf("comms.c data[%i] is %i, block len is %i\n",j,block->data[j],block->len);*/
					if ((notifies) && ((j % notif_divisor) == 0))
						thread_update_widget("info_label",MTX_LABEL,g_strdup_printf(_("<b>Sending %i of %i bytes</b>"),j,block->len));
					QUIET_MTXDBG(SERIAL_WR,_("Writing argument %i byte %i of %i, \"%.2X\"\n"),i,j+1,block->len,block->data[j]);
					res = write_wrapper(serial_params->fd,&(block->data[j]),1, &len);
					/* Send write command */
					if (!res)
					{
						MTXDBG((Dbg_Class)(SERIAL_WR|CRITICAL),_("Error writing block offset %i, value \"%.2X\" ERROR \"%s\"!!!\n"),j,block->data[j],err_text);
						retval = FALSE;
					}
					if (firmware->capabilities & MS2)
						g_usleep((*factor)*firmware->interchardelay*1000);
				}
			}
		}
	}
	if (notifies)
	{
		thread_update_widget("info_label",MTX_LABEL,g_strdup("<b>Transfer Completed</b>"));
		g_timeout_add(2000,(GSourceFunc)reset_infolabel_wrapper,NULL);
	}
	/* If sucessfull update ecu_data as well, this way, current 
	 * and pending match, in the case of a failed write, the 
	 * update_write_status() function will catch it and rollback as needed
	 */
	if ((output) && (retval))
	{
		if (mode == MTX_SIMPLE_WRITE)
			set_ecu_data(output->data,NULL);
		else if (mode == MTX_CHUNK_WRITE)
			store_new_block(output->data);
	}

	g_mutex_unlock(serio_mutex);
	g_mutex_unlock(&mutex);
	EXIT();
	return retval;
}
Beispiel #23
0
/* -------------------------------------------------------------------------- */
void *mpd_run(void *cookie)
{
    time_t next_update, current;
    gboolean result;
    int retry_count = RETRY_INTERVAL;
    struct lcd_stuff_mpd mpd;

    /* default values */
    mpd.lcd = (struct lcd_stuff *)cookie;
    mpd.mpd = NULL;
    mpd.error = 0;
    mpd.current_state = 0;
    mpd.song_displayed = false;
    mpd.current_song = NULL;
    mpd.stop_time = UINT_MAX;
    mpd.current_list = NULL;
    mpd.connection = NULL;
    mpd.timeout = 0;

    result = key_file_has_group(MODULE_NAME);
    if (!result) {
        report(RPT_INFO, "mpd disabled");
        conf_dec_count();
        return NULL;
    }

    if (!mpd_init(&mpd))
        goto out;

    if (!mpd_init_connection(&mpd))
        goto out_screen;
    if (!mpd_start_connection(&mpd))
        goto out_screen;

    /* do first update instantly */
    next_update = time(NULL);

    conf_dec_count();

    /* dispatcher */
    while (!g_exit) {

        /* if we are in error state, try to retrieve a connection first */
        if (mpd.error) {
            if (retry_count-- <= 0) { /* each minute */
                if (mpd_start_connection(&mpd)) {
                    mpd.error = false;
                } else {
                    retry_count = RETRY_INTERVAL;
                }
            }

            if (mpd.error) {
                g_usleep(1000000);
                continue;
            }
        }

        current = time(NULL);

        g_usleep(1000000);
        mpd_status_queue_update(mpd.mpd);
        mpd_status_check(mpd.mpd);
        mpd_update_status_time(&mpd);

        /* check playlists ? */
        if (current > next_update) {
            mpd_update_playlist_menu(&mpd);
            next_update = time(NULL) + 60;
        } if (current > mpd.stop_time) {
            mpd_player_stop(mpd.mpd);
            mpd.stop_time = UINT_MAX;
            service_thread_command(mpd.lcd->service_thread,
                                   "menu_set_item \"\" mpd_standby -value 0\n");
        }
    }

out_screen:
    mpd_deinit(&mpd);

out:
    if (mpd.mpd)
        mpd_free(mpd.mpd);
    if (mpd.current_list)
        mpd_free_playlist(mpd.current_list);
    service_thread_unregister_client(mpd.lcd->service_thread, MODULE_NAME);
    mpd_song_delete(mpd.current_song);
    connection_delete(mpd.connection);

    return NULL;
}
Beispiel #24
0
G_MODULE_EXPORT void *serial_repair_thread(gpointer data)
{
	/* We got sent here because of one of the following occurred:
	 * Serial port isn't opened yet (app just fired up)
	 * Serial I/O errors (missing data, or failures reading/writing)
	 *  - This includes things like pulling the RS232 cable out of the ECU
	 * Serial port disappeared (i.e. device hot unplugged)
	 *  - This includes unplugging the USB side of a USB->Serial adapter
	 *    or going out of bluetooth range, for a BT serial device
	 *
	 * Thus we need to handle all possible conditions if possible
	 */
	static gboolean serial_is_open = FALSE; /* Assume never opened */
	static GAsyncQueue *io_repair_queue = NULL;
	gchar * potential_ports;
	gint len = 0;
	gboolean autodetect = FALSE;
	guchar buf [1024];
	gchar ** vector = NULL;
	guint i = 0;
	Serial_Params *serial_params = NULL;
	void (*unlock_serial_f)(void) = NULL;
	void (*close_serial_f)(void) = NULL;
	gboolean (*open_serial_f)(const gchar *,gboolean) = NULL;
	gboolean (*lock_serial_f)(const gchar *) = NULL;
	void (*setup_serial_params_f)(void) = NULL;

	ENTER();
	serial_params = (Serial_Params *)DATA_GET(global_data,"serial_params");

	get_symbol_f("setup_serial_params",(void **)&setup_serial_params_f);
	get_symbol_f("open_serial",(void **)&open_serial_f);
	get_symbol_f("close_serial",(void **)&close_serial_f);
	get_symbol_f("lock_serial",(void **)&lock_serial_f);
	get_symbol_f("unlock_serial",(void **)&unlock_serial_f);
	MTXDBG(THREADS|CRITICAL,_("LibreEMS serial_repair_thread() created!\n"));

	if (DATA_GET(global_data,"offline"))
	{
		g_timeout_add(100,(GSourceFunc)queue_function_f,(gpointer)"kill_conn_warning");
		MTXDBG(THREADS|CRITICAL,_("LibreEMS serial_repair_thread() exiting, offline mode!\n"));
		g_thread_exit(0);
	}
	if (!io_repair_queue)
		io_repair_queue = (GAsyncQueue *)DATA_GET(global_data,"io_repair_queue");
	/* IF serial_is_open is true, then the port was ALREADY opened 
	 * previously but some error occurred that sent us down here. Thus
	 * first do a simple comms test, if that succeeds, then just cleanup 
	 * and return,  if not, close the port and essentially start over.
	 */
	if (serial_is_open == TRUE)
	{
		MTXDBG(SERIAL_RD|SERIAL_WR,_("Port considered open, but throwing errors\n"));
		libreems_serial_disable();
		close_serial_f();
		unlock_serial_f();
		serial_is_open = FALSE;
		/* Fall through */
	}
	while (!serial_is_open)
	{
		/* If "leaving" flag set, EXIT now */
		if (DATA_GET(global_data,"leaving"))
			g_thread_exit(0);
		MTXDBG(SERIAL_RD|SERIAL_WR,_("Port NOT considered open yet.\n"));
		autodetect = (GBOOLEAN) DATA_GET(global_data,"autodetect_port");
		if (!autodetect) /* User thinks he/she is S M A R T */
		{
			potential_ports = (gchar *)DATA_GET(global_data, "override_port");
			if (potential_ports == NULL)
				potential_ports = (gchar *)DATA_GET(global_data,"potential_ports");
		}
		else    /* Auto mode */
			potential_ports = (gchar *)DATA_GET(global_data,"potential_ports");
		vector = g_strsplit(potential_ports,",",-1);
		for (guint i=0;i<g_strv_length(vector);i++)
		{
			if (DATA_GET(global_data,"leaving"))
			{
				g_strfreev(vector);
				g_thread_exit(0);
			}
			/* Message queue used to exit immediately */
			if (g_async_queue_try_pop(io_repair_queue))
			{
				g_timeout_add(300,(GSourceFunc)queue_function_f,(gpointer)"kill_conn_warning");
				MTXDBG(THREADS|CRITICAL,_("LibreEMS serial_repair_thread() exiting, told to!\n"));
				g_thread_exit(0);
			}
			if (!g_file_test(vector[i],G_FILE_TEST_EXISTS))
			{
				MTXDBG(SERIAL_RD|SERIAL_WR,_("Port %s does NOT exist\n"),vector[i]);

				/* Wait 100 ms to avoid deadlocking */
				g_usleep(100000);
				continue;
			}
			g_usleep(100000);
			MTXDBG(SERIAL_RD|SERIAL_WR,_("Attempting to open port %s\n"),vector[i]);
			thread_update_logbar_f("comms_view",NULL,g_strdup_printf(_("Attempting to open port %s\n"),vector[i]),FALSE,FALSE);
			if (lock_serial_f(vector[i]))
			{
				if (open_serial_f(vector[i],TRUE))
				{
					if (autodetect)
						thread_update_widget_f("active_port_entry",MTX_ENTRY,g_strdup(vector[i]));
					MTXDBG(SERIAL_RD|SERIAL_WR,_("Port %s opened\n"),vector[i]);
					setup_serial_params_f();
					libreems_serial_enable();

					thread_update_logbar_f("comms_view",NULL,g_strdup_printf(_("Searching for ECU\n")),FALSE,FALSE);
					MTXDBG(SERIAL_RD|SERIAL_WR,_("Performing ECU comms test via port %s.\n"),vector[i]);
					if (comms_test())
					{       /* We have a winner !!  Abort loop */
						thread_update_logbar_f("comms_view",NULL,g_strdup_printf(_("Search successfull\n")),FALSE,FALSE);
						serial_is_open = TRUE;
						break;
					}
					else
					{
						MTXDBG(SERIAL_RD|SERIAL_WR,_("COMMS test failed, no ECU found, closing port %s.\n"),vector[i]);
						thread_update_logbar_f("comms_view",NULL,g_strdup_printf(_("No ECU found...\n")),FALSE,FALSE);
						libreems_serial_disable();
						close_serial_f();
						unlock_serial_f();
						/*g_usleep(100000);*/
					}
				}
				g_usleep(100000);
			}
			else
			{
				MTXDBG(SERIAL_RD|SERIAL_WR,_("Port %s is open by another application\n"),vector[i]);
				thread_update_logbar_f("comms_view","warning",g_strdup_printf(_("Port %s is open by another application\n"),vector[i]),FALSE,FALSE);
			}
		}
		queue_function_f("conn_warning");
	}

	if (serial_is_open)
	{
		queue_function_f("kill_conn_warning");
		thread_update_widget_f("active_port_entry",MTX_ENTRY,g_strdup(vector[i]));
	}
	if (vector)
		g_strfreev(vector);
	MTXDBG(THREADS|CRITICAL,_("LibreEMS serial_repair_thread()  exiting, device found!\n"));
	g_thread_exit(0);
	EXIT();
	return NULL;
}
Beispiel #25
0
//_________________________________________________________________________
void    DelayNMs (long ms)
{
    g_usleep(ms*1000);
}
Beispiel #26
0
/**
 * Try to find a valid packet in a serial data stream.
 *
 * @param serial Previously initialized serial port structure.
 * @param buf Buffer containing the bytes to write.
 * @param count Size of the buffer.
 * @param packet_size Size, in bytes, of a valid packet.
 * @param is_valid Callback that assesses whether the packet is valid or not.
 * @param timeout_ms The timeout after which, if no packet is detected, to
 *                   abort scanning.
 * @param baudrate The baudrate of the serial port. This parameter is not
 *                 critical, but it helps fine tune the serial port polling
 *                 delay.
 *
 * @return SR_OK if a valid packet is found within the given timeout,
 *         SR_ERR upon failure.
 */
SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
				 uint8_t *buf, size_t *buflen,
				 size_t packet_size, packet_valid_t is_valid,
				 uint64_t timeout_ms, int baudrate)
{
	uint64_t start, time, byte_delay_us;
	size_t ibuf, i, maxlen;
	int len;

	maxlen = *buflen;

	sr_dbg("Detecting packets on FD %d (timeout = %" PRIu64
	       "ms, baudrate = %d).", serial->fd, timeout_ms, baudrate);

	if (maxlen < (packet_size / 2) ) {
		sr_err("Buffer size must be at least twice the packet size.");
		return SR_ERR;
	}

	/* Assume 8n1 transmission. That is 10 bits for every byte. */
	byte_delay_us = 10 * (1000000 / baudrate);
	start = g_get_monotonic_time();

	i = ibuf = len = 0;
	while (ibuf < maxlen) {
		len = serial_read(serial, &buf[ibuf], 1);
		if (len > 0) {
			ibuf += len;
		} else if (len == 0) {
			/* No logging, already done in serial_read(). */
		} else {
			/* Error reading byte, but continuing anyway. */
		}

		time = g_get_monotonic_time() - start;
		time /= 1000;

		if ((ibuf - i) >= packet_size) {
			/* We have at least a packet's worth of data. */
			if (is_valid(&buf[i])) {
				sr_spew("Found valid %d-byte packet after "
					"%" PRIu64 "ms.", (ibuf - i), time);
				*buflen = ibuf;
				return SR_OK;
			} else {
				sr_spew("Got %d bytes, but not a valid "
					"packet.", (ibuf - i));
			}
			/* Not a valid packet. Continue searching. */
			i++;
		}
		if (time >= timeout_ms) {
			/* Timeout */
			sr_dbg("Detection timed out after %dms.", time);
			break;
		}
		if (len < 1)
			g_usleep(byte_delay_us);
	}

	*buflen = ibuf;

	sr_err("Didn't find a valid packet (read %d bytes).", *buflen);

	return SR_ERR;
}
Beispiel #27
0
void *
arv_fake_gv_camera_thread (void *user_data)
{
	ArvFakeGvCamera *gv_camera = user_data;
	ArvBuffer *image_buffer = NULL;
	GError *error = NULL;
	GSocketAddress *stream_address = NULL;
	void *packet_buffer;
	size_t packet_size;
	size_t payload = 0;
	guint16 block_id;
	ptrdiff_t offset;
	guint32 gv_packet_size;

	packet_buffer = g_malloc (ARV_FAKE_GV_CAMERA_BUFFER_SIZE);

	do {
		if (arv_fake_camera_get_control_channel_privilege (gv_camera->camera) == 0 ||
		    arv_fake_camera_get_acquisition_status (gv_camera->camera) == 0) {
			if (stream_address != NULL) {
				g_object_unref (stream_address);
				stream_address = NULL;
				g_object_unref (image_buffer);
				image_buffer = NULL;
				arv_debug_stream_thread ("[FakeGvCamera::stream_thread] Stop stream");
			}
			g_usleep (100000);
		} else {
			if (stream_address == NULL) {
				GInetAddress *inet_address;
				char *inet_address_string;

				stream_address = arv_fake_camera_get_stream_address (gv_camera->camera);
				inet_address = g_inet_socket_address_get_address
					(G_INET_SOCKET_ADDRESS (stream_address));
				inet_address_string = g_inet_address_to_string (inet_address);
				arv_debug_stream_thread ("[FakeGvCamera::stream_thread] Start stream to %s (%d)",
							 inet_address_string,
							 g_inet_socket_address_get_port
							 (G_INET_SOCKET_ADDRESS (stream_address)));
				g_free (inet_address_string);

				payload = arv_fake_camera_get_payload (gv_camera->camera);
				image_buffer = arv_buffer_new (payload, NULL);
			}

			arv_fake_camera_wait_for_next_frame (gv_camera->camera);
			arv_fake_camera_fill_buffer (gv_camera->camera, image_buffer, &gv_packet_size);

			block_id = 0;

			packet_size = ARV_FAKE_GV_CAMERA_BUFFER_SIZE;
			arv_gvsp_packet_new_data_leader (image_buffer->frame_id,
							 block_id,
							 image_buffer->timestamp_ns,
							 image_buffer->pixel_format,
							 image_buffer->width, image_buffer->height,
							 image_buffer->x_offset, image_buffer->y_offset,
							 packet_buffer, &packet_size);

			g_socket_send_to (gv_camera->gvsp_socket, stream_address,
					  packet_buffer, packet_size, NULL, &error);
			if (error != NULL) {
				arv_warning_stream_thread ("[ArvFakeGvCamera::stream_thread] Socket send error [%s]",
							   error->message);
				g_error_free (error);
				error = NULL;
			}

			block_id++;

			offset = 0;
			while (offset < payload) {
				size_t data_size;

				data_size = MIN (gv_packet_size - ARV_GVSP_PACKET_PROTOCOL_OVERHEAD,
						 payload - offset);

				packet_size = ARV_FAKE_GV_CAMERA_BUFFER_SIZE;
				arv_gvsp_packet_new_data_block (image_buffer->frame_id, block_id,
								data_size, ((char *) image_buffer->data) + offset,
								packet_buffer, &packet_size);

				g_socket_send_to (gv_camera->gvsp_socket, stream_address,
						  packet_buffer, packet_size, NULL, NULL);

				offset += data_size;
				block_id++;
			}

			packet_size = ARV_FAKE_GV_CAMERA_BUFFER_SIZE;
			arv_gvsp_packet_new_data_trailer (image_buffer->frame_id, block_id,
							  packet_buffer, &packet_size);

			g_socket_send_to (gv_camera->gvsp_socket, stream_address,
					  packet_buffer, packet_size, NULL, NULL);
		}
	} while (!cancel);

	if (stream_address != NULL)
		g_object_unref (stream_address);
	if (image_buffer != NULL)
		g_object_unref (image_buffer);

	g_free (packet_buffer);

	return NULL;
}
Beispiel #28
0
static CURLState *curl_init_state(BDRVCURLState *s)
{
    CURLState *state = NULL;
    int i, j;

    do {
        for (i=0; i<CURL_NUM_STATES; i++) {
            for (j=0; j<CURL_NUM_ACB; j++)
                if (s->states[i].acb[j])
                    continue;
            if (s->states[i].in_use)
                continue;

            state = &s->states[i];
            state->in_use = 1;
            break;
        }
        if (!state) {
            g_usleep(100);
            curl_multi_do(s);
        }
    } while(!state);

    if (state->curl)
        goto has_curl;

    state->curl = curl_easy_init();
    if (!state->curl)
        return NULL;
    curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
    curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, 5);
    curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION, (void *)curl_read_cb);
    curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
    curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
    curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
    curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
    curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);

    /* Restrict supported protocols to avoid security issues in the more
     * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see
     * CVE-2013-0249.
     *
     * Restricting protocols is only supported from 7.19.4 upwards.
     */
#if LIBCURL_VERSION_NUM >= 0x071304
    curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
    curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
#endif

#ifdef DEBUG_VERBOSE
    curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
#endif

has_curl:

    state->s = s;

    return state;
}
Beispiel #29
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;
}
Beispiel #30
0
static gboolean vorbis_play (InputPlayback * playback, const gchar * filename,
 VFSFile * file, gint start_time, gint stop_time, gboolean pause)
{
    if (file == NULL)
        return FALSE;

    vorbis_info *vi;
    OggVorbis_File vf;
    gint last_section = -1;
    ReplayGainInfo rg_info;
    gfloat pcmout[PCM_BUFSIZE*sizeof(float)], **pcm;
    gint bytes, channels, samplerate, br;
    gchar * title = NULL;

    seek_value = (start_time > 0) ? start_time : -1;
    stop_flag = FALSE;

    memset(&vf, 0, sizeof(vf));

    gboolean error = FALSE;

    if (ov_open_callbacks (file, & vf, NULL, 0, vfs_is_streaming (file) ?
     vorbis_callbacks_stream : vorbis_callbacks) < 0)
    {
        error = TRUE;
        goto play_cleanup;
    }

    vi = ov_info(&vf, -1);

    if (vi->channels > 2)
        goto play_cleanup;

    br = vi->bitrate_nominal;
    channels = vi->channels;
    samplerate = vi->rate;

    playback->set_params (playback, br, samplerate, channels);

    if (!playback->output->open_audio(FMT_FLOAT, samplerate, channels)) {
        error = TRUE;
        goto play_cleanup;
    }

    if (pause)
        playback->output->pause (TRUE);

    vorbis_update_replaygain(&vf, &rg_info);
    playback->output->set_replaygain_info (& rg_info);

    playback->set_pb_ready(playback);

    /*
     * Note that chaining changes things here; A vorbis file may
     * be a mix of different channels, bitrates and sample rates.
     * You can fetch the information for any section of the file
     * using the ov_ interface.
     */

    while (1)
    {
        if (stop_time >= 0 && playback->output->written_time () >= stop_time)
            goto DRAIN;

        g_mutex_lock (seek_mutex);

        if (stop_flag)
        {
            g_mutex_unlock (seek_mutex);
            break;
        }

        if (seek_value >= 0)
        {
            ov_time_seek (& vf, (double) seek_value / 1000);
            playback->output->flush (seek_value);
            seek_value = -1;
            g_cond_signal (seek_cond);
        }

        g_mutex_unlock (seek_mutex);

        gint current_section = last_section;
        bytes = ov_read_float(&vf, &pcm, PCM_FRAMES, &current_section);
        if (bytes == OV_HOLE)
            continue;

        if (bytes <= 0)
        {
DRAIN:
            while (playback->output->buffer_playing ())
                g_usleep (10000);

            break;
        }

        bytes = vorbis_interleave_buffer (pcm, bytes, channels, pcmout);

        { /* try to detect when metadata has changed */
            vorbis_comment * comment = ov_comment (& vf, -1);
            const gchar * new_title = (comment == NULL) ? NULL :
             vorbis_comment_query (comment, "title", 0);

            if (new_title != NULL && (title == NULL || strcmp (title, new_title)))
            {
                g_free (title);
                title = g_strdup (new_title);

                playback->set_tuple (playback, get_tuple_for_vorbisfile (& vf,
                 filename));
            }
        }

        if (current_section <= last_section) {
            /*
             * The info struct is different in each section.  vf
             * holds them all for the given bitstream.  This
             * requests the current one
             */
            vi = ov_info(&vf, -1);

            if (vi->channels > 2)
                goto stop_processing;

            if (vi->rate != samplerate || vi->channels != channels) {
                samplerate = vi->rate;
                channels = vi->channels;
                while (playback->output->buffer_playing())
                    g_usleep(1000);

                playback->output->close_audio();

                if (!playback->output->open_audio(FMT_FLOAT, vi->rate, vi->channels)) {
                    error = TRUE;
                    goto stop_processing;
                }

                playback->output->flush(ov_time_tell(&vf) * 1000);
                vorbis_update_replaygain(&vf, &rg_info);
                playback->output->set_replaygain_info (& rg_info); /* audio reopened */
            }
        }

        playback->output->write_audio (pcmout, bytes);

stop_processing:

        if (current_section <= last_section)
        {
            playback->set_params (playback, br, samplerate, channels);
            last_section = current_section;
        }
    } /* main loop */

    g_mutex_lock (seek_mutex);
    stop_flag = TRUE;
    g_cond_signal (seek_cond); /* wake up any waiting request */
    g_mutex_unlock (seek_mutex);

    playback->output->close_audio ();

play_cleanup:

    ov_clear(&vf);
    g_free (title);
    return ! error;
}