コード例 #1
0
ファイル: main.c プロジェクト: slyon/debian-fso-gsmd
gint _vala_main (gchar** args, int args_length1) {
	gint result = 0;
	gboolean _tmp12_;
	gchar* _tmp16_ = NULL;
	gchar* bin;
	GBusType _tmp17_ = 0;
	gboolean _tmp18_;
	GBusType _tmp19_;
	GBusType bus_type;
	GBusType _tmp20_;
	FsoFrameworkDBusSubsystem* _tmp21_;
	FsoFrameworkSubsystem* _tmp22_;
	FsoFrameworkSubsystem* _tmp23_;
	guint _tmp24_ = 0U;
	guint count;
	FsoFrameworkLogger* _tmp25_;
	guint _tmp26_;
	gchar* _tmp27_ = NULL;
	gchar* _tmp28_;
	guint _tmp29_;
	FsoFrameworkLogger* _tmp40_;
	const gchar* _tmp41_;
	gchar* _tmp42_ = NULL;
	gchar* _tmp43_;
	GError * _inner_error_ = NULL;
	{
		GOptionContext* _tmp0_;
		GOptionContext* opt_context;
		GOptionContext* _tmp1_;
		GOptionContext* _tmp2_;
		GOptionContext* _tmp3_;
		GOptionContext* _tmp4_;
		GOptionContext* _tmp5_;
		_tmp0_ = g_option_context_new ("");
		opt_context = _tmp0_;
		_tmp1_ = opt_context;
		g_option_context_set_summary (_tmp1_, "FreeSmartphone.org GSM daemon");
		_tmp2_ = opt_context;
		g_option_context_set_description (_tmp2_, "This daemon implements the freesmartphone.org GSM API");
		_tmp3_ = opt_context;
		g_option_context_set_help_enabled (_tmp3_, TRUE);
		_tmp4_ = opt_context;
		g_option_context_add_main_entries (_tmp4_, options, NULL);
		_tmp5_ = opt_context;
		g_option_context_parse (_tmp5_, &args_length1, &args, &_inner_error_);
		if (_inner_error_ != NULL) {
			_g_option_context_free0 (opt_context);
			if (_inner_error_->domain == G_OPTION_ERROR) {
				goto __catch0_g_option_error;
			}
			_g_option_context_free0 (opt_context);
			g_critical ("file %s: line %d: unexpected error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
			g_clear_error (&_inner_error_);
			return 0;
		}
		_g_option_context_free0 (opt_context);
	}
	goto __finally0;
	__catch0_g_option_error:
	{
		GError* e = NULL;
		FILE* _tmp6_;
		GError* _tmp7_;
		const gchar* _tmp8_;
		FILE* _tmp9_;
		gchar** _tmp10_;
		gint _tmp10__length1;
		const gchar* _tmp11_;
		e = _inner_error_;
		_inner_error_ = NULL;
		_tmp6_ = stdout;
		_tmp7_ = e;
		_tmp8_ = _tmp7_->message;
		fprintf (_tmp6_, "%s\n", _tmp8_);
		_tmp9_ = stdout;
		_tmp10_ = args;
		_tmp10__length1 = args_length1;
		_tmp11_ = _tmp10_[0];
		fprintf (_tmp9_, "Run '%s --help' to see a full list of available command line options.\n", _tmp11_);
		result = 1;
		_g_error_free0 (e);
		return result;
	}
	__finally0:
	if (_inner_error_ != NULL) {
		g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
		g_clear_error (&_inner_error_);
		return 0;
	}
	_tmp12_ = show_version;
	if (_tmp12_) {
		FILE* _tmp13_;
		gchar* _tmp14_ = NULL;
		gchar* _tmp15_;
		_tmp13_ = stdout;
		_tmp14_ = g_strdup_printf ("fsogsmd %s\n", PACKAGE_VERSION);
		_tmp15_ = _tmp14_;
		fprintf (_tmp13_, "%s", _tmp15_);
		_g_free0 (_tmp15_);
		result = 1;
		return result;
	}
	_tmp16_ = fso_framework_utility_programName ();
	bin = _tmp16_;
	_tmp18_ = use_session_bus;
	if (_tmp18_) {
		_tmp17_ = G_BUS_TYPE_SESSION;
	} else {
		_tmp17_ = G_BUS_TYPE_SYSTEM;
	}
	_tmp19_ = _tmp17_;
	bus_type = _tmp19_;
	_tmp20_ = bus_type;
	_tmp21_ = fso_framework_dbus_subsystem_new ("fsogsm", _tmp20_);
	_g_object_unref0 (subsystem);
	subsystem = (FsoFrameworkSubsystem*) _tmp21_;
	_tmp22_ = subsystem;
	fso_framework_subsystem_registerPlugins (_tmp22_);
	_tmp23_ = subsystem;
	_tmp24_ = fso_framework_subsystem_loadPlugins (_tmp23_);
	count = _tmp24_;
	_tmp25_ = fso_framework_theLogger;
	_tmp26_ = count;
	_tmp27_ = g_strdup_printf ("loaded %u plugins", _tmp26_);
	_tmp28_ = _tmp27_;
	fso_framework_logger_info (_tmp25_, _tmp28_);
	_g_free0 (_tmp28_);
	_tmp29_ = count;
	if (_tmp29_ > ((guint) 0)) {
		GMainLoop* _tmp30_;
		FsoFrameworkLogger* _tmp31_;
		const gchar* _tmp32_;
		gchar* _tmp33_ = NULL;
		gchar* _tmp34_;
		GMainLoop* _tmp35_;
		FsoFrameworkLogger* _tmp36_;
		const gchar* _tmp37_;
		gchar* _tmp38_ = NULL;
		gchar* _tmp39_;
		_tmp30_ = g_main_loop_new (NULL, FALSE);
		_g_main_loop_unref0 (mainloop);
		mainloop = _tmp30_;
		_tmp31_ = fso_framework_theLogger;
		_tmp32_ = bin;
		_tmp33_ = g_strdup_printf ("%s => mainloop", _tmp32_);
		_tmp34_ = _tmp33_;
		fso_framework_logger_info (_tmp31_, _tmp34_);
		_g_free0 (_tmp34_);
		signal (SIGINT, _sighandler_sighandler_t);
		signal (SIGTERM, _sighandler_sighandler_t);
		signal (SIGBUS, _sighandler_sighandler_t);
		signal (SIGSEGV, _sighandler_sighandler_t);
		_tmp35_ = mainloop;
		g_main_loop_run (_tmp35_);
		_tmp36_ = fso_framework_theLogger;
		_tmp37_ = bin;
		_tmp38_ = g_strdup_printf ("mainloop => %s", _tmp37_);
		_tmp39_ = _tmp38_;
		fso_framework_logger_info (_tmp36_, _tmp39_);
		_g_free0 (_tmp39_);
	}
	_tmp40_ = fso_framework_theLogger;
	_tmp41_ = bin;
	_tmp42_ = g_strdup_printf ("%s exit", _tmp41_);
	_tmp43_ = _tmp42_;
	fso_framework_logger_info (_tmp40_, _tmp43_);
	_g_free0 (_tmp43_);
	result = 0;
	_g_free0 (bin);
	return result;
}
コード例 #2
0
/*
 * Runs the RTP pipeline.
 * @param p Pointer to the RTP pipeline.
 */
static void
rtp_pipeline_run (rtp_pipeline * p)
{
  GstFlowReturn flow_ret;
  GMainLoop *mainloop = NULL;
  GstBus *bus;
  gint i, j;

  /* Check parameters. */
  if (p == NULL) {
    return;
  }

  /* Create mainloop. */
  mainloop = g_main_loop_new (NULL, FALSE);
  if (!mainloop) {
    return;
  }

  /* Add bus callback. */
  bus = gst_pipeline_get_bus (GST_PIPELINE (p->pipeline));

  gst_bus_add_watch (bus, rtp_bus_callback, (gpointer) mainloop);
  gst_object_unref (bus);

  /* Set pipeline to PLAYING. */
  gst_element_set_state (p->pipeline, GST_STATE_PLAYING);

  /* Push custom event into the pipeline */
  if (p->custom_event) {
    GstPad *srcpad;

    /* Install a probe to drop the event after it being serialized */
    srcpad = gst_element_get_static_pad (p->rtppay, "src");
    gst_pad_add_probe (srcpad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
        pay_event_probe_cb, p, NULL);
    gst_object_unref (srcpad);

    /* Install a probe to trace the deserialized event after depayloading */
    srcpad = gst_element_get_static_pad (p->rtpdepay, "src");
    gst_pad_add_probe (srcpad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
        depay_event_probe_cb, p, NULL);
    gst_object_unref (srcpad);
    /* Send the event */
    gst_element_send_event (p->appsrc, gst_event_ref (p->custom_event));
  }

  /* Push data into the pipeline */
  for (i = 0; i < LOOP_COUNT; i++) {
    const guint8 *data = p->frame_data;

    for (j = 0; j < p->frame_count; j++) {
      GstBuffer *buf;

      buf =
          gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
          (guint8 *) data, p->frame_data_size, 0, p->frame_data_size, NULL,
          NULL);

      g_signal_emit_by_name (p->appsrc, "push-buffer", buf, &flow_ret);
      fail_unless_equals_int (flow_ret, GST_FLOW_OK);
      data += p->frame_data_size;

      gst_buffer_unref (buf);
    }
  }

  g_signal_emit_by_name (p->appsrc, "end-of-stream", &flow_ret);

  /* Run mainloop. */
  g_main_loop_run (mainloop);

  /* Set pipeline to NULL. */
  gst_element_set_state (p->pipeline, GST_STATE_NULL);

  /* Release mainloop. */
  g_main_loop_unref (mainloop);

  fail_if (p->custom_event);
}
コード例 #3
0
static GstPlay *
play_new (gchar ** uris, const gchar * audio_sink, const gchar * video_sink,
    gboolean gapless, gdouble initial_volume)
{
  GstElement *sink, *playbin;
  GstPlay *play;

  playbin = gst_element_factory_make ("playbin", "playbin");
  if (playbin == NULL)
    return NULL;

  play = g_new0 (GstPlay, 1);

  play->uris = uris;
  play->num_uris = g_strv_length (uris);
  play->cur_idx = -1;

  play->playbin = playbin;

  if (audio_sink != NULL) {
    if (strchr (audio_sink, ' ') != NULL)
      sink = gst_parse_bin_from_description (audio_sink, TRUE, NULL);
    else
      sink = gst_element_factory_make (audio_sink, NULL);

    if (sink != NULL)
      g_object_set (play->playbin, "audio-sink", sink, NULL);
    else
      g_warning ("Couldn't create specified audio sink '%s'", audio_sink);
  }
  if (video_sink != NULL) {
    if (strchr (video_sink, ' ') != NULL)
      sink = gst_parse_bin_from_description (video_sink, TRUE, NULL);
    else
      sink = gst_element_factory_make (video_sink, NULL);

    if (sink != NULL)
      g_object_set (play->playbin, "video-sink", sink, NULL);
    else
      g_warning ("Couldn't create specified video sink '%s'", video_sink);
  }

  play->loop = g_main_loop_new (NULL, FALSE);

  play->bus_watch = gst_bus_add_watch (GST_ELEMENT_BUS (play->playbin),
      play_bus_msg, play);

  /* FIXME: make configurable incl. 0 for disable */
  play->timeout = g_timeout_add (100, play_timeout, play);

  play->missing = NULL;
  play->buffering = FALSE;
  play->is_live = FALSE;

  play->desired_state = GST_STATE_PLAYING;

  play->gapless = gapless;
  if (gapless) {
    g_signal_connect (play->playbin, "about-to-finish",
        G_CALLBACK (play_about_to_finish), play);
  }

  if (initial_volume != -1)
    play_set_relative_volume (play, initial_volume - 1.0);

  play->rate = 1.0;
  play->trick_mode = GST_PLAY_TRICK_MODE_NONE;

  return play;
}
コード例 #4
0
static void test_webkit_atk_get_text_at_offset(void)
{
    WebKitWebView* webView;
    AtkObject *obj;
    GMainLoop* loop;
    AtkText* text_obj;
    char* text;

    webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
    g_object_ref_sink(webView);
    webkit_web_view_load_string(webView, contents, NULL, NULL, NULL);
    loop = g_main_loop_new(NULL, TRUE);

    g_timeout_add(100, (GSourceFunc)bail_out, loop);
    g_main_loop_run(loop);

    /* Get to the inner AtkText object */
    obj = gtk_widget_get_accessible(GTK_WIDGET(webView));
    g_assert(obj);
    obj = atk_object_ref_accessible_child(obj, 0);
    g_assert(obj);
    obj = atk_object_ref_accessible_child(obj, 0);
    g_assert(obj);

    text_obj = ATK_TEXT(obj);
    g_assert(ATK_IS_TEXT(text_obj));

    text = atk_text_get_text(text_obj, 0, -1);
    g_assert_cmpstr(text, ==, "This is a test. This is the second sentence. And this the third.");
    g_free(text);

    /* ATK_TEXT_BOUNDARY_CHAR */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_CHAR,
                           0, "T", 0, 1);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_CHAR,
                           0, "h", 1, 2);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_CHAR,
                           0, "", 0, 0);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_CHAR,
                           1, "T", 0, 1);
    
    /* ATK_TEXT_BOUNDARY_WORD_START */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           0, "This ", 0, 5);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           4, "This ", 0, 5);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           10, "test. ", 10, 16);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           58, "third.", 58, 64);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           5, "This ", 0, 5);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           7, "This ", 0, 5);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           0, "is ", 5, 8);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           4, "is ", 5, 8);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           3, "is ", 5, 8);

    /* ATK_TEXT_BOUNDARY_WORD_END */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           0, "This", 0, 4);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           4, " is", 4, 7);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           5, " is", 4, 7);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           9, " test", 9, 14);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           5, "This", 0, 4);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           4, "This", 0, 4);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           7, " is", 4, 7);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           5, " a", 7, 9);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           4, " a", 7, 9);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           58, " third", 57, 63);

    /* ATK_TEXT_BOUNDARY_SENTENCE_START */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           0, "This is a test. ", 0, 16);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           15, "This is a test. ", 0, 16);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           0, "This is the second sentence. ", 16, 45);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           15, "This is the second sentence. ", 16, 45);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           16, "This is a test. ", 0, 16);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           44, "This is a test. ", 0, 16);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           15, "", 0, 0);

    /* ATK_TEXT_BOUNDARY_SENTENCE_END */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           0, "This is a test.", 0, 15);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           15, " This is the second sentence.", 15, 44);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           16, " This is the second sentence.", 15, 44);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           17, " This is the second sentence.", 15, 44);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           0, " This is the second sentence.", 15, 44);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           15, " And this the third.", 44, 64);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           16, "This is a test.", 0, 15);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           15, "This is a test.", 0, 15);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           14, "", 0, 0);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           44, " This is the second sentence.", 15, 44);

    /* It's trick to test these properly right now, since our a11y
       implementation splits different lines in different a11y
       items */
    /* ATK_TEXT_BOUNDARY_LINE_START */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_LINE_START,
                           0, "This is a test. This is the second sentence. And this the third.", 0, 64);

    /* ATK_TEXT_BOUNDARY_LINE_END */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_LINE_END,
                           0, "This is a test. This is the second sentence. And this the third.", 0, 64);

    g_object_unref(webView);
}
コード例 #5
0
/* This program implements the following gst-launch commandline:
gst-launch-0.10 filesrc location=DownUnder.mp3 ! 
		mad 		! 
		audioconvert  	! audio/x-raw-int,channels=2 ! 
		rtpL16pay  	! 
		udpsink 	host=localhost port=5000

*/
gint
main (gint   argc,
      gchar *argv[])
{ 
  GMainLoop 	*loop;
  GstElement 	*pipeline, *source, *demuxer, *resamp, *conv, *alaw, *rtp, *sink;
  GstBus 	*bus;  
  gchar 	**exclude_list  = NULL;
  gboolean	g711		= FALSE;
  gboolean      verbose		= FALSE;
  gint	  	port	 	= 5000;
  gchar		*musicFile	= NULL;
  gchar		*ipAddress      = NULL;
  GError 	*err 		= NULL;
  GOptionContext *ctx;

  GOptionEntry 	entries[] = {
    { "location", 'l', 0, G_OPTION_ARG_FILENAME, &musicFile,
      "The mp3 to be streamed", "FILE.mp3" },
    { "host", 'h', 0, G_OPTION_ARG_STRING, &ipAddress,
      "Unicast IP address or multicast group address to stream to", "IP@" },
    { "port", 'p', 0, G_OPTION_ARG_INT, &port,
      "UDP port to stream to (default 5000)", "PORT" },
    { "g711", 'g', 0, G_OPTION_ARG_NONE, &g711,
      "Stream Mono 8 bit 8kHz g711/alaw (default Stereo, L16 44.1kHz)", NULL },
    { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
      "Print verbose information (default: non-verbose)", NULL },
    { NULL }
  };

  // we must initialise the threading system before using any
  // other GLib funtion, such as g_option_context_new() 
  if (!g_thread_supported ())
    g_thread_init (NULL);

  ctx = g_option_context_new ("- Stream mp3 to unicast/multicast RTP stream (Stereo, L16 44.1kHz - Mono, 8bit 8kHz alaw)");
  g_option_context_add_main_entries (ctx, entries, NULL);
  g_option_context_add_group (ctx, gst_init_get_option_group ());
  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Failed to initialize: %s\n", err->message);
    g_error_free (err);
    return 1;
  }

  g_option_context_free(ctx);
  if (!musicFile || !ipAddress)
  {
    printf("location or host option not given. Use --help to see the options\n");
    g_free(musicFile);
    g_free(ipAddress);
    return -1;
  }

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

  loop = g_main_loop_new (NULL, FALSE);

  /* Create gstreamer elements */
  pipeline = 	gst_pipeline_new (NULL);
  source   = 	gst_element_factory_make ("filesrc", NULL);
  demuxer  = 	gst_element_factory_make ("mad", NULL);
  resamp   =	gst_element_factory_make ("audioresample", NULL);
  conv     = 	gst_element_factory_make ("audioconvert", NULL);
  sink     = 	gst_element_factory_make ("udpsink", NULL);

  if (g711) {
    rtp	   = gst_element_factory_make ("rtppcmapay", NULL);
    alaw   = gst_element_factory_make ("alawenc", NULL);
    if (!alaw) {
      g_printerr ("One element could not be created.\n");
      return -1;
    }
  } else {
    rtp	   = gst_element_factory_make ("rtpL16pay", NULL);
  }

  if (!pipeline || !source || !demuxer || !resamp || !conv || !rtp || !sink) 
  {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

  if (verbose) {/* get verbose information during start of the pipeline */
    g_signal_connect (	pipeline, 
			"deep-notify",
        		G_CALLBACK (gst_object_default_deep_notify), 
			exclude_list);
  }
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  gst_bus_add_watch (bus, my_bus_callback, loop);
  gst_object_unref (bus);

  /* link */
  
  if (g711) {
    gst_bin_add_many (GST_BIN (pipeline), source, demuxer, resamp, conv, alaw, rtp, sink, NULL);
    if (!gst_element_link_many (source, demuxer, resamp, conv, alaw, rtp, sink, NULL)) 
    {
      g_warning ("Failed to link elements!");
    }
  } else {
    gst_bin_add_many (GST_BIN (pipeline), source, demuxer, resamp, conv, rtp, sink, NULL);
    if (!gst_element_link_many (source, demuxer, resamp, conv, rtp, sink, NULL)) 
    {
      g_warning ("Failed to link elements!");
    }
  }
  /* set the source audio file */
  g_object_set (source, "location", musicFile, NULL);

  /* set RTP parameters */
  g_object_set (sink, "host", ipAddress, "port", port, NULL);

  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  /* now run */
  g_main_loop_run (loop);

  /* also clean up */
  g_free(musicFile);
  g_free(ipAddress);
  gst_element_set_state (pipeline, GST_STATE_NULL);
  gst_object_unref (GST_OBJECT (pipeline));

  return 0;
}
コード例 #6
0
ファイル: Mainloop.cpp プロジェクト: evifree/luna-sysservice
Mainloop::Mainloop()
{
	p_m_gmain = g_main_loop_new(NULL, FALSE);
}
コード例 #7
0
ファイル: main.c プロジェクト: justinzane/navit
int main(int argc, char **argv)
{
	GError *error = NULL;
	char *config_file = NULL;
	char *s;
	int l;

	signal(SIGCHLD, sigchld);

	setenv("LC_NUMERIC","C",1);
	setlocale(LC_ALL,"");
	setlocale(LC_NUMERIC,"C");
	setlocale(LC_NUMERIC,"C");

	if (file_exists("navit.c") || file_exists("navit.o")) {
		char buffer[PATH_MAX];
		printf(_("Running from source directory\n"));
		getcwd(buffer, PATH_MAX);
		setenv("NAVIT_PREFIX", buffer, 0);
		setenv("NAVIT_LIBDIR", buffer, 0);
		setenv("NAVIT_SHAREDIR", buffer, 0);
		setenv("NAVIT_LIBPREFIX", "*/.libs/", 0);
		s=g_strdup_printf("%s/../locale", buffer);	
		setenv("NAVIT_LOCALEDIR", s, 0);
		g_free(s);
	} else {
		if (!getenv("NAVIT_PREFIX")) {
			l=strlen(argv[0]);
			if (l > 10 && !strcmp(argv[0]+l-10,"/bin/navit")) {
				s=g_strdup(argv[0]);
				s[l-10]='\0';
				if (strcmp(s, PREFIX)) 
					printf(_("setting '%s' to '%s'\n"), "NAVIT_PREFIX", s);
				setenv("NAVIT_PREFIX", s, 0);
				g_free(s);
			} else 
				setenv("NAVIT_PREFIX", PREFIX, 0);
		}
		s=g_strdup_printf("%s/share/locale", getenv("NAVIT_PREFIX"));
		setenv("NAVIT_LOCALEDIR", s, 0);
		g_free(s);
		s=g_strdup_printf("%s/share/navit", getenv("NAVIT_PREFIX"));
		setenv("NAVIT_SHAREDIR", s, 0);
		g_free(s);
		s=g_strdup_printf("%s/lib/navit", getenv("NAVIT_PREFIX"));
		setenv("NAVIT_LIBDIR", s, 0);
		g_free(s);
	}
        bindtextdomain( "navit", getenv("NAVIT_LOCALEDIR"));
	textdomain( "navit" );

	debug_init();
#if 0
	/* handled in gui/gtk */
	gtk_set_locale();
	gtk_init(&argc, &argv);
	gdk_rgb_init();
#endif
	s = getenv("NAVIT_WID");
	if (s) {
		setenv("SDL_WINDOWID", s, 0);
	}
	config_file=NULL;
	if (argc > 1) 
		config_file=argv[1];
	if (! config_file) {
		config_file=g_strjoin(NULL,get_home_directory(), "/.navit/navit.xml" , NULL);
		if (!file_exists(config_file)) {
			g_free(config_file);
			config_file=NULL;
			}
	}
	if (! config_file) {
		if (file_exists("navit.xml.local"))
			config_file="navit.xml.local";
	}
	if (! config_file) {
		if (file_exists("navit.xml"))
			config_file="navit.xml";
	}
	if (! config_file) {
		config_file=g_strjoin(NULL,getenv("NAVIT_SHAREDIR"), "/navit.xml.local" , NULL);
		if (!file_exists(config_file)) {
			g_free(config_file);
			config_file=NULL;
		}
	}
	if (! config_file) {
		config_file=g_strjoin(NULL,getenv("NAVIT_SHAREDIR"), "/navit.xml" , NULL);
		if (!file_exists(config_file)) {
			g_free(config_file);
			config_file=NULL;
		}
	}
	if (!config_file) {
		printf(_("No config file navit.xml, navit.xml.local found\n"));
		exit(1);
	}
	if (!config_load(config_file, &error)) {
		printf(_("Error parsing '%s': %s\n"), config_file, error->message);
		exit(1);
	} else {
		printf(_("Using '%s'\n"), config_file);
	}
	if (! navit) {
		printf(_("No instance has been created, exiting\n"));
		exit(1);
	}
	if (main_loop_gui) {
		gui_run_main_loop(main_loop_gui);
	} else {
#ifdef USE_GTK_MAIN_LOOP
		gtk_main();
#else
		loop = g_main_loop_new (NULL, TRUE);
		if (g_main_loop_is_running (loop))
		{
			g_main_loop_run (loop);
		}
#endif
	}

	return 0;
}
コード例 #8
0
ファイル: tut7.c プロジェクト: kfihihc/xmms2-tutorial
int
main (int argc, char **argv)
{
	/*
	 * A struct that will hold the user data passed
	 * to the result method. In this case we need the
	 * GMainLoop and a counter in the result method.
	 */
	udata_t udata;

	/*
	 * The first part of this program is
	 * commented on in tut1.c
	 */
	xmmsc_connection_t *connection;
	xmmsc_result_t *result;

	/*
	 * In an async client we still connect as
	 * normal. Read up on this in earlier
	 * tutorials if you need.
	 */
	connection = xmmsc_init ("tutorial6");
	if (!connection) {
		fprintf (stderr, "OOM!\n");
		exit (EXIT_FAILURE);
	}

	if (!xmmsc_connect (connection, getenv ("XMMS_PATH"))) {
		fprintf (stderr, "Connection failed: %s\n",
		         xmmsc_get_last_error (connection));

		exit (EXIT_FAILURE);
	}

	/*
	 * Initialize the mainloop, for more information about GLib mainloop
	 * see the GTK docs.
	 */
	udata.ml = g_main_loop_new (NULL, FALSE);

	/*
	 * Initialize the counter to 0.
	 */
	udata.counter = 0;

	/*
	 * The big difference between a sync client and an async client is that the
	 * async client works with callbacks. When you send a command and get an
	 * xmmsc_result_t back you should set up a callback for it and directly
	 * unref it. This means we can't do syncronous operations on this connection.
	 *
	 * In simple cases you can use the XMMS_CALLBACK_SET macro, but in order to
	 * be verbose here I do it all manually. Let's ask for the current id
	 * in an async way instead of the sync way as we did in tut2.
	 */

	result = xmmsc_broadcast_playback_current_id (connection);
	xmmsc_result_notifier_set (result, my_current_id, &udata);
	xmmsc_result_unref (result);

	/*
	 * As you see we do it pretty much the same way that we did in tut2, but
	 * instead of being able to access the current id directly (as we would
	 * have if we where blocking) we need to wait until xmms calls our
	 * my_current_id function. This will keep your GUI from hanging while
	 * waiting for xmms2 to answer your command.
	 *
	 * In order to make xmmsclient call your callback functions we need to put
	 * the fd of the connection into the mainloop of our program. For your
	 * convenience the xmmsclient lib ships with automatic integration with
	 * GMainLoop. We just need to link with xmmsclient-glib and do the following
	 * call to make it work.
	 */
	xmmsc_mainloop_gmain_init (connection);

	/*
	 * We are now all set to go. Just run the main loop and watch the magic.
	 */

	g_main_loop_run (udata.ml);

	return EXIT_SUCCESS;

}
コード例 #9
0
ファイル: dunst.c プロジェクト: DSMan195276/dunst
int main(int argc, char *argv[])
{

        history = g_queue_new();
        displayed = g_queue_new();
        queue = g_queue_new();

        cmdline_load(argc, argv);

        if (cmdline_get_bool("-v/-version", false, "Print version")
            || cmdline_get_bool("--version", false, "Print version")) {
                print_version();
        }

        char *cmdline_config_path;
        cmdline_config_path =
            cmdline_get_string("-conf/-config", NULL,
                               "Path to configuration file");
        load_settings(cmdline_config_path);

        if (cmdline_get_bool("-h/-help", false, "Print help")
            || cmdline_get_bool("--help", false, "Print help")) {
                usage(EXIT_SUCCESS);
        }

        int owner_id = initdbus();

        x_setup();

        signal(SIGUSR1, pause_signal_handler);
        signal(SIGUSR2, pause_signal_handler);

        if (settings.startup_notification) {
                notification *n = malloc(sizeof(notification));
                n->appname = "dunst";
                n->summary = "startup";
                n->body = "dunst is up and running";
                n->progress = 0;
                n->timeout = 10;
                n->urgency = LOW;
                n->icon = NULL;
                n->category = NULL;
                n->msg = NULL;
                n->dbus_client = NULL;
                n->color_strings[0] = NULL;
                n->color_strings[1] = NULL;
                n->actions = NULL;
                n->urls = NULL;
                notification_init(n, 0);
        }

        mainloop = g_main_loop_new(NULL, FALSE);

        GPollFD dpy_pollfd = { xctx.dpy->fd,
                G_IO_IN | G_IO_HUP | G_IO_ERR, 0
        };

        GSourceFuncs x11_source_funcs = {
                x_mainloop_fd_prepare,
                x_mainloop_fd_check,
                x_mainloop_fd_dispatch,
                NULL,
                NULL,
                NULL
        };

        GSource *x11_source =
            g_source_new(&x11_source_funcs, sizeof(x11_source_t));
        ((x11_source_t *) x11_source)->dpy = xctx.dpy;
        ((x11_source_t *) x11_source)->w = xctx.win;
        g_source_add_poll(x11_source, &dpy_pollfd);

        g_source_attach(x11_source, NULL);

        run(NULL);
        g_main_loop_run(mainloop);

        dbus_tear_down(owner_id);

        return 0;
}
コード例 #10
0
int main (int argc, char *argv[])
{
  PseudoTcpCallbacks cbs = {
    NULL, opened, readable, writable, closed, write_packet
  };
  GOptionContext *context;
  GError *error = NULL;

  setlocale (LC_ALL, "");

  /* Configuration. */
  context = g_option_context_new ("— fuzz-test the pseudotcp socket");
  g_option_context_add_main_entries (context, entries, NULL);

  if (!g_option_context_parse (context, &argc, &argv, &error)) {
    g_printerr ("Option parsing failed: %s\n", error->message);
    goto context_error;
  }

  if (n_changes_lambda == 0) {
    g_printerr ("Option parsing failed: %s\n",
        "Lambda values must be positive.");
    goto context_error;
  }

  g_option_context_free (context);

  /* Tweak the configuration. */
  if (seed == 0) {
    seed = g_get_real_time ();
  }

  /* Open the input and output files */
  if (argc >= 3) {
    in = fopen (argv[1], "r");
    out = fopen (argv[2], "w");
  }

  /* Set up the main loop and sockets. */
  main_loop = g_main_loop_new (NULL, FALSE);

  g_print ("Using seed: %" G_GINT64_FORMAT ", start position: %u, λ: %u\n",
      seed, fuzz_start_pos, n_changes_lambda);
  prng = g_rand_new_with_seed (seed);

  pseudo_tcp_set_debug_level (PSEUDO_TCP_DEBUG_VERBOSE);

  left = pseudo_tcp_socket_new (0, &cbs);
  right = pseudo_tcp_socket_new (0, &cbs);
  g_debug ("Left: %p. Right: %p", left, right);

  pseudo_tcp_socket_notify_mtu (left, 1496);
  pseudo_tcp_socket_notify_mtu (right, 1496);

  pseudo_tcp_socket_connect (left);
  adjust_clock (left);
  adjust_clock (right);

  /* Run the main loop. */
  g_main_loop_run (main_loop);
  g_main_loop_unref (main_loop);

  g_object_unref (left);
  g_object_unref (right);

  g_rand_free (prng);

  if (in != NULL)
    fclose (in);
  if (out != NULL)
    fclose (out);

  return retval;

context_error:
  g_printerr ("\n%s\n", g_option_context_get_help (context, TRUE, NULL));
  g_option_context_free (context);

  return 1;
}
コード例 #11
0
ファイル: gst.c プロジェクト: alfredh/baresip
/**
 * Set up the Gstreamer pipeline. The playbin element is used to decode
 * all kinds of different formats. The capsfilter is used to deliver the
 * audio in a fixed format (X Hz, 1-2 channels, 16 bit signed)
 *
 * The pipeline looks like this:
 *
 * <pre>
 *  .--------------.    .------------------------------------------.
 *  |    playbin   |    |mybin    .------------.   .------------.  |
 *  |----.    .----|    |-----.   | capsfilter |   |  fakesink  |  |
 *  |sink|    |src |--->|ghost|   |----.   .---|   |----.   .---|  |    handoff
 *  |----'    '----|    |pad  |-->|sink|   |src|-->|sink|   |src|--+--> handler
 *  |              |    |-----'   '------------'   '------------'  |
 *  '--------------'    '------------------------------------------'
 * </pre>
 *
 * @param st Audio source state
 *
 * @return 0 if success, otherwise errorcode
 */
static int gst_setup(struct ausrc_st *st)
{
	GstBus *bus;
	GstPad *pad;

	st->loop = g_main_loop_new(NULL, FALSE);

	st->pipeline = gst_pipeline_new("pipeline");
	if (!st->pipeline) {
		warning("gst: failed to create pipeline element\n");
		return ENOMEM;
	}

	/********************* Player BIN **************************/

	st->source = gst_element_factory_make("playbin", "source");
	if (!st->source) {
		warning("gst: failed to create playbin source element\n");
		return ENOMEM;
	}

	/********************* My BIN **************************/

	st->bin = gst_bin_new("mybin");

	st->capsfilt = gst_element_factory_make("capsfilter", NULL);
	if (!st->capsfilt) {
		warning("gst: failed to create capsfilter element\n");
		return ENOMEM;
	}

	set_caps(st);

	st->sink = gst_element_factory_make("fakesink", "sink");
	if (!st->sink) {
		warning("gst: failed to create sink element\n");
		return ENOMEM;
	}

	gst_bin_add_many(GST_BIN(st->bin), st->capsfilt, st->sink, NULL);
	gst_element_link_many(st->capsfilt, st->sink, NULL);

	/* add ghostpad */
	pad = gst_element_get_static_pad(st->capsfilt, "sink");
	gst_element_add_pad(st->bin, gst_ghost_pad_new("sink", pad));
	gst_object_unref(GST_OBJECT(pad));

	/* put all elements in a bin */
	gst_bin_add_many(GST_BIN(st->pipeline), st->source, NULL);

	/* Override audio-sink handoff handler */
	g_object_set(G_OBJECT(st->sink), "signal-handoffs", TRUE, NULL);
	g_signal_connect(st->sink, "handoff", G_CALLBACK(handoff_handler), st);

	g_object_set(G_OBJECT(st->source), "audio-sink", st->bin, NULL);

	/********************* Misc **************************/

	/* Bus watch */
	bus = gst_pipeline_get_bus(GST_PIPELINE(st->pipeline));
	gst_bus_add_watch(bus, bus_watch_handler, st);
	gst_object_unref(bus);

	/* Set URI */
	g_object_set(G_OBJECT(st->source), "uri", st->uri, NULL);

	return 0;
}
コード例 #12
0
ファイル: meta-daemon.c プロジェクト: Alustriel/gvfs
int
main (int argc, char *argv[])
{
  GMainLoop *loop;
  GDBusConnection *conn;
  gboolean replace;
  GError *error;
  guint name_owner_id;
  GBusNameOwnerFlags flags;
  GOptionContext *context;
  const GOptionEntry options[] = {
    { "replace", 'r', 0, G_OPTION_ARG_NONE, &replace,  N_("Replace old daemon."), NULL },
    { NULL }
  };

  setlocale (LC_ALL, "");

  bindtextdomain (GETTEXT_PACKAGE, GVFS_LOCALEDIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);

  g_set_application_name (_("GVFS Metadata Daemon"));
  context = g_option_context_new ("");

  g_option_context_set_summary (context, _("Metadata daemon for GVFS"));

  g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);

  replace = FALSE;
  name_owner_id = 0;

  error = NULL;
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      /* Translators: the first %s is the application name, */
      /* the second %s is the error message                 */
      g_printerr (_("%s: %s"), g_get_application_name(), error->message);
      g_printerr ("\n");
      g_printerr (_("Try \"%s --help\" for more information."),
		  g_get_prgname ());
      g_printerr ("\n");
      g_error_free (error);
      g_option_context_free (context);
      return 1;
    }

  g_option_context_free (context);

  loop = g_main_loop_new (NULL, FALSE);

  error = NULL;
  conn = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
  if (!conn)
    {
      g_printerr ("Failed to connect to the D-BUS daemon: %s (%s, %d)\n",
                  error->message, g_quark_to_string (error->domain), error->code);
      g_error_free (error);
      return 1;
    }

  tree_infos = g_hash_table_new_full (g_str_hash,
				      g_str_equal,
				      NULL,
				      (GDestroyNotify)tree_info_free);

  g_dbus_connection_set_exit_on_close (conn, FALSE);
  g_signal_connect (conn, "closed", G_CALLBACK (on_connection_closed), loop);

  flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
  if (replace)
    flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;

  name_owner_id = g_bus_own_name_on_connection (conn,
                                                G_VFS_DBUS_METADATA_NAME,
                                                flags,
                                                on_name_acquired,
                                                on_name_lost,
                                                loop,
                                                NULL);
  
  g_main_loop_run (loop);
  
  if (skeleton)
    g_dbus_interface_skeleton_unexport (G_DBUS_INTERFACE_SKELETON (skeleton));
  if (name_owner_id != 0)
    g_bus_unown_name (name_owner_id);
  if (conn)
    g_object_unref (conn);
  if (loop != NULL)
    g_main_loop_unref (loop);

  return 0;
}
コード例 #13
0
ファイル: rygel-standalone.c プロジェクト: jmsal/niupnp
int main (int argc, char *argv[])
{
    RygelMediaServer *server;
    RygelSimpleContainer *root_container;
    char *path;
    GFile *source_dir;
    GFileEnumerator *enumerator;
    GFileInfo *info;
    int i;
    GMainLoop *loop;
    GError *error = NULL;

//     g_type_init ();

    rygel_media_engine_init (&error);

    if (error != NULL) {
        g_print ("Could not initialize media engine: %s\n",
                 error->message);
        g_error_free (error);

        return EXIT_FAILURE;
    }

    g_set_application_name ("Standalone-Server");

    root_container = rygel_simple_container_new_root ("Sample implementation");
    if (argc >= 2) {
        path = g_strdup (argv[1]);
    } else {
        path = g_get_current_dir ();
    }

    source_dir = g_file_new_for_commandline_arg (path);
    g_free (path);

    enumerator = g_file_enumerate_children (source_dir,
                                            G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME ","
                                            G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
                                            G_FILE_QUERY_INFO_NONE,
                                            NULL,
                                            NULL);
    info = g_file_enumerator_next_file (enumerator, NULL, NULL);
    i = 0;
    while (info != NULL) {
        GFile *file;
        const char *display_name, *content_type;
        char *uri, *id;
        RygelMediaItem *item = NULL;
        GError *error = NULL;

        display_name = g_file_info_get_display_name (info);
        content_type = g_file_info_get_content_type (info);
        file = g_file_get_child_for_display_name (source_dir, display_name, &error);
        if (error != NULL) {
            g_critical ("Failed to get child: %s", error->message);

            return 127;
        }
        uri = g_file_get_uri (file);
        g_object_unref (file);
        id = g_strdup_printf ("%06d", i);

        if (g_str_has_prefix (content_type, "audio/")) {
            item = (RygelMediaItem*)rygel_audio_item_new (id,
                                         (RygelMediaContainer*)root_container,
                                         display_name,
                                         RYGEL_AUDIO_ITEM_UPNP_CLASS);
        } else if (g_str_has_prefix (content_type, "video/")) {
            item = (RygelMediaItem*)rygel_video_item_new (id,
                                         (RygelMediaContainer*)root_container,
                                         display_name,
                                         RYGEL_VIDEO_ITEM_UPNP_CLASS);
        } else if (g_str_has_prefix (content_type, "image/")) {
            item = (RygelMediaItem*)rygel_image_item_new (id,
                                         (RygelMediaContainer*)root_container,
                                         display_name,
                                         RYGEL_IMAGE_ITEM_UPNP_CLASS);
        }
        g_free (id);

        if (item != NULL) {
            RygelMediaObject *object;
            GeeArrayList* uris;

            rygel_media_item_set_mime_type (RYGEL_MEDIA_ITEM (item), content_type);

            object = RYGEL_MEDIA_OBJECT (item);
            gee_collection_add (GEE_COLLECTION (object->uris), uri);

            rygel_simple_container_add_child_item (root_container, item);
        }

        i++;
        info = g_file_enumerator_next_file (enumerator, NULL, NULL);
    }

    server = rygel_media_server_new ("Single purpose server",
                                     (RygelMediaContainer*)root_container,
                                     RYGEL_PLUGIN_CAPABILITIES_NONE);
    rygel_media_device_add_interface (RYGEL_MEDIA_DEVICE (server), "eth0");
    rygel_media_device_add_interface (RYGEL_MEDIA_DEVICE (server), "wlan0");

    loop = g_main_loop_new (NULL, FALSE);
    g_main_loop_run (loop);
}
コード例 #14
0
int
main (int argc, char **argv)
{
	xmmsc_connection_t *conn;
	gchar *path;
	gchar *gp = NULL;
	gchar **s;
	gchar **ipcsplit;
	int i;

	printf ("Starting XMMS2 mDNS Agent...\n");

	path = getenv ("XMMS_PATH_FULL");
	if (!path) {
		printf ("Sorry you need XMMS_PATH_FULL set\n");
		exit (1);
	}

	ipcsplit = g_strsplit (path, ";", 0);
	for (i = 0; ipcsplit[i]; i++) {
		if (g_ascii_strncasecmp (ipcsplit[i], "tcp://", 6) == 0) {
			gp = ipcsplit[i];
		}
	}

	if (!gp) {
		printf ("Need to have a socket listening to TCP before we can do that!\n");
		exit (1);
	}

	s = g_strsplit (gp, ":", 0);
	if (s && s[2]) {
		port = strtol (s[2], NULL, 10);
	} else {
		port = XMMS_DEFAULT_TCP_PORT;
	}

	conn = xmmsc_init ("xmms2-mdns");

	if (!conn) {
		printf ("Could not init xmmsc_connection!\n");
		exit (1);
	}

	if (!xmmsc_connect (conn, gp)) {
		printf ("Could not connect to xmms2d: %s\n", xmmsc_get_last_error (conn));
		exit (1);
	}

	avahi_set_allocator (avahi_glib_allocator ());

	ml = g_main_loop_new (NULL, FALSE);

	XMMS_CALLBACK_SET (conn, xmmsc_broadcast_quit, handle_quit, ml);
	xmmsc_disconnect_callback_set (conn, disconnected, NULL);

	register_service ();

	xmmsc_mainloop_gmain_init (conn);

	g_main_loop_run (ml);

	xmmsc_unref (conn);
	printf ("XMMS2-mDNS shutting down...\n");

	g_main_loop_unref (ml);

	avahi_free (name);

	return 0;
}
コード例 #15
0
ファイル: xmlrpc-server-test.c プロジェクト: jwendell/libsoup
int
main (int argc, char **argv)
{
	SoupServer *server;
	SoupURI *server_uri;
	int ret;

	test_init (argc, argv, no_test_entry);

	server = soup_test_server_new (run_tests ? SOUP_TEST_SERVER_IN_THREAD : SOUP_TEST_SERVER_DEFAULT);
	soup_server_add_handler (server, "/xmlrpc-server.php",
				 server_callback, NULL, NULL);
	server_uri = soup_test_server_get_uri (server, "http", NULL);
	soup_uri_set_path (server_uri, "/xmlrpc-server.php");
	uri = soup_uri_to_string (server_uri, FALSE);

	if (run_tests) {
		char *out, **tests, *path;
		char *list_argv[4];
		GError *error = NULL;
		int i;

		list_argv[0] = NULL;
		list_argv[1] = "-S";
		list_argv[2] = "-l";
		list_argv[3] = NULL;

		if (!run_xmlrpc_test (list_argv, &out, NULL, &error)) {
			g_printerr ("'xmlrpc-test -l' failed: %s\n", error->message);
			g_error_free (error);
			return 1;
		}

		tests = g_strsplit (out, "\n", -1);
		g_free (out);

		for (i = 0; tests[i] && *tests[i]; i++) {
			g_assert_true (g_str_has_prefix (tests[i], "/xmlrpc/"));
			path = g_strdup_printf ("/xmlrpc-server/%s", tests[i] + strlen ("/xmlrpc/"));
			g_test_add_data_func (path, tests[i], do_one_xmlrpc_test);
			g_free (path);
		}

		ret = g_test_run ();

		g_strfreev (tests);
	} else {
		GMainLoop *loop;

		g_print ("Listening on port %d\n", server_uri->port);

		loop = g_main_loop_new (NULL, TRUE);
		g_main_loop_run (loop);
		g_main_loop_unref (loop);

		ret = 0;
	}

	soup_test_server_quit_unref (server);
	soup_uri_free (server_uri);
	g_free (uri);
	if (run_tests)
		test_cleanup ();
	return ret;
}
コード例 #16
0
int main(int argc, char ** argv)
{

  if (argc < 2) {
      usage (argc, argv);
      exit(1);
  }

  param_server_t * self = calloc(1, sizeof(param_server_t));
  GMainLoop * mainloop = g_main_loop_new(NULL, FALSE);
  if (!mainloop) {
      fprintf (stderr, "Error getting the GLIB main loop\n");
      exit(1);
  }


  char *optstring = "hs:l:m::";
  struct option long_opts[] = {
      { "help", no_argument, NULL, 'h' },
      { "server-name", required_argument, NULL, 's' },
      { "lcm-url", required_argument, NULL, 'l' },
      { "message-init", optional_argument, NULL, 'm' },
      { 0, 0, 0, 0 }
  };
  int c=-1;
  char *param_prefix = NULL;
  char *lcm_url = NULL;
  char *message_init_channel = NULL;
  while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0)
  {
      switch (c) {
      case 's':
          param_prefix = optarg;
          break;
      case 'l':
          lcm_url = optarg;
          break;
      case 'm':
          message_init_channel = (optarg==NULL) ? BOT_PARAM_UPDATE_CHANNEL : optarg;
          break;
      case 'h':
      default:
          usage (argc, argv);
          return 1;
      }
  }
  
  self->lcm = lcm_create(lcm_url);
  lcmu_glib_mainloop_attach_lcm(self->lcm);
  

  self->seqNo = 0;
  self->id = _timestamp_now();
  if (message_init_channel == NULL) {
    self->params = bot_param_new_from_file(argv[optind]);
    if (self->params==NULL){
      fprintf(stderr, "Could not load params from %s\n", argv[optind]);
      exit(1);
    }
    else{
      fprintf(stderr, "Loaded params from %s\n", argv[optind]);
    }
  }

  // set channels here
  if (!param_prefix) param_prefix = getenv ("BOT_PARAM_SERVER_NAME");
  self->update_channel = g_strconcat (param_prefix ? : "", 
          BOT_PARAM_UPDATE_CHANNEL, NULL);
  self->request_channel = g_strconcat (param_prefix ? : "", 
          BOT_PARAM_REQUEST_CHANNEL, NULL);
  self->set_channel = g_strconcat (param_prefix ? : "", 
          BOT_PARAM_SET_CHANNEL, NULL);

  bot_param_update_t_subscribe(self->lcm, self->update_channel, on_param_update, (void *) self);
  bot_param_request_t_subscribe(self->lcm, self->request_channel, on_param_request, (void *) self);
  bot_param_set_t_subscribe(self->lcm, self->set_channel, on_param_set, (void *) self);

  if (message_init_channel != NULL) {
      fprintf(stderr, "Listening to %s for params\n", message_init_channel);
      self->init_subscription = bot_param_update_t_subscribe(self->lcm, message_init_channel, on_param_init, (void *)self);
  }

  //timer to always publish params every 5sec
  g_timeout_add_full(G_PRIORITY_HIGH, (guint) 5.0 * 1000, on_timer, (gpointer) self, NULL);

  g_main_loop_run(mainloop);

  return 0;
}
gint
main (gint argc,
      gchar **argv)
{
	guint id;
	guint watched_id;
	ESubprocessBookFactory *subprocess_book_factory;
	GMainLoop *loop;
	GDBusObjectManagerServer *manager;
	GOptionContext *context;
	SubprocessData sd;
	GError *error = NULL;

#ifdef G_OS_WIN32
	e_util_win32_initialize ();
#endif

	setlocale (LC_ALL, "");
	bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");

	/* Workaround https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
	g_type_ensure (G_TYPE_DBUS_CONNECTION);

#if defined (ENABLE_MAINTAINER_MODE) && defined (HAVE_GTK)
	if (g_getenv ("EDS_TESTING") == NULL)
		/* This is only to load gtk-modules, like
		 * bug-buddy's gnomesegvhandler, if possible */
		gtk_init_check (&argc, &argv);
#endif

	context = g_option_context_new (NULL);
	g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
	g_option_context_parse (context, &argc, &argv, &error);
	g_option_context_free (context);

	if (error != NULL) {
		g_printerr ("%s\n", error->message);
		exit (EXIT_FAILURE);
	}

	loop = g_main_loop_new (NULL, FALSE);

	manager = g_dbus_object_manager_server_new ("/org/gnome/evolution/dataserver/Subprocess/Backend");

	subprocess_book_factory = e_subprocess_book_factory_new (NULL, NULL);

	sd.loop = loop;
	sd.manager = manager;
	sd.subprocess_book_factory = subprocess_book_factory;

	/* Watch the factory name and close the subprocess if the factory dies/crashes */
	watched_id = g_bus_watch_name (
		G_BUS_TYPE_SESSION,
		ADDRESS_BOOK_DBUS_SERVICE_NAME,
		G_BUS_NAME_WATCHER_FLAGS_NONE,
		NULL,
		(GBusNameVanishedCallback) vanished_cb,
		&sd,
		NULL);

	id = g_bus_own_name (
		G_BUS_TYPE_SESSION,
		bus_name,
		G_BUS_NAME_OWNER_FLAGS_NONE,
		(GBusAcquiredCallback) on_bus_acquired,
		NULL,
		NULL,
		&sd,
		NULL);

	g_main_loop_run (loop);

	g_bus_unown_name (id);
	g_bus_unwatch_name (watched_id);

	g_clear_object (&subprocess_book_factory);
	g_clear_object (&manager);
	g_main_loop_unref (loop);

	return 0;
}
コード例 #18
0
ファイル: gui-misc.c プロジェクト: bert/pcb
  /* Run a glib GMainLoop which intercepts key and mouse button events from
     |  the top level loop.  When a mouse or key is hit in the Output drawing
     |  area, quit the loop so the top level loop can continue and use the
     |  the mouse pointer coordinates at the time of the mouse button event.
   */
static gboolean
run_get_location_loop (const gchar * message)
{
  GMainLoop *loop;
  gulong button_handler, key_handler;
  gint oldObjState, oldLineState, oldBoxState;

  /* Make the text cue bold so it hides less and looks like command prompt  */
  GString *bold_message = g_string_new (message);
  g_string_prepend (bold_message, "<b>");
  g_string_append (bold_message, "</b>");

  ghid_status_line_set_text (bold_message->str);

  g_string_free (bold_message, TRUE);

  oldObjState = Crosshair.AttachedObject.State;
  oldLineState = Crosshair.AttachedLine.State;
  oldBoxState = Crosshair.AttachedBox.State;
  notify_crosshair_change (false);
  Crosshair.AttachedObject.State = STATE_FIRST;
  Crosshair.AttachedLine.State = STATE_FIRST;
  Crosshair.AttachedBox.State = STATE_FIRST;
  ghid_hand_cursor ();
  notify_crosshair_change (true);

  /* Stop the top level GMainLoop from getting user input from keyboard
     |  and mouse so we can install our own handlers here.  Also set the
     |  control interface insensitive so all the user can do is hit a key
     |  or mouse button in the Output drawing area.
   */
  ghid_interface_input_signals_disconnect ();
  ghid_interface_set_sensitive (FALSE);

  got_location = TRUE;		/* Will be unset by hitting most keys */
  button_handler =
    g_signal_connect (G_OBJECT (gport->drawing_area),
		      "button_press_event",
		      G_CALLBACK (loop_button_press_cb), &loop);
  key_handler =
    g_signal_connect (G_OBJECT (gport->top_window),
		      "key_press_event",
		      G_CALLBACK (loop_key_press_cb), &loop);

  loop = g_main_loop_new (NULL, FALSE);

  GDK_THREADS_LEAVE ();
  g_main_loop_run (loop);
  GDK_THREADS_ENTER ();

  g_main_loop_unref (loop);

  g_signal_handler_disconnect (gport->drawing_area, button_handler);
  g_signal_handler_disconnect (gport->top_window, key_handler);

  ghid_interface_input_signals_connect ();	/* return to normal */
  ghid_interface_set_sensitive (TRUE);

  notify_crosshair_change (false);
  Crosshair.AttachedObject.State = oldObjState;
  Crosshair.AttachedLine.State = oldLineState;
  Crosshair.AttachedBox.State = oldBoxState;
  notify_crosshair_change (true);
  ghid_restore_cursor ();

  ghid_set_status_line_label ();

  return got_location;
}
コード例 #19
0
ファイル: hciemu.c プロジェクト: thentenaar/bluez-dinovo
int main(int argc, char *argv[])
{
	struct sigaction sa;
	GIOChannel *dev_io;
	char *device = NULL, *snoop = NULL;
	bdaddr_t bdaddr;
	int fd, dd, opt, detach = 1, dev = -1;

	bacpy(&bdaddr, BDADDR_ANY);

	while ((opt=getopt_long(argc, argv, "d:b:s:nh", main_options, NULL)) != EOF) {
		switch(opt) {
		case 'd':
			device = strdup(optarg);
			break;

		case 'b':
			str2ba(optarg, &bdaddr);
			break;

		case 's':
			snoop = strdup(optarg);
			break;

		case 'n':
			detach = 0;
			break;

		case 'h':
		default:
			usage();
			exit(0);
		}
	}

	argc -= optind;
	argv += optind;
	optind = 0;

	if (argc < 1) {
		usage();
		exit(1);
	}

	if (strlen(argv[0]) > 3 && !strncasecmp(argv[0], "hci", 3)) {
		dev = hci_devid(argv[0]);
		if (dev < 0) {
			perror("Invalid device");
			exit(1);
		}
	} else {
		if (getbdaddrbyname(argv[0], &vdev.bdaddr) < 0)
			exit(1);
	}

	if (detach) {
		if (daemon(0, 0)) {
			perror("Can't start daemon");
			exit(1);
		}
	}

	/* Start logging to syslog and stderr */
	openlog("hciemu", LOG_PID | LOG_NDELAY | LOG_PERROR, LOG_DAEMON);
	syslog(LOG_INFO, "HCI emulation daemon ver %s started", VERSION);

	memset(&sa, 0, sizeof(sa));
	sa.sa_flags   = SA_NOCLDSTOP;
	sa.sa_handler = SIG_IGN;
	sigaction(SIGCHLD, &sa, NULL);
	sigaction(SIGPIPE, &sa, NULL);

	sa.sa_handler = sig_term;
	sigaction(SIGTERM, &sa, NULL);
	sigaction(SIGINT,  &sa, NULL);

	io_init();

	if (!device && dev >= 0)
		device = strdup(GHCI_DEV);

	/* Open and create virtual HCI device */
	if (device) {
		fd = open(device, O_RDWR);
		if (fd < 0) {
			syslog(LOG_ERR, "Can't open device %s: %s (%d)",
						device, strerror(errno), errno);
			free(device);
			exit(1);
		}
		free(device);
	} else {
		fd = open(VHCI_DEV, O_RDWR);
		if (fd < 0) {
			fd = open(VHCI_UDEV, O_RDWR);
			if (fd < 0) {
				syslog(LOG_ERR, "Can't open device %s: %s (%d)",
						VHCI_DEV, strerror(errno), errno);
				exit(1);
			}
		}
	}

	/* Create snoop file */
	if (snoop) {
		dd = create_snoop(snoop);
		if (dd < 0)
			syslog(LOG_ERR, "Can't create snoop file %s: %s (%d)",
						snoop, strerror(errno), errno);
		free(snoop);
	} else
		dd = -1;

	/* Create event loop */
	event_loop = g_main_loop_new(NULL, FALSE);

	if (dev >= 0)
		return run_proxy(fd, dev, &bdaddr);

	/* Device settings */
	vdev.features[0] = 0xff;
	vdev.features[1] = 0xff;
	vdev.features[2] = 0x8f;
	vdev.features[3] = 0xfe;
	vdev.features[4] = 0x9b;
	vdev.features[5] = 0xf9;
	vdev.features[6] = 0x01;
	vdev.features[7] = 0x80;

	memset(vdev.name, 0, sizeof(vdev.name));
	strncpy((char *) vdev.name, "BlueZ (Virtual HCI)",
							sizeof(vdev.name) - 1);

	vdev.dev_class[0] = 0x00;
	vdev.dev_class[1] = 0x00;
	vdev.dev_class[2] = 0x00;

	vdev.inq_mode = 0x00;
	vdev.eir_fec = 0x00;
	memset(vdev.eir_data, 0, sizeof(vdev.eir_data));

	vdev.fd = fd;
	vdev.dd = dd;

	dev_io = g_io_channel_unix_new(fd);
	g_io_add_watch(dev_io, G_IO_IN, io_hci_data, NULL);

	setpriority(PRIO_PROCESS, 0, -19);

	/* Start event processor */
	g_main_loop_run(event_loop);

	close(fd);

	if (dd >= 0)
		close(dd);

	syslog(LOG_INFO, "Exit");

	return 0;
}
コード例 #20
0
ファイル: empty-server.c プロジェクト: Distrotech/libbonobo
int
main (int argc, char *argv[])
{
	PortableServer_ObjectId *objid;
	PortableServer_POA poa;
	GOptionContext *ctx;
	GOptionGroup *goption_group;
	GError *error = NULL;
        GMainLoop *loop;

	CORBA_Environment ev;
	CORBA_ORB orb;
	GSList *reg_env = NULL;

	signal (SIGINT, do_exit);
	signal (SIGTERM, do_exit);

        g_thread_init (NULL);

	CORBA_exception_init (&ev);
	orb = bonobo_activation_init (argc, argv);

	g_set_prgname ("bonobo-activation-empty-server");
	ctx = g_option_context_new (NULL);
	goption_group = bonobo_activation_get_goption_group ();
	g_option_context_set_main_group (ctx, goption_group);
	if (!g_option_context_parse (ctx, &argc, &argv, &error)) {
		g_printerr ("%s\n", error->message);
		g_error_free (error);
		exit (1);
	}
	g_option_context_free (ctx);

	POA_Empty__init (&poa_empty_servant, &ev);

	poa = (PortableServer_POA)
		CORBA_ORB_resolve_initial_references (orb, "RootPOA", &ev);
	objid = PortableServer_POA_activate_object (poa, &poa_empty_servant, &ev);

	empty_client = PortableServer_POA_servant_to_reference (poa,
								&poa_empty_servant,
								&ev);
	if (!empty_client) {
		printf ("Cannot get objref\n");
		return 1;
	}

#ifndef G_OS_WIN32
	reg_env = bonobo_activation_registration_env_set (
			reg_env, "DISPLAY", getenv ("DISPLAY"));
	reg_env = bonobo_activation_registration_env_set (
			reg_env, "SESSION_MANAGER", getenv ("SESSION_MANAGER"));
	reg_env = bonobo_activation_registration_env_set (
			reg_env, "AUDIODEV", getenv ("AUDIODEV"));
#endif
	reg_env = bonobo_activation_registration_env_set (
			reg_env, "LANG", getenv ("LANG"));

        /*
         * NB. It is imperative to register the server that is being
         * requested last - or we can still race in the activation daemon.
         */
	bonobo_activation_register_active_server ("OAFIID:Empty2:19991025", empty_client, reg_env);
        g_usleep (500000); /* 1/2 sec */
	bonobo_activation_register_active_server ("OAFIID:Empty:19991025", empty_client, reg_env);

	bonobo_activation_registration_env_free (reg_env);

	PortableServer_POAManager_activate
		(PortableServer_POA__get_the_POAManager (poa, &ev), &ev);

        /* run the CORBA main loop for a couple of seconds then quit */
        loop = g_main_loop_new (NULL, FALSE);
        g_timeout_add (1000, (GSourceFunc) g_main_loop_quit, loop);
        g_main_loop_run (loop);

	bonobo_activation_active_server_unregister ("OAFIID:Empty:19991025", empty_client);
	bonobo_activation_active_server_unregister ("OAFIID:Empty2:19991025", empty_client);

	PortableServer_POA_deactivate_object (poa, objid, &ev);

	return 0;
}
コード例 #21
0
ファイル: mce.c プロジェクト: g7/mce
/**
 * Main
 *
 * @param argc Number of command line arguments
 * @param argv Array with command line arguments
 * @return 0 on success, non-zero on failure
 */
int main(int argc, char **argv)
{
	int status = EXIT_FAILURE;

	/* Set the program-name */
	progname = PRG_NAME;

	/* Parse the command-line options */
	if( !mce_command_line_parse(options, argc, argv) )
		goto EXIT;

	/* We don't take any non-flag arguments */
	if ((argc - optind) > 0) {
		fprintf(stderr, "%s: Too many arguments\n"
			"Try: `%s --help' for more information.\n",
			progname, progname);
		exit(EXIT_FAILURE);
	}

	mce_log_open(PRG_NAME, LOG_DAEMON, mce_args.logtype);
	mce_log_set_verbosity(mce_args.verbosity);

#ifdef ENABLE_WAKELOCKS
	/* Since mce enables automatic suspend, we must try to
	 * disable it when mce process exits */
	atexit(mce_cleanup_wakelocks);
#endif

	/* Identify mce version & flavor on start up */
	mce_log(LL_WARN, "MCE %s (%s) starting up",
		G_STRINGIFY(PRG_VERSION),
		(LL_DEVEL == LL_EXTRA) ? "devel" : "release");

	/* Daemonize if requested */
	if( mce_args.daemonflag )
		daemonize();

	/* Register a mainloop */
	mainloop = g_main_loop_new(NULL, FALSE);

	/* Signal handlers can be installed once we have a mainloop */
	if( !mce_init_signal_pipe() ) {
		mce_log(LL_CRIT, "Failed to initialise signal pipe");
		exit(EXIT_FAILURE);
	}
	mce_signal_handlers_install();

	/* Initialise subsystems */

	/* Open fbdev as early as possible */
	mce_fbdev_init();

	/* Get configuration options */
	if( !mce_conf_init() ) {
		mce_log(LL_CRIT,
			"Failed to initialise configuration options");
		exit(EXIT_FAILURE);
	}

	/* Initialise D-Bus */
	if( !mce_dbus_init(mce_args.systembus) ) {
		mce_log(LL_CRIT,
			"Failed to initialise D-Bus");
		exit(EXIT_FAILURE);
	}

	/* Initialise GConf
	 * pre-requisite: g_type_init()
	 */
	if (mce_gconf_init() == FALSE) {
		mce_log(LL_CRIT,
			"Cannot connect to default GConf engine");
		exit(EXIT_FAILURE);
	}

	/* Setup all datapipes */
	mce_datapipe_init();

	/* Allow registering of suspend proof timers */
	mce_hbtimer_init();

	/* Initialise mode management
	 * pre-requisite: mce_gconf_init()
	 * pre-requisite: mce_dbus_init()
	 */
	if (mce_mode_init() == FALSE) {
		goto EXIT;
	}

	/* Initialise DSME
	 * pre-requisite: mce_gconf_init()
	 * pre-requisite: mce_dbus_init()
	 * pre-requisite: mce_mce_init()
	 */
	if( !mce_dsme_init() )
		goto EXIT;

	/* Initialise powerkey driver */
	if (mce_powerkey_init() == FALSE) {
		goto EXIT;
	}

	/* Initialise /dev/input driver
	 * pre-requisite: g_type_init()
	 */
	if (mce_input_init() == FALSE) {
		goto EXIT;
	}

	/* Initialise switch driver */
	if (mce_switches_init() == FALSE) {
		goto EXIT;
	}

	/* Initialise tklock driver */
	if (mce_tklock_init() == FALSE) {
		goto EXIT;
	}

	if( !mce_sensorfw_init() ) {
		goto EXIT;
	}

	/* Load all modules */
	if (mce_modules_init() == FALSE) {
		goto EXIT;
	}

	if( mce_args.show_module_info ) {
		mce_modules_dump_info();
		goto EXIT;
	}

	/* MCE startup succeeded */
	status = EXIT_SUCCESS;

	/* Tell systemd that we have started up */
	if( mce_args.systemd_notify ) {
		mce_log(LL_NOTICE, "notifying systemd");
		sd_notify(0, "READY=1");
	}
	/* Debug feature: exit after startup is finished */
	if( mce_args.auto_exit >= 0 ) {
		mce_log(LL_WARN, "auto-exit scheduled");
		g_idle_add(mce_auto_exit_cb, 0);
	}

	/* Run the main loop */
	g_main_loop_run(mainloop);

	/* If we get here, the main loop has terminated;
	 * either because we requested or because of an error
	 */
EXIT:
	/* Unload all modules */
	mce_modules_exit();

	/* Call the exit function for all components */
	mce_sensorfw_quit();
	mce_tklock_exit();
	mce_switches_exit();
	mce_input_exit();
	mce_powerkey_exit();
	mce_dsme_exit();
	mce_mode_exit();
	mce_hbtimer_quit();

	/* Free all datapipes */
	mce_datapipe_quit();

	/* Call the exit function for all subsystems */
	mce_gconf_exit();
	mce_dbus_exit();
	mce_conf_exit();
	mce_fbdev_quit();

	/* If the mainloop is initialised, unreference it */
	if (mainloop != NULL) {
		g_main_loop_unref(mainloop);
		mainloop = 0;
	}

	/* Close signal pipe & remove io watch for it */
	mce_quit_signal_pipe();

	/* Log a farewell message and close the log */
	mce_log(LL_INFO, "Exiting...");

	/* No more logging expected */
	mce_log_close();

	return status;
}
コード例 #22
0
int
main (int argc,
      char * argv[])
{
  guint target_pid;
  FridaDeviceManager * manager;
  GError * error = NULL;
  FridaDeviceList * devices;
  gint num_devices, i;
  FridaDevice * local_device;
  FridaSession * session;

  frida_init ();

  if (argc != 2 || (target_pid = atoi (argv[1])) == 0)
  {
    g_printerr ("Usage: %s <pid>\n", argv[0]);
    return 1;
  }

  loop = g_main_loop_new (NULL, TRUE);

  signal (SIGINT, on_signal);
  signal (SIGTERM, on_signal);

  manager = frida_device_manager_new ();

  devices = frida_device_manager_enumerate_devices_sync (manager, &error);
  g_assert (error == NULL);

  local_device = NULL;
  num_devices = frida_device_list_size (devices);
  for (i = 0; i != num_devices; i++)
  {
    FridaDevice * device = frida_device_list_get (devices, i);

    g_print ("[*] Found device: \"%s\"\n", frida_device_get_name (device));

    if (frida_device_get_dtype (device) == FRIDA_DEVICE_TYPE_LOCAL)
      local_device = g_object_ref (device);

    g_object_unref (device);
  }
  g_assert (local_device != NULL);

  frida_unref (devices);
  devices = NULL;

  session = frida_device_attach_sync (local_device, target_pid, &error);
  if (error == NULL)
  {
    FridaScript * script;
    FridaScriptOptions * options;

    g_print ("[*] Attached\n");

    options = frida_script_options_new ();
    frida_script_options_set_name (options, "example");
    frida_script_options_set_runtime (options, FRIDA_SCRIPT_RUNTIME_V8);

    script = frida_session_create_script_sync (session,
        "Interceptor.attach(Module.getExportByName('kernel32.dll', 'CreateFileW'), {\n"
        "  onEnter(args) {\n"
        "    console.log('[*] CreateFileW(\"' + args[0].readUtf16String() + '\")');\n"
        "  }\n"
        "});\n"
        "Interceptor.attach(Module.getExportByName('kernel32.dll', 'CloseHandle'), {\n"
        "  onEnter(args) {\n"
        "    console.log('[*] CloseHandle(' + args[0] + ')');\n"
        "  }\n"
        "});",
        options, &error);
    g_assert (error == NULL);

    g_clear_object (&options);

    g_signal_connect (script, "message", G_CALLBACK (on_message), NULL);

    frida_script_load_sync (script, &error);
    g_assert (error == NULL);

    g_print ("[*] Script loaded\n");

    if (g_main_loop_is_running (loop))
      g_main_loop_run (loop);

    g_print ("[*] Stopped\n");

    frida_script_unload_sync (script, NULL);
    frida_unref (script);
    g_print ("[*] Unloaded\n");

    frida_session_detach_sync (session);
    frida_unref (session);
    g_print ("[*] Detached\n");
  }
  else
  {
    g_printerr ("Failed to attach: %s\n", error->message);
    g_error_free (error);
  }

  frida_unref (local_device);

  frida_device_manager_close_sync (manager);
  frida_unref (manager);
  g_print ("[*] Closed\n");

  g_main_loop_unref (loop);

  return 0;
}
コード例 #23
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GOptionGroup *gatt_group, *params_group, *char_rw_group;
	GError *gerr = NULL;
	GIOChannel *chan;

	opt_sec_level = g_strdup("low");

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);

	/* GATT commands */
	gatt_group = g_option_group_new("gatt", "GATT commands",
					"Show all GATT commands", NULL, NULL);
	g_option_context_add_group(context, gatt_group);
	g_option_group_add_entries(gatt_group, gatt_options);

	/* Primary Services and Characteristics arguments */
	params_group = g_option_group_new("params",
			"Primary Services/Characteristics arguments",
			"Show all Primary Services/Characteristics arguments",
			NULL, NULL);
	g_option_context_add_group(context, params_group);
	g_option_group_add_entries(params_group, primary_char_options);

	/* Characteristics value/descriptor read/write arguments */
	char_rw_group = g_option_group_new("char-read-write",
		"Characteristics Value/Descriptor Read/Write arguments",
		"Show all Characteristics Value/Descriptor Read/Write "
		"arguments",
		NULL, NULL);
	g_option_context_add_group(context, char_rw_group);
	g_option_group_add_entries(char_rw_group, char_rw_options);

	if (g_option_context_parse(context, &argc, &argv, &gerr) == FALSE) {
		g_printerr("%s\n", gerr->message);
		g_error_free(gerr);
	}

	if (opt_interactive) {
		interactive(opt_src, opt_dst, opt_psm);
		goto done;
	}

	if (opt_primary)
		operation = primary;
	else if (opt_characteristics)
		operation = characteristics;
	else if (opt_char_read)
		operation = characteristics_read;
	else if (opt_char_write)
		operation = characteristics_write;
	else if (opt_char_write_req)
		operation = characteristics_write_req;
	else if (opt_char_desc)
		operation = characteristics_desc;
	else {
		gchar *help = g_option_context_get_help(context, TRUE, NULL);
		g_print("%s\n", help);
		g_free(help);
		got_error = TRUE;
		goto done;
	}

	chan = gatt_connect(opt_src, opt_dst, opt_sec_level,
					opt_psm, opt_mtu, connect_cb);
	if (chan == NULL) {
		got_error = TRUE;
		goto done;
	}

	event_loop = g_main_loop_new(NULL, FALSE);

	g_main_loop_run(event_loop);

	g_main_loop_unref(event_loop);

done:
	g_option_context_free(context);
	g_free(opt_src);
	g_free(opt_dst);
	g_free(opt_uuid);
	g_free(opt_sec_level);

	if (got_error)
		exit(EXIT_FAILURE);
	else
		exit(EXIT_SUCCESS);
}
コード例 #24
0
ファイル: main.c プロジェクト: Acidburn0zzz/qemu
int main(int argc, char **argv)
{
    const char *sopt = "hVvdm:p:l:f:F::b:s:t:";
    const char *method = NULL, *path = NULL;
    const char *log_filepath = NULL;
    const char *pid_filepath;
#ifdef CONFIG_FSFREEZE
    const char *fsfreeze_hook = NULL;
#endif
    const char *state_dir;
#ifdef _WIN32
    const char *service = NULL;
#endif
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
        { "logfile", 1, NULL, 'l' },
        { "pidfile", 1, NULL, 'f' },
#ifdef CONFIG_FSFREEZE
        { "fsfreeze-hook", 2, NULL, 'F' },
#endif
        { "verbose", 0, NULL, 'v' },
        { "method", 1, NULL, 'm' },
        { "path", 1, NULL, 'p' },
        { "daemonize", 0, NULL, 'd' },
        { "blacklist", 1, NULL, 'b' },
#ifdef _WIN32
        { "service", 1, NULL, 's' },
#endif
        { "statedir", 1, NULL, 't' },
        { NULL, 0, NULL, 0 }
    };
    int opt_ind = 0, ch, daemonize = 0, i, j, len;
    GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
    GList *blacklist = NULL;
    GAState *s;

    module_call_init(MODULE_INIT_QAPI);

    init_dfl_pathnames();
    pid_filepath = dfl_pathnames.pidfile;
    state_dir = dfl_pathnames.state_dir;

    while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
        switch (ch) {
        case 'm':
            method = optarg;
            break;
        case 'p':
            path = optarg;
            break;
        case 'l':
            log_filepath = optarg;
            break;
        case 'f':
            pid_filepath = optarg;
            break;
#ifdef CONFIG_FSFREEZE
        case 'F':
            fsfreeze_hook = optarg ? optarg : QGA_FSFREEZE_HOOK_DEFAULT;
            break;
#endif
        case 't':
             state_dir = optarg;
             break;
        case 'v':
            /* enable all log levels */
            log_level = G_LOG_LEVEL_MASK;
            break;
        case 'V':
            printf("QEMU Guest Agent %s\n", QEMU_VERSION);
            return 0;
        case 'd':
            daemonize = 1;
            break;
        case 'b': {
            if (is_help_option(optarg)) {
                qmp_for_each_command(ga_print_cmd, NULL);
                return 0;
            }
            for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
                if (optarg[i] == ',') {
                    optarg[i] = 0;
                    blacklist = g_list_append(blacklist, &optarg[j]);
                    j = i + 1;
                }
            }
            if (j < i) {
                blacklist = g_list_append(blacklist, &optarg[j]);
            }
            break;
        }
#ifdef _WIN32
        case 's':
            service = optarg;
            if (strcmp(service, "install") == 0) {
                const char *fixed_state_dir;

                /* If the user passed the "-t" option, we save that state dir
                 * in the service. Otherwise we let the service fetch the state
                 * dir from the environment when it starts.
                 */
                fixed_state_dir = (state_dir == dfl_pathnames.state_dir) ?
                                  NULL :
                                  state_dir;
                if (ga_install_vss_provider()) {
                    return EXIT_FAILURE;
                }
                if (ga_install_service(path, log_filepath, fixed_state_dir)) {
                    return EXIT_FAILURE;
                }
                return 0;
            } else if (strcmp(service, "uninstall") == 0) {
                ga_uninstall_vss_provider();
                return ga_uninstall_service();
            } else {
                printf("Unknown service command.\n");
                return EXIT_FAILURE;
            }
            break;
#endif
        case 'h':
            usage(argv[0]);
            return 0;
        case '?':
            g_print("Unknown option, try '%s --help' for more information.\n",
                    argv[0]);
            return EXIT_FAILURE;
        }
    }

#ifdef _WIN32
    /* On win32 the state directory is application specific (be it the default
     * or a user override). We got past the command line parsing; let's create
     * the directory (with any intermediate directories). If we run into an
     * error later on, we won't try to clean up the directory, it is considered
     * persistent.
     */
    if (g_mkdir_with_parents(state_dir, S_IRWXU) == -1) {
        g_critical("unable to create (an ancestor of) the state directory"
                   " '%s': %s", state_dir, strerror(errno));
        return EXIT_FAILURE;
    }
#endif

    s = g_malloc0(sizeof(GAState));
    s->log_level = log_level;
    s->log_file = stderr;
#ifdef CONFIG_FSFREEZE
    s->fsfreeze_hook = fsfreeze_hook;
#endif
    g_log_set_default_handler(ga_log, s);
    g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
    ga_enable_logging(s);
    s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
                                                 state_dir);
    s->pstate_filepath = g_strdup_printf("%s/qga.state", state_dir);
    s->frozen = false;

#ifndef _WIN32
    /* check if a previous instance of qemu-ga exited with filesystems' state
     * marked as frozen. this could be a stale value (a non-qemu-ga process
     * or reboot may have since unfrozen them), but better to require an
     * uneeded unfreeze than to risk hanging on start-up
     */
    struct stat st;
    if (stat(s->state_filepath_isfrozen, &st) == -1) {
        /* it's okay if the file doesn't exist, but if we can't access for
         * some other reason, such as permissions, there's a configuration
         * that needs to be addressed. so just bail now before we get into
         * more trouble later
         */
        if (errno != ENOENT) {
            g_critical("unable to access state file at path %s: %s",
                       s->state_filepath_isfrozen, strerror(errno));
            return EXIT_FAILURE;
        }
    } else {
        g_warning("previous instance appears to have exited with frozen"
                  " filesystems. deferring logging/pidfile creation and"
                  " disabling non-fsfreeze-safe commands until"
                  " guest-fsfreeze-thaw is issued, or filesystems are"
                  " manually unfrozen and the file %s is removed",
                  s->state_filepath_isfrozen);
        s->frozen = true;
    }
#endif

    if (ga_is_frozen(s)) {
        if (daemonize) {
            /* delay opening/locking of pidfile till filesystems are unfrozen */
            s->deferred_options.pid_filepath = pid_filepath;
            become_daemon(NULL);
        }
        if (log_filepath) {
            /* delay opening the log file till filesystems are unfrozen */
            s->deferred_options.log_filepath = log_filepath;
        }
        ga_disable_logging(s);
        qmp_for_each_command(ga_disable_non_whitelisted, NULL);
    } else {
        if (daemonize) {
            become_daemon(pid_filepath);
        }
        if (log_filepath) {
            FILE *log_file = ga_open_logfile(log_filepath);
            if (!log_file) {
                g_critical("unable to open specified log file: %s",
                           strerror(errno));
                goto out_bad;
            }
            s->log_file = log_file;
        }
    }

    /* load persistent state from disk */
    if (!read_persistent_state(&s->pstate,
                               s->pstate_filepath,
                               ga_is_frozen(s))) {
        g_critical("failed to load persistent state");
        goto out_bad;
    }

    blacklist = ga_command_blacklist_init(blacklist);
    if (blacklist) {
        s->blacklist = blacklist;
        do {
            g_debug("disabling command: %s", (char *)blacklist->data);
            qmp_disable_command(blacklist->data);
            blacklist = g_list_next(blacklist);
        } while (blacklist);
    }
    s->command_state = ga_command_state_new();
    ga_command_state_init(s, s->command_state);
    ga_command_state_init_all(s->command_state);
    json_message_parser_init(&s->parser, process_event);
    ga_state = s;
#ifndef _WIN32
    if (!register_signal_handlers()) {
        g_critical("failed to register signal handlers");
        goto out_bad;
    }
#endif

    s->main_loop = g_main_loop_new(NULL, false);
    if (!channel_init(ga_state, method, path)) {
        g_critical("failed to initialize guest agent channel");
        goto out_bad;
    }
#ifndef _WIN32
    g_main_loop_run(ga_state->main_loop);
#else
    if (daemonize) {
        SERVICE_TABLE_ENTRY service_table[] = {
            { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
        StartServiceCtrlDispatcher(service_table);
    } else {
        g_main_loop_run(ga_state->main_loop);
    }
#endif

    ga_command_state_cleanup_all(ga_state->command_state);
    ga_channel_free(ga_state->channel);

    if (daemonize) {
        unlink(pid_filepath);
    }
    return 0;

out_bad:
    if (daemonize) {
        unlink(pid_filepath);
    }
    return EXIT_FAILURE;
}
コード例 #25
0
int
main (int argc, char *argv[])
{
  App *app = &s_app;
  GError *error = NULL;
  GstBus *bus;

  gst_init (&argc, &argv);

  GST_DEBUG_CATEGORY_INIT (appsrc_playbin_debug, "appsrc-playbin", 0,
      "appsrc playbin example");

  if (argc < 2) {
    g_print ("usage: %s <filename>\n", argv[0]);
    return -1;
  }

  /* try to open the file as an mmapped file */
  app->file = g_mapped_file_new (argv[1], FALSE, &error);
  if (error) {
    g_print ("failed to open file: %s\n", error->message);
    g_error_free (error);
    return -2;
  }
  /* get some vitals, this will be used to read data from the mmapped file and
   * feed it to appsrc. */
  app->length = g_mapped_file_get_length (app->file);
  app->data = (guint8 *) g_mapped_file_get_contents (app->file);
  app->offset = 0;

  /* create a mainloop to get messages */
  app->loop = g_main_loop_new (NULL, TRUE);

  app->playbin = gst_element_factory_make ("playbin2", NULL);
  g_assert (app->playbin);

  bus = gst_pipeline_get_bus (GST_PIPELINE (app->playbin));

  /* add watch for messages */
  gst_bus_add_watch (bus, (GstBusFunc) bus_message, app);

  /* set to read from appsrc */
  g_object_set (app->playbin, "uri", "appsrc://", NULL);

  /* get notification when the source is created so that we get a handle to it
   * and can configure it */
  g_signal_connect (app->playbin, "deep-notify::source",
      (GCallback) found_source, app);

  /* go to playing and wait in a mainloop. */
  gst_element_set_state (app->playbin, GST_STATE_PLAYING);

  /* this mainloop is stopped when we receive an error or EOS */
  g_main_loop_run (app->loop);

  GST_DEBUG ("stopping");

  gst_element_set_state (app->playbin, GST_STATE_NULL);

  /* free the file */
  g_mapped_file_free (app->file);

  gst_object_unref (bus);
  g_main_loop_unref (app->loop);

  return 0;
}
コード例 #26
0
ファイル: nullclient.c プロジェクト: adderly/cmoon
int main(int argc, char *argv[])
{
	GList *iter;
	int i, num;
	GList *names = NULL;
	const char *prpl;
	char name[128];
	char *password;
	GMainLoop *loop = g_main_loop_new(NULL, FALSE);
	PurpleAccount *account;
	PurpleSavedStatus *status;
	char *res;

	/* libpurple's built-in DNS resolution forks processes to perform
	 * blocking lookups without blocking the main process.  It does not
	 * handle SIGCHLD itself, so if the UI does not you quickly get an army
	 * of zombie subprocesses marching around.
	 */
	signal(SIGCHLD, SIG_IGN);

    if (argc > 1) {
        if (!strcmp(argv[1], "1")) {
            g_debug = 1;
        }
    }

	init_libpurple();

	printf("libpurple initialized.\n");

	iter = purple_plugins_get_protocols();
	for (i = 0; iter; iter = iter->next) {
		PurplePlugin *plugin = iter->data;
		PurplePluginInfo *info = plugin->info;
		if (info && info->name) {
			printf("\t%d: %s\n", i++, info->name);
			names = g_list_append(names, info->id);
		}
	}
	printf("Select the protocol [0-%d]: ", i-1);
	res = fgets(name, sizeof(name), stdin);
	if (!res) {
		fprintf(stderr, "Failed to gets protocol selection.");
		abort();
	}
	sscanf(name, "%d", &num);
	prpl = g_list_nth_data(names, num);

	printf("Username: "******"Failed to read user name.");
		abort();
	}
	name[strlen(name) - 1] = 0;  /* strip the \n at the end */

	/* Create the account */
	account = purple_account_new(name, prpl);

	/* Get the password for the account */
	password = getpass("Password: ");
	purple_account_set_password(account, password);

	/* It's necessary to enable the account first. */
	purple_account_set_enabled(account, UI_ID, TRUE);

	/* Now, to connect the account(s), create a status and activate it. */
	status = purple_savedstatus_new(NULL, PURPLE_STATUS_AVAILABLE);
	purple_savedstatus_activate(status);

	null_signals_connect();

	g_main_loop_run(loop);

	return 0;
}
コード例 #27
0
ファイル: gstapi.cpp プロジェクト: PeterXu/gst-mobile
int ogg_player (const char *location) {

    GMainLoop *loop;
    GstElement *pipeline, *source, *demuxer, *decoder, *conv, *sink;
    GstBus *bus;
    guint bus_watch_id;

    /* Initialisation */
    loop = g_main_loop_new (NULL, FALSE);

    /* Create gstreamer elements */
    pipeline = gst_pipeline_new ("audio-player");
    source   = gst_element_factory_make ("filesrc",       "file-source");
    returnv_assert(source, -1);
    demuxer  = gst_element_factory_make ("oggdemux",      "ogg-demuxer");
    returnv_assert(demuxer, -1);
    decoder  = gst_element_factory_make ("vorbisdec",     "vorbis-decoder");
    returnv_assert(decoder, -1);
    conv     = gst_element_factory_make ("audioconvert",  "converter");
    returnv_assert(conv, -1);
    sink     = gst_element_factory_make ("autoaudiosink", "audio-output");
    returnv_assert(sink, -1);

    if (!pipeline || !source || !demuxer || !decoder || !conv || !sink) {
        g_printerr ("One element could not be created. Exiting.\n");
        return -1;
    }

    /* Set up the pipeline */

    /* we set the input filename to the source element */
    g_object_set (G_OBJECT (source), "location", location, NULL);

    /* we add a message handler */
    bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
    returnv_assert(bus, -1);
    bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
    gst_object_unref (bus);

    /* we add all elements into the pipeline */
    /* file-source | ogg-demuxer | vorbis-decoder | converter | alsa-output */
    gst_bin_add_many (GST_BIN (pipeline), source, demuxer, decoder, conv, sink, NULL);

    /* we link the elements together */
    /* file-source -> ogg-demuxer ~> vorbis-decoder -> converter -> alsa-output */
    gst_element_link (source, demuxer);
    gst_element_link_many (decoder, conv, sink, NULL);
    g_signal_connect (demuxer, "pad-added", G_CALLBACK (on_pad_added), decoder);

    /* note that the demuxer will be linked to the decoder dynamically.
       The reason is that Ogg may contain various streams (for example
       audio and video). The source pad(s) will be created at run time,
       by the demuxer when it detects the amount and nature of streams.
       Therefore we connect a callback function which will be executed
       when the "pad-added" is emitted.*/

    /* Set the pipeline to "playing" state*/
    g_print ("Now playing: %s\n", location);
    gst_element_set_state (pipeline, GST_STATE_PLAYING);

    /* Iterate */
    g_print ("Running...\n");
    g_main_loop_run (loop);

    /* Out of the main loop, clean up nicely */
    g_print ("Returned, stopping playback\n");
    gst_element_set_state (pipeline, GST_STATE_NULL);

    g_print ("Deleting pipeline\n");
    gst_object_unref (GST_OBJECT (pipeline));
    g_source_remove (bus_watch_id);
    g_main_loop_unref (loop);

    return 0;
}
コード例 #28
0
ファイル: light-client.c プロジェクト: ZachGoldberg/gupnp-gi
int
main (int argc, char **argv)
{
  GError *error = NULL;
  GUPnPContext *context;
  GUPnPControlPoint *cp;

  g_thread_init (NULL);
  g_type_init ();

  /* Check and parse command line arguments */
  if (argc != 2) {
    usage ();
    return EXIT_FAILURE;
  }
  
  if (g_str_equal (argv[1], "on")) {
    mode = ON;
  } else if (g_str_equal (argv[1], "off")) {
    mode = OFF;
  } else if (g_str_equal (argv[1], "toggle")) {
    mode = TOGGLE;
  } else {
    usage ();
    return EXIT_FAILURE;
  }

  /* Create the UPnP context */
  context = gupnp_context_new (NULL, NULL, 0, &error);
  if (error) {
    g_printerr ("Error creating the GUPnP context: %s\n",
		error->message);
    g_error_free (error);

    return EXIT_FAILURE;
  }

  /* Create the control point, searching for SwitchPower services */
  cp = gupnp_control_point_new (context,
				"urn:schemas-upnp-org:service:SwitchPower:1");
  
  /* Connect to the service-found callback */
  g_signal_connect (cp,
                    "service-proxy-available",
                    G_CALLBACK (service_proxy_available_cb),
                    NULL);
  
  /* Start searching when the main loop runs */
  gssdp_resource_browser_set_active (GSSDP_RESOURCE_BROWSER (cp), TRUE);

  /* Run the main loop */
  main_loop = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (main_loop);

  /* Cleanup */
  g_main_loop_unref (main_loop);
  g_object_unref (cp);
  g_object_unref (context);
  
  return EXIT_SUCCESS;
}
コード例 #29
0
int
main (int argc, char **argv)
{
  GError *err = NULL;
  GstDiscoverer *dc;
  gint timeout = 10;
  GOptionEntry options[] = {
    {"async", 'a', 0, G_OPTION_ARG_NONE, &async,
        "Run asynchronously", NULL},
    {"timeout", 't', 0, G_OPTION_ARG_INT, &timeout,
        "Specify timeout (in seconds, default 10)", "T"},
    /* {"elem", 'e', 0, G_OPTION_ARG_NONE, &elem_seek, */
    /*     "Seek on elements instead of pads", NULL}, */
    {"toc", 'c', 0, G_OPTION_ARG_NONE, &show_toc,
        "Output TOC (chapters and editions)", NULL},
    {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
        "Verbose properties", NULL},
    {NULL}
  };
  GOptionContext *ctx;

  ctx =
      g_option_context_new
      ("- discover files synchronously with GstDiscoverer");
  g_option_context_add_main_entries (ctx, options, NULL);
  g_option_context_add_group (ctx, gst_init_get_option_group ());

  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", err->message);
    exit (1);
  }

  g_option_context_free (ctx);

  if (argc < 2) {
    g_print ("usage: %s <uris>\n", argv[0]);
    exit (-1);
  }

  dc = gst_discoverer_new (timeout * GST_SECOND, &err);
  if (G_UNLIKELY (dc == NULL)) {
    g_print ("Error initializing: %s\n", err->message);
    exit (1);
  }

  if (async == FALSE) {
    gint i;
    for (i = 1; i < argc; i++)
      process_file (dc, argv[i]);
  } else {
    PrivStruct *ps = g_new0 (PrivStruct, 1);
    GMainLoop *ml = g_main_loop_new (NULL, FALSE);

    ps->dc = dc;
    ps->argc = argc;
    ps->argv = argv;

    /* adding uris will be started when the mainloop runs */
    g_idle_add ((GSourceFunc) _run_async, ps);

    /* connect signals */
    g_signal_connect (dc, "discovered", G_CALLBACK (_new_discovered_uri), NULL);
    g_signal_connect (dc, "finished", G_CALLBACK (_discoverer_finished), ml);

    gst_discoverer_start (dc);
    /* run mainloop */
    g_main_loop_run (ml);

    gst_discoverer_stop (dc);
    g_free (ps);
    g_main_loop_unref (ml);
  }
  g_object_unref (dc);

  return 0;
}
コード例 #30
0
ファイル: gsmsendrecv.c プロジェクト: ChinnaSuhas/ossbuild
int 
main (int   argc,
      char *argv[]) 
{
  GstElement *bin, *rtpbin, *encoder, *payloader, *decoder, *depayloader;
  GMainLoop *loop;
  gst_init (&argc, &argv);
  guint32 pt = 3;  /* PT=3 => GSM */
  char destination[DEST_MAXSIZE];
  int port, rtp_sockfd, rtcp_sockfd = -1;
  struct sockaddr_in rtp_addr;
  GstCaps *caps;
  GHashTable *pt_map = g_hash_table_new_full (g_direct_hash,
					      g_direct_equal,
					      NULL,
					      (GDestroyNotify) gst_caps_unref);

  /* initialize the PT<->caps hash table */
  caps = gst_caps_new_simple ("application/x-rtp",
      "clock-rate", G_TYPE_INT, 8000, NULL);
  g_hash_table_insert (pt_map, GINT_TO_POINTER(pt), (gpointer) caps);

  loop = g_main_loop_new(NULL, FALSE);

  if (argc != 3)
  {
      printf("Usage : gsmsendrecv <host> <port>\n");
      return 0;
  }

  /* set the local port */
  port = atoi (argv[2]);

  /* create and bind a socket for RTP and RTCP */
  memset(&rtp_addr, 0, sizeof(struct sockaddr_in));
  rtp_sockfd = socket (AF_INET, SOCK_DGRAM, 0);
  rtcp_sockfd = socket (AF_INET, SOCK_DGRAM, 0);
  if (rtp_sockfd > 0 && rtcp_sockfd > 0) {
    int res;
    rtp_addr.sin_family = AF_INET;
    rtp_addr.sin_port = htons (port);
    rtp_addr.sin_addr.s_addr = INADDR_ANY;

    res = bind(rtp_sockfd, (struct sockaddr*)&rtp_addr, sizeof(rtp_addr));
    if (res == 0) {
      fprintf(stderr, "Succesfully bound to local RTP port %d.\n", port);
    } else {
      fprintf(stderr, "Unable to bind to local RTP port %d.\n", port);
      rtp_sockfd = -1;
    }

    memset(&rtp_addr, 0, sizeof(struct sockaddr_in));
    rtp_addr.sin_family = AF_INET;
    rtp_addr.sin_port = htons (port + 1);
    rtp_addr.sin_addr.s_addr = INADDR_ANY;
    res = bind(rtcp_sockfd, (struct sockaddr*)&rtp_addr, sizeof(rtp_addr));
    if (res == 0) {
      fprintf(stderr, "Succesfully bound to local RTCP port %d.\n", port + 1);
    } else {
      fprintf(stderr, "Unable to bind to local RTCP port %d.\n", port + 1);
      rtcp_sockfd = -1;
    }
  }

  bin = gst_pipeline_new("pipe");
  fprintf(stderr,"bin: %p\n",bin);  
  
  // first we create our rtpbin object
  rtpbin = gst_element_factory_make("rtpbin", "rtpbin");
  fprintf(stderr,"rtpbin: %p\n",rtpbin);  
  snprintf(destination, DEST_MAXSIZE, "%s:%s", argv[1], argv[2]);
  g_object_set(G_OBJECT(rtpbin), "destinations", destination, NULL);
  g_object_set(G_OBJECT(rtpbin), "rtcp-support", TRUE, NULL);
  g_object_set(G_OBJECT(rtpbin), "localport", port, NULL);
  g_object_set(G_OBJECT(rtpbin), "pt-map", pt_map, NULL);
  if (rtp_sockfd != -1)
    g_object_set(G_OBJECT(rtpbin), "rtp_sockfd", rtp_sockfd, NULL);
  if (rtcp_sockfd != -1)
    g_object_set(G_OBJECT(rtpbin), "rtcp_sockfd", rtcp_sockfd, NULL);
  
  // then our encoder/payloader
  encoder = gst_element_factory_make("gsmenc", "gsmenc");
  payloader = gst_element_factory_make("rtpgsmpay", "rtpgsmpay");

  // add both to the piepline and link them
  gst_bin_add_many(GST_BIN(bin), rtpbin, encoder, payloader, NULL);
  gst_element_link_pads(encoder, "src", payloader, "sink");
  gst_element_link_pads(payloader, "src", rtpbin, "sink%d");

  // our test src and link it to the encoder
  GstElement *testsrc = gst_element_factory_make("alsasrc", "alsasrc");
  g_object_set(G_OBJECT(testsrc), "blocksize", 320, NULL);
  gst_bin_add_many(GST_BIN(bin), testsrc, NULL);
  gst_element_link_pads(testsrc, "src", encoder, "sink");

  // decoder and depayloader
  decoder = gst_element_factory_make("gsmdec", "gsmdec");
  depayloader = gst_element_factory_make("rtpgsmdepay", "rtpgsmdepay");
  if (!decoder) {
      printf("unable to create a gsmdec.\n");
      exit(1);
  }  
  if (!depayloader) {
      printf("unable to create a rtpgsmdepay.\n");
      exit(1);
  }  
  g_object_set(G_OBJECT(depayloader), "queue-delay", 0, NULL);

  // add receive elements to the pipeline and link them
  gst_bin_add_many(GST_BIN(bin), decoder, depayloader, NULL);
  gst_element_link_pads(rtpbin, "src%d", depayloader, "sink");
  gst_element_link_pads(depayloader, "src", decoder, "sink");

  // our alsasink and link it to the encoder
  GstElement *testsink = gst_element_factory_make("alsasink", "alsasink");
  g_object_set(G_OBJECT(testsink), "sync", TRUE, NULL);
  gst_bin_add_many(GST_BIN(bin), testsink, NULL);
  gst_element_link_pads(decoder, "src", testsink , "sink");

  // let's start playing
  gst_element_set_state (bin, GST_STATE_PLAYING);

  //gst_debug_set_threshold_for_name ("rtpbin", 1);
  //gst_debug_set_threshold_for_name ("rtpsend", 5);
  //gst_debug_set_threshold_for_name ("*pad*", 5);

  g_main_loop_run(loop);

  return 0;
}