コード例 #1
0
ファイル: ws.c プロジェクト: davehorton/sofia-sip
ssize_t ws_raw_read(wsh_t *wsh, void *data, size_t bytes, int block)
{
	ssize_t r;
	int err = 0;

	wsh->x++;
	if (wsh->x > 250) ms_sleep(1);

	if (wsh->ssl) {
		do {
			r = SSL_read(wsh->ssl, data, bytes);

			if (r == -1) {
				err = SSL_get_error(wsh->ssl, r);
				
				if (!block && err == SSL_ERROR_WANT_READ) {
					r = -2;
					goto end;
				}

				if (block) {
					wsh->x++;
					ms_sleep(10);
				}
			}

		} while (r == -1 && err == SSL_ERROR_WANT_READ && wsh->x < 100);

		goto end;
	}

	do {

		r = recv(wsh->sock, data, bytes, 0);

		if (r == -1) {
			if (!block && xp_is_blocking(xp_errno())) {
				r = -2;
				goto end;
			}

			if (block) {
				wsh->x++;
				ms_sleep(10);
			}
		}
	} while (r == -1 && xp_is_blocking(xp_errno()) && wsh->x < 100);
	
	if (wsh->x >= 1000 || (block && wsh->x >= 100)) {
		r = -1;
	}

 end:

	if (r > 0) {
		*((char *)data + r) = '\0';
	}

	if (r >= 0) {
		wsh->x = 0;
	}
	
	return r;
}
コード例 #2
0
int main(int argc, char **argv)
{
	ll_init_apr();

	// Set up llerror logging 
	{
		LLError::initForApplication(".");
		LLError::setDefaultLevel(LLError::LEVEL_INFO);
	}
	
	std::string launcher_name;
	std::string plugin_name;

	if(argc >= 3)
	{
		launcher_name = argv[1];
		plugin_name = argv[2];
	}
	else
	{
#if LL_DARWIN
		// hardcoding the testbed arguments by default
		launcher_name = "plugin_process_host";
		plugin_name = "libdemo_plugin.dylib";
#elif LL_WINDOWS
		// hardcoding the testbed arguments by default
		launcher_name = "plugin_process_host.exe";
		plugin_name = "demo_plugin.dll";
#else
		LL_ERRS("plugin_process_launcher") << "usage: " << argv[0] << " launcher_filename plugin_filename" << LL_ENDL;
#endif
	}

	PluginProcessLauncherMessageReceiver receiver;
	
	gServicePump = new LLPumpIO(gAPRPoolp);
	gServicePump->prime(gAPRPoolp);

	gPlugin = new LLPluginProcessParent(gServicePump, &receiver);

	State state = STATE_STARTUP;
	while(state != STATE_DONE)
	{
		switch(state)
		{
			case STATE_STARTUP:
				LL_INFOS("plugin_process_launcher") << "startup" << LL_ENDL;
				gPlugin->init(launcher_name, plugin_name);
				state = STATE_ADD_MEMORY;
			break;
			
			case STATE_ADD_MEMORY:
				if(gPlugin->isRunning())
				{
					LL_INFOS("plugin_process_launcher") << "adding shared memory" << LL_ENDL;
					gPlugin->addSharedMemory(SHARED_MEMORY_SIZE);
					state = STATE_RUNNING;
				}
			break;
			
			case STATE_RUNNING:
			{
				volatile unsigned char *addr = (unsigned char*)gPlugin->getSharedMemoryAddress(SHARED_MEMORY_NAME);
				if(addr != NULL)
				{
					int val = (int)(addr[0]);
					if(val >= 16)
					{
						state = STATE_REMOVE_MEMORY;
					}
					else
					{
						LL_INFOS("plugin_process_launcher") << "running, value from shared memory is " << val << LL_ENDL;
					}
				}
			}
			break;
			
			case STATE_REMOVE_MEMORY:
				LL_INFOS("plugin_process_launcher") << "removing shared memory" << LL_ENDL;
				gPlugin->removeSharedMemory(SHARED_MEMORY_NAME);
				state = STATE_SHUTDOWN;
			break;
			
			case STATE_SHUTDOWN:
			{
				volatile unsigned char *addr = (unsigned char*)gPlugin->getSharedMemoryAddress(SHARED_MEMORY_NAME);
				if(addr == NULL)
				{
					LL_INFOS("plugin_process_launcher") << "sending shutdown request" << LL_ENDL;
					gPlugin->shutdownRequest();
					state = STATE_CLEANUP;
				}
			}
			break;
			
			case STATE_CLEANUP:
				if(gPlugin->isDone())
				{
					LL_INFOS("plugin_process_launcher") << "plugin is done" << LL_ENDL;
					state = STATE_DONE;
				}
			break;
			
			case STATE_DONE:
				// should never reach here -- the while() should exit first.
			break;
		}
		
		// Do this every time through the loop
		if(state != STATE_DONE)
		{
			gServicePump->pump();
			gServicePump->callback();
			gPlugin->idle();
			ms_sleep(100);
		}
	}

	delete gPlugin;
	
	ll_cleanup_apr();
	
}
コード例 #3
0
ファイル: main.c プロジェクト: 4hmedSamir/headunit
gboolean commander_poll_event(gpointer data)
{	
	return TRUE;
	
	const struct timespec timeout = { .tv_sec = 0, .tv_nsec = 10000};
	
	struct input_event event[64];
	const size_t ev_size = sizeof(struct input_event);
	const size_t buffer_size = ev_size * 64;
	ssize_t size;
	gst_app_t *app = (gst_app_t *)data;
	struct timespec tp;
	uint8_t *cmd_buf = NULL;
	int cmd_size = 0; 

	sigset_t sigmask;
	struct pollfd fds[1];
	int ret;
	unsigned char* buf = 0;
	int len;

	sigemptyset(&sigmask);

	fds[0].events = POLLIN;
    fds[0].fd = mCommander.fd;
    
    fds[0].revents = 0;

	ret = ppoll(fds, sizeof(fds) / sizeof(struct pollfd), &timeout, &sigmask);

	if (fds[0].revents & POLLIN) {

		size = read(mCommander.fd, &event, buffer_size);
		
		if (size == 0 || size == -1)
			return FALSE;
		
		if (size < ev_size) {
			printf("Error size when reading\n");
			g_main_loop_quit(app->loop);
			return FALSE;
		}
		
		int num_chars = size / ev_size;
		
		int i;
		
		
		for (i=0;i < num_chars;i++) {			
			if (event[i].type == EV_KEY && event[i].value == 1) {
				
				switch (event[i].code) {
					case KEY_UP:
						cmd_buf = cd_up1;
						cmd_size = sizeof(cd_up1);
						break;
							
					case KEY_DOWN:
						cmd_buf = cd_down1;
						cmd_size = sizeof(cd_down1);
						break;
										
					case KEY_LEFT:
						cmd_buf = cd_left1;
						cmd_size = sizeof(cd_left1);
						break;
						
					case KEY_RIGHT:
						cmd_buf = cd_right1;
						cmd_size = sizeof(cd_right1);
						break;
						
					case KEY_N:
						cmd_buf = cd_lefturn;
						cmd_size = sizeof(cd_lefturn);
						break;
						
					case KEY_M:
						cmd_buf = cd_rightturn;
						cmd_size = sizeof(cd_rightturn);
						break;

					case KEY_ENTER:
						cmd_buf = cd_enter1;
						cmd_size = sizeof(cd_enter1);
						break;

					case KEY_BACKSPACE:
						cmd_buf = cd_back1;
						cmd_size = sizeof(cd_back1);
						break;
				}
				
				if (cmd_buf != NULL) {
					clock_gettime(CLOCK_REALTIME, &tp);
					
					uint8_t *buf = (uint8_t *)malloc(cmd_size);

					memcpy(buf, cmd_buf, cmd_size);

					varint_encode(tp.tv_sec * 1000000000 +tp.tv_nsec, buf,3);

					printf("\n { ");
			
					for (i = 0; i < cmd_size; i++)
					{
						
						if (i > 0) printf(",");
						printf("0x%02X", (char) buf[i]);
					}
					
					printf(" } \n");

									
					queueSend(0,AA_CH_TOU, buf, cmd_size, TRUE);
					
				}
				
			}
				
			if (event[i].type == EV_KEY && event[i].value == 0) {
				cmd_buf = NULL;
				
				switch (event[i].code) {
					case KEY_UP:
						cmd_buf = cd_up2;
						cmd_size = sizeof(cd_up2);
						break;
							
					case KEY_DOWN:
						cmd_buf = cd_down2;
						cmd_size = sizeof(cd_down2);
						break;
										
					case KEY_LEFT:
						cmd_buf = cd_left2;
						cmd_size = sizeof(cd_left2);
						break;
						
					case KEY_RIGHT:
						cmd_buf = cd_right2;
						cmd_size = sizeof(cd_right2);
						break;

					case KEY_ENTER:
						cmd_buf = cd_enter2;
						cmd_size = sizeof(cd_enter2);
						break;

					case KEY_BACKSPACE:
						cmd_buf = cd_back2;
						cmd_size = sizeof(cd_back2);
						break;
				}
				
				if (cmd_buf != NULL) {
					clock_gettime(CLOCK_REALTIME, &tp);
					uint8_t *buf = (uint8_t *)malloc(cmd_size);

					memcpy(buf, cmd_buf, cmd_size);

					printf("\n { ");
			
					for (i = 0; i < cmd_size; i++)
					{
						
						if (i > 0) printf(",");
						printf("0x%02X", (char) buf[i]);
					}
					
					printf(" } \n");

					varint_encode(tp.tv_sec * 100000000 +tp.tv_nsec, buf,3);
					
					queueSend(0,AA_CH_TOU, buf, cmd_size, TRUE);
				}
			}
		}
	}
	
	return TRUE;
}


static void * input_thread(void *app) {
	
	while (touch_poll_event(app)) {
		commander_poll_event(app);		
		ms_sleep(100);
	}
}

GMainLoop *mainloop;

#define HMI_BUS_ADDRESS "unix:path=/tmp/dbus_hmi_socket"

 
static void * nightmode_thread(void *app) 
{

	// Initialize HMI bus
	DBusConnection *hmi_bus;
	DBusError error;

	hmi_bus = dbus_connection_open(HMI_BUS_ADDRESS, &error);

	if (!hmi_bus) {
		printf("DBUS: failed to connect to HMI bus: %s: %s\n", error.name, error.message);
	}

	if (!dbus_bus_register(hmi_bus, &error)) {
		printf("DBUS: failed to register with HMI bus: %s: %s\n", error.name, error.message);
	}

	// Wait for mainloop to start
	ms_sleep(100);
		
	while (g_main_loop_is_running (mainloop)) {
		
		DBusMessage *msg = dbus_message_new_method_call("com.jci.BLM_TIME", "/com/jci/BLM_TIME", "com.jci.BLM_TIME", "GetClock");
		DBusPendingCall *pending = NULL;

		if (!msg) {
			printf("DBUS: failed to create message \n");
		}

		if (!dbus_connection_send_with_reply(hmi_bus, msg, &pending, -1)) {
			printf("DBUS: failed to send message \n");
		}

		dbus_connection_flush(hmi_bus);
		dbus_message_unref(msg);

		dbus_pending_call_block(pending);
		msg = dbus_pending_call_steal_reply(pending);
		if (!msg) {
		   printf("DBUS: received null reply \n");
		}

		dbus_uint32_t nm_hour;
		dbus_uint32_t nm_min;
		dbus_uint32_t nm_timestamp;
		dbus_uint64_t nm_calltimestamp;
		if (!dbus_message_get_args(msg, &error, DBUS_TYPE_UINT32, &nm_hour,
											  DBUS_TYPE_UINT32, &nm_min,
											  DBUS_TYPE_UINT32, &nm_timestamp,
											  DBUS_TYPE_UINT64, &nm_calltimestamp,
											  DBUS_TYPE_INVALID)) {
			printf("DBUS: failed to get result %s: %s\n", error.name, error.message);
		}
		
		dbus_message_unref(msg);
		
		int nightmodenow = 1;

		if (nm_hour >= 6 && nm_hour <= 18)
			nightmodenow = 0;

		if (nightmode != nightmodenow) {
			nightmode = nightmodenow;
			byte* rspds = malloc(sizeof(byte) * 6);
			rspds[0] = -128; 
			rspds[1] = 0x03;
		   	rspds[2] = 0x52; 
			rspds[3] = 0x02;
		   	rspds[4] = 0x08;
			if (nightmode == 0)
				rspds[5]= 0x00;
			else
				rspds[5] = 0x01;
			
			queueSend(0,AA_CH_SEN, rspds, sizeof (byte) * 6, TRUE); 	// Send Sensor Night mode
		}
		
		sleep(600);		
	}
}
コード例 #4
0
ファイル: hu_ush.c プロジェクト: Entropy512/headunit
 void send_string (struct usb_device * device, int index, const char * string) {
   usb_device_control_transfer (device, USB_DIR_OUT | USB_TYPE_VENDOR, ACC_REQ_SEND_STRING, 0, index, (void *) string, strlen (string) + 1, 0);
   ms_sleep (10);                                                      // Some devices can't handle back-to-back requests, so delay a bit
 }
コード例 #5
0
bool LLPluginMessagePipe::pumpInput(F64 timeout)
{
	bool result = true;

	if(mSocket)
	{
		apr_status_t status;
		apr_size_t size;

		// FIXME: For some reason, the apr timeout stuff isn't working properly on windows.
		// Until such time as we figure out why, don't try to use the socket timeout -- just sleep here instead.
#if LL_WINDOWS
		if(result)
		{
			if(timeout != 0.0f)
			{
				ms_sleep((int)(timeout * 1000.0f));
				timeout = 0.0f;
			}
		}
#endif
		
		// Check for incoming messages
		if(result)
		{
			char input_buf[1024];
			apr_size_t request_size;
			
			if(timeout == 0.0f)
			{
				// If we have no timeout, start out with a full read.
				request_size = sizeof(input_buf);
			}
			else
			{
				// Start out by reading one byte, so that any data received will wake us up.
				request_size = 1;
			}
			
			// and use the timeout so we'll sleep if no data is available.
			setSocketTimeout((apr_interval_time_t)(timeout * 1000000));

			while(1)		
			{
				size = request_size;

//				LL_INFOS("Plugin") << "before apr_socket_recv, size = " << size << LL_ENDL;

				status = apr_socket_recv(
						mSocket->getSocket(), 
						input_buf, 
						&size);

//				LL_INFOS("Plugin") << "after apr_socket_recv, size = " << size << LL_ENDL;
				
				if(size > 0)
				{
					LLMutexLock lock(&mInputMutex);
					mInput.append(input_buf, size);
				}

				if(status == APR_SUCCESS)
				{
					LL_DEBUGS("PluginSocket") << "success, read " << size << LL_ENDL;

					if(size != request_size)
					{
						// This was a short read, so we're done.
						break;
					}
				}
				else if(APR_STATUS_IS_TIMEUP(status))
				{
					LL_DEBUGS("PluginSocket") << "TIMEUP, read " << size << LL_ENDL;

					// Timeout was hit.  Since the initial read is 1 byte, this should never be a partial read.
					break;
				}
				else if(APR_STATUS_IS_EAGAIN(status))
				{
					LL_DEBUGS("PluginSocket") << "EAGAIN, read " << size << LL_ENDL;

					// Non-blocking read returned immediately.
					break;
				}
				else if(APR_STATUS_IS_EOF(status))
				{
					// This is what we normally expect when a plugin exits.
					LL_INFOS("PluginSocket") << "Got EOF from plugin socket. " << LL_ENDL;

					if(mOwner)
					{
						mOwner->socketError(status);
					}
					result = false;
					break;
				}
				else
				{
					// some other error
					// Treat this as fatal.
					ll_apr_warn_status(status);

					if(mOwner)
					{
						mOwner->socketError(status);
					}
					result = false;
					break;
				}

				if(timeout != 0.0f)
				{
					// Second and subsequent reads should not use the timeout
					setSocketTimeout(0);
					// and should try to fill the input buffer
					request_size = sizeof(input_buf);
				}
			}
			
			processInput();
		}
	}
	
	return result;	
}
コード例 #6
0
ファイル: hu_usb.c プロジェクト: tdassonville/headunit
  int hu_usb_start (byte ep_in_addr, byte ep_out_addr) {
    int ret = 0;

    if (iusb_state == hu_STATE_STARTED) {
      logd ("CHECK: iusb_state: %d (%s)", iusb_state, state_get (iusb_state));
      return (0);
    }

    //#include <sys/prctl.h>
    //ret = prctl (PR_GET_DUMPABLE, 1, 0, 0, 0);  // 1 = SUID_DUMP_USER
    //logd ("prctl ret: %d", ret);

    iusb_state = hu_STATE_STARTIN;
    logd ("  SET: iusb_state: %d (%s)", iusb_state, state_get (iusb_state));

    iusb_best_vendor = 0;
    int tries = 0;
    while (iusb_best_vendor != USB_VID_GOO && tries ++ < 4) { //2000) {

      ret = iusb_init (ep_in_addr, ep_out_addr);
      if (ret < 0) {
        loge ("Error iusb_init");
        iusb_deinit ();
        iusb_state = hu_STATE_STOPPED;
        logd ("  SET: iusb_state: %d (%s)", iusb_state, state_get (iusb_state));
        return (-1);
      }
      logd ("OK iusb_init");

      if (iusb_best_vendor == USB_VID_GOO) {
        logd ("Already OAP/AA mode, no need to call iusb_oap_start()");

        iusb_state = hu_STATE_STARTED;
        logd ("  SET: iusb_state: %d (%s)", iusb_state, state_get (iusb_state));
        return (0);
      }

      ret = iusb_oap_start ();
      if (ret < 0) {
        loge ("Error iusb_oap_start");
        iusb_deinit ();
        iusb_state = hu_STATE_STOPPED;
        logd ("  SET: iusb_state: %d (%s)", iusb_state, state_get (iusb_state));
        return (-2);
      }
      logd ("OK iusb_oap_start");

      if (iusb_best_vendor != USB_VID_GOO) {
        iusb_deinit ();
        ms_sleep (4000);//!!!!!!!!!!!!!!      (1000);                                                // 600 ms not enough; 700 seems OK
        logd ("Done iusb_best_vendor != USB_VID_GOO ms_sleep()");
      }
      else
        logd ("Done iusb_best_vendor == USB_VID_GOO");
    }

    if (iusb_best_vendor != USB_VID_GOO) {
      loge ("No Google AA/Accessory mode iusb_best_vendor: 0x%x", iusb_best_vendor);
      iusb_deinit ();
      iusb_state = hu_STATE_STOPPED;
      logd ("  SET: iusb_state: %d (%s)", iusb_state, state_get (iusb_state));
      return (-3);
    }

    iusb_state = hu_STATE_STARTED;
    logd ("  SET: iusb_state: %d (%s)", iusb_state, state_get (iusb_state));
    return (0);
  }
コード例 #7
0
ファイル: hu_jni.c プロジェクト: FrankZZ/headunit
  int jni_aa_cmd (int cmd_len, char * cmd_buf, int res_max, char * res_buf) {
    if (ena_log_extra || cmd_len >= 1)
      logd ("cmd_len: %d  cmd_buf %p  res_max: %d  res_buf: %p", cmd_len, cmd_buf, res_max, res_buf);
    int res_len = 0;
    int ret = 0;


    int vid_bufs = vid_buf_buf_tail - vid_buf_buf_head;
    int aud_bufs = vid_buf_buf_tail - vid_buf_buf_head;


    if (cmd_buf != NULL && cmd_len == 3 && cmd_buf [0] == 121) {        // If onCreate() hu_tra:transport_start()
      byte ep_in_addr  = cmd_buf [1];
      byte ep_out_addr = cmd_buf [2];                                   // Get endpoints passed

      ret = hu_aap_start (ep_in_addr, ep_out_addr);                     // Start USB/ACC/OAP, AA Protocol

      aap_state_starts ++;                                              // Count error starts too
      if (ret == 0) {
        logd ("hu_aap_start() success aap_state_starts: %d", aap_state_starts);
      }
      else {
        loge ("hu_aap_start() error aap_state_starts: %d", aap_state_starts);
        aap_state_start_error = 1;
        return (-1);
      }
    }

/* Functions                code                            Params:
    Transport Start         hu_aap_start()                  USB EPs
    Poll/Handle 1 Rcv Msg   hu_aap_recv_process()           -
    Send:
      Send Mic              hu_aap_enc_send()               mic data
      Send Touch            hu_aap_enc_send()               touch data
      Send Ctrl             hu_aap_enc_send()/hu_aap_stop() ctrl data

  Returns:
    Audio Mic Start/Stop
    Audio Out Start/Stop
    Video
    Audio
*/
    else if (cmd_buf != NULL && cmd_len >= 4) {                         // If encrypted command to send...
      int chan = 0;//cmd_buf [0];

      if (cmd_len > 63)                                                 // If Microphone audio...
        chan = AA_CH_MIC;
      else if (cmd_len > 6 && cmd_buf [4] == 0x80 && cmd_buf [5] == 1)  // If Touch event...
        chan = AA_CH_TOU;
      else                                                              // If Byebye or other control packet...
        chan = AA_CH_CTR;
      if (chan != cmd_buf [0]) {
        loge ("chan: %d != cmd_buf[0]: %d", chan, cmd_buf [0]);
        chan = cmd_buf [0];
      }

      //hex_dump ("JNITX: ", 16, cmd_buf, cmd_len);

      ret = hu_aap_enc_send (chan, & cmd_buf [4], cmd_len - 4);         // Send

      if (cmd_buf != NULL && cmd_len  >= 8 && cmd_buf [5] == 15) {      // If byebye...
        logd ("Byebye");
        ms_sleep (100);
        ret = hu_aap_stop ();
      }

    }
    else {
      if (vid_bufs > 0 || aud_bufs > 0)                                 // If any queue audio or video...
        ret = 0;                                                        // Do nothing (don't wait for recv iaap_tra_recv_tmo)
      else
        ret = hu_aap_recv_process ();                                   // Else Process 1 message w/ iaap_tra_recv_tmo
    }
    if (ret < 0) {
      return (ret);                                                     // If error then done w/ error
    }

    if (vid_bufs <= 0 && aud_bufs <= 0) {                               // If no queued audio or video...
      ret = hu_aap_mic_get ();
      if (ret >= 1) {// && ret <= 2) {                                  // If microphone start (2) or stop (1)...
        return (ret);                                                   // Done w/ mic notification: start (2) or stop (1)
      }
                                                                        // Else if no microphone state change...
      
      if (hu_aap_out_get (AA_CH_AUD) >= 0)                              // If audio out stop...
        return (3);                                                     // Done w/ audio out notification 0
      if (hu_aap_out_get (AA_CH_AU1) >= 0)                              // If audio out stop...
        return (4);                                                     // Done w/ audio out notification 1
      if (hu_aap_out_get (AA_CH_AU2) >= 0)                              // If audio out stop...
        return (5);                                                     // Done w/ audio out notification 2
    }

    byte * dq_buf = NULL;
    dq_buf = aud_read_head_buf_get (& res_len);                         // Get audio if ready

    if (dq_buf == NULL)                                                 // If no audio... (Audio has priority over video)
      dq_buf = vid_read_head_buf_get (& res_len);                       // Get video if ready

    else {                                                              // If audio
      if (dq_buf [0] == 0 && dq_buf [1] == 0 && dq_buf [2] == 0 && dq_buf [3] == 1) {
        dq_buf [3] = 0;                                                   // If audio happened to have magic video signature... (rare), then 0 the 1
        loge ("magic video signature in audio");
      }

      //hu_uti.c:  #define aud_buf_BUFS_SIZE    65536 * 4      // Up to 256 Kbytes
    }

    if (ena_log_extra || (ena_log_verbo && dq_buf != NULL))
      logd ("dq_buf: %p", dq_buf);
    if (dq_buf == NULL || res_len <= 0) {
      if (ena_log_extra)
        logd ("No data dq_buf: %p  res_len: %d", dq_buf, res_len);
      return (0);
    }
    memcpy (res_buf, dq_buf, res_len);

    if (ena_log_verbo)
      logd ("res_len: %d", res_len);
    return (res_len);
  }
コード例 #8
0
static void soundread_filerec_fileplay_soundwrite(void) {
	MSConnectionHelper h;
	unsigned int filter_mask = FILTER_MASK_SOUNDREAD | FILTER_MASK_FILEREC | FILTER_MASK_FILEPLAY | FILTER_MASK_SOUNDWRITE;
	int capture_sample_rate = 8000;
	int playback_sample_rate = 8000;
	int capture_nchannels = 1;
	int playback_nchannels = 1;

	ms_filter_reset_statistics();
	ms_tester_create_ticker();
	ms_tester_create_filters(filter_mask);

	// Write audio capture to a file
	ms_filter_call_method(ms_tester_soundread, MS_FILTER_GET_SAMPLE_RATE, &capture_sample_rate);
	ms_filter_call_method(ms_tester_soundread, MS_FILTER_GET_NCHANNELS, &capture_nchannels);
	ms_filter_call_method(ms_tester_filerec, MS_FILTER_SET_SAMPLE_RATE, &capture_sample_rate);
	ms_filter_call_method(ms_tester_filerec, MS_FILTER_SET_NCHANNELS, &capture_nchannels);
	ms_filter_call_method_noarg(ms_tester_filerec, MS_FILE_REC_CLOSE);
	ms_filter_call_method(ms_tester_filerec, MS_FILE_REC_OPEN, SOUNDREAD_FILE_NAME);
	ms_filter_call_method_noarg(ms_tester_filerec, MS_FILE_REC_START);
	ms_connection_helper_start(&h);
	ms_connection_helper_link(&h, ms_tester_soundread, -1, 0);
	ms_connection_helper_link(&h, ms_tester_filerec, 0, -1);
	ms_ticker_attach(ms_tester_ticker, ms_tester_soundread);

	ms_sleep(4);

	ms_filter_call_method_noarg(ms_tester_filerec, MS_FILE_REC_CLOSE);
	ms_ticker_detach(ms_tester_ticker, ms_tester_soundread);
	ms_connection_helper_start(&h);
	ms_connection_helper_unlink(&h, ms_tester_soundread, -1, 0);
	ms_connection_helper_unlink(&h, ms_tester_filerec, 0, -1);

	// Read the previous file and play it
	ms_filter_call_method(ms_tester_soundwrite, MS_FILTER_GET_SAMPLE_RATE, &playback_sample_rate);
	ms_filter_call_method(ms_tester_soundwrite, MS_FILTER_GET_NCHANNELS, &playback_nchannels);
	if ((capture_sample_rate != playback_sample_rate) || (capture_nchannels != playback_nchannels)) {
		ms_tester_create_filter(&ms_tester_resampler, MS_RESAMPLE_ID);
	}
	ms_filter_call_method_noarg(ms_tester_fileplay, MS_FILE_PLAYER_CLOSE);
	ms_filter_call_method(ms_tester_fileplay, MS_FILE_PLAYER_OPEN, SOUNDREAD_FILE_NAME);
	ms_filter_call_method_noarg(ms_tester_fileplay, MS_FILE_PLAYER_START);
	ms_connection_helper_start(&h);
	ms_connection_helper_link(&h, ms_tester_fileplay, -1, 0);
	if (ms_tester_resampler != NULL) {
		ms_connection_helper_link(&h, ms_tester_resampler, 0, 0);
		ms_filter_call_method(ms_tester_resampler, MS_FILTER_SET_SAMPLE_RATE, &capture_sample_rate);
		ms_filter_call_method(ms_tester_resampler, MS_FILTER_SET_OUTPUT_SAMPLE_RATE, &playback_sample_rate);
		ms_filter_call_method(ms_tester_resampler, MS_FILTER_SET_NCHANNELS, &capture_nchannels);
		ms_filter_call_method(ms_tester_resampler, MS_FILTER_SET_OUTPUT_NCHANNELS, &capture_nchannels);
	}
	ms_connection_helper_link(&h, ms_tester_soundwrite, 0, -1);
	ms_ticker_attach(ms_tester_ticker, ms_tester_fileplay);

	ms_sleep(4);

	ms_filter_call_method_noarg(ms_tester_fileplay, MS_FILE_PLAYER_CLOSE);
	ms_ticker_detach(ms_tester_ticker, ms_tester_fileplay);
	ms_connection_helper_start(&h);
	ms_connection_helper_unlink(&h, ms_tester_fileplay, -1, 0);
	if (ms_tester_resampler != NULL) {
		ms_connection_helper_unlink(&h, ms_tester_resampler, 0, 0);
	}
	ms_connection_helper_unlink(&h, ms_tester_soundwrite, 0, -1);
	ms_filter_log_statistics();
	ms_tester_destroy_filters(filter_mask);
	ms_tester_destroy_ticker();

	unlink(SOUNDREAD_FILE_NAME);
}
コード例 #9
0
ファイル: player.c プロジェクト: CBke/cmus
static void *consumer_loop(void *arg)
{
	while (1) {
		int rc, space;
		int size;
		char *rpos;

		consumer_lock();
		if (!consumer_running)
			break;

		if (consumer_status == CS_PAUSED || consumer_status == CS_STOPPED) {
			pthread_cond_wait(&consumer_playing, &consumer_mutex);
			consumer_unlock();
			continue;
		}
		space = op_buffer_space();
		if (space < 0) {
			d_print("op_buffer_space returned %d %s\n", space,
					space == -1 ? strerror(errno) : "");

			/* try to reopen */
			op_close();
			__consumer_status_update(CS_STOPPED);
			__consumer_play();

			consumer_unlock();
			continue;
		}
/* 		d_print("BS: %6d %3d\n", space, space * 1000 / (44100 * 2 * 2)); */

		while (1) {
			if (space == 0) {
				__consumer_position_update();
				consumer_unlock();
				ms_sleep(25);
				break;
			}
			size = buffer_get_rpos(&rpos);
			if (size == 0) {
				producer_lock();
				if (producer_status != PS_PLAYING) {
					producer_unlock();
					consumer_unlock();
					break;
				}
				/* must recheck rpos */
				size = buffer_get_rpos(&rpos);
				if (size == 0) {
					/* OK. now it's safe to check if we are at EOF */
					if (ip_eof(ip)) {
						/* EOF */
						__consumer_handle_eof();
						producer_unlock();
						consumer_unlock();
						break;
					} else {
						/* possible underrun */
						producer_unlock();
						__consumer_position_update();
						consumer_unlock();
/* 						d_print("possible underrun\n"); */
						ms_sleep(10);
						break;
					}
				}

				/* player_buffer and ip.eof were inconsistent */
				producer_unlock();
			}
			if (size > space)
				size = space;
			if (soft_vol || replaygain)
				scale_samples(rpos, (unsigned int *)&size);
			rc = op_write(rpos, size);
			if (rc < 0) {
				d_print("op_write returned %d %s\n", rc,
						rc == -1 ? strerror(errno) : "");

				/* try to reopen */
				op_close();
				__consumer_status_update(CS_STOPPED);
				__consumer_play();

				consumer_unlock();
				break;
			}
			buffer_consume(rc);
			consumer_pos += rc;
			space -= rc;
		}
	}
	__consumer_stop();
	consumer_unlock();
	return NULL;
}
コード例 #10
0
ファイル: llwatchdog.cpp プロジェクト: Nora28/imprudence
	void stop() 
	{
		mStopping = true; 
		ms_sleep(1);
	}
コード例 #11
0
static void soundread_speexenc_speexdec_soundwrite(void) {
	MSConnectionHelper h;
	MSFilter *read_resampler = NULL, *write_resampler = NULL;
	bool_t need_read_resampler = FALSE, need_write_resampler = FALSE;
	unsigned int filter_mask = FILTER_MASK_SOUNDREAD | FILTER_MASK_ENCODER | FILTER_MASK_DECODER | FILTER_MASK_SOUNDWRITE;
	int sample_rate = 8000;
	int nchannels = 1;

	ms_filter_reset_statistics();
	ms_tester_create_ticker();
	ms_tester_codec_mime = "speex";
	ms_tester_create_filters(filter_mask);
	ms_filter_call_method(ms_tester_encoder, MS_FILTER_GET_BITRATE, &sample_rate);
	ms_filter_call_method(ms_tester_decoder, MS_FILTER_SET_BITRATE, &sample_rate);
	if (ms_filter_call_method(ms_tester_soundread, MS_FILTER_SET_BITRATE, &sample_rate) != 0) {
		int soundread_sample_rate = 48000;
		ms_filter_call_method(ms_tester_soundread, MS_FILTER_GET_BITRATE, &soundread_sample_rate);
		if (sample_rate != soundread_sample_rate) need_read_resampler = TRUE;
	}
	if (ms_filter_call_method(ms_tester_soundread, MS_FILTER_SET_NCHANNELS, &nchannels) != 0) {
		int soundread_nchannels = 1;
		ms_filter_call_method(ms_tester_soundread, MS_FILTER_GET_NCHANNELS, &soundread_nchannels);
		if (nchannels != soundread_nchannels) need_read_resampler = TRUE;
	}
	if (need_read_resampler == TRUE) {
		ms_tester_create_filter(&read_resampler, MS_RESAMPLE_ID);
		configure_resampler(read_resampler, ms_tester_soundread, ms_tester_encoder);
	}
	if (ms_filter_call_method(ms_tester_soundwrite, MS_FILTER_SET_BITRATE, &sample_rate) != 0) {
		int soundwrite_sample_rate = 48000;
		ms_filter_call_method(ms_tester_soundwrite, MS_FILTER_GET_BITRATE, &soundwrite_sample_rate);
		if (sample_rate != soundwrite_sample_rate) need_write_resampler = TRUE;
	}
	if (ms_filter_call_method(ms_tester_soundwrite, MS_FILTER_SET_NCHANNELS, &nchannels) != 0) {
		int soundwrite_nchannels = 1;
		ms_filter_call_method(ms_tester_soundwrite, MS_FILTER_GET_NCHANNELS, &soundwrite_nchannels);
		if (nchannels != soundwrite_nchannels) need_write_resampler = TRUE;
	}
	if (need_write_resampler == TRUE) {
		ms_tester_create_filter(&write_resampler, MS_RESAMPLE_ID);
		configure_resampler(write_resampler, ms_tester_decoder, ms_tester_soundwrite);
	}
	ms_connection_helper_start(&h);
	ms_connection_helper_link(&h, ms_tester_soundread, -1, 0);
	if (need_read_resampler == TRUE) {
		ms_connection_helper_link(&h, read_resampler, 0, 0);
	}
	ms_connection_helper_link(&h, ms_tester_encoder, 0, 0);
	ms_connection_helper_link(&h, ms_tester_decoder, 0, 0);
	if (need_write_resampler == TRUE) {
		ms_connection_helper_link(&h, write_resampler, 0, 0);
	}
	ms_connection_helper_link(&h, ms_tester_soundwrite, 0, -1);
	ms_ticker_attach(ms_tester_ticker, ms_tester_soundread);

	ms_sleep(5);

	ms_ticker_detach(ms_tester_ticker, ms_tester_soundread);
	ms_connection_helper_start(&h);
	ms_connection_helper_unlink(&h, ms_tester_soundread, -1, 0);
	if (need_read_resampler == TRUE) {
		ms_connection_helper_unlink(&h, read_resampler, 0, 0);
	}
	ms_connection_helper_unlink(&h, ms_tester_encoder, 0, 0);
	ms_connection_helper_unlink(&h, ms_tester_decoder, 0, 0);
	if (need_write_resampler == TRUE) {
		ms_connection_helper_unlink(&h, write_resampler, 0, 0);
	}
	ms_connection_helper_unlink(&h, ms_tester_soundwrite, 0, -1);
	if (need_read_resampler == TRUE) {
		ms_tester_destroy_filter(&read_resampler);
	}
	if (need_write_resampler == TRUE) {
		ms_tester_destroy_filter(&write_resampler);
	}
	ms_filter_log_statistics();
	ms_tester_destroy_filters(filter_mask);
	ms_tester_destroy_ticker();
}
コード例 #12
0
ファイル: play.c プロジェクト: dormclub/tjphone
int main(int argc, char *argv[]){
	MSFilter *f1,*f2,*g729en,*g729de;
	MSSndCard *card_capture;
	MSSndCard *card_playback;
	MSTicker *ticker;
	char *capt_card=NULL,*play_card=NULL;
	int rate = 8000;
	int loop = -2;
	int i;
	const char *name="test.wav";
#ifdef __linux
	const char *alsadev=NULL;
#endif

	ortp_init();
	ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL);
	ms_init();

#ifndef _WIN32_WCE
	signal(SIGINT,stop);
#endif

#ifdef __linux
	alsadev=getenv("MS2_ALSADEV");
	if (alsadev!=NULL){
		ms_snd_card_manager_add_card(ms_snd_card_manager_get(),
			ms_alsa_card_new_custom (alsadev,alsadev));
	}
#endif
	
	for(i=1;i<argc;++i){
		if (strcmp(argv[i],"--help")==0){
			print_usage();
		}else if (strcmp(argv[i],"--card")==0){
			i++;
			capt_card=play_card=argv[i];
		}else if (strcmp(argv[i],"--capt-card")==0){
			i++;
			capt_card=argv[i];
		}else if (strcmp(argv[i],"--file-name")==0){
			i++;
			name=argv[i];
		}else if (strcmp(argv[i],"--play-card")==0){
			i++;
			play_card=argv[i];
		}
	}

	if (capt_card)
		card_capture = ms_snd_card_manager_get_card(ms_snd_card_manager_get(),capt_card);
	else card_capture = ms_snd_card_manager_get_default_capture_card(ms_snd_card_manager_get());
	if (play_card)
		card_playback = ms_snd_card_manager_get_card(ms_snd_card_manager_get(),play_card);
	else card_playback = ms_snd_card_manager_get_default_playback_card(ms_snd_card_manager_get());
	
	if (card_playback==NULL || card_capture==NULL){
		ms_error("No card.");
		return -1;
	}

	f1=ms_filter_new(MS_FILE_PLAYER_ID);
	f2=ms_snd_card_create_writer(card_playback);
	g729de=ms_filter_create_decoder("G729");
	ms_filter_call_method (f1, MS_FILTER_SET_SAMPLE_RATE,
		&rate);
	ms_filter_call_method (f2, MS_FILTER_SET_SAMPLE_RATE,
		&rate);
	ms_filter_call_method(g729de, MS_FILTER_SET_SAMPLE_RATE,
		&rate);
	ms_filter_call_method_noarg(f1,MS_FILE_PLAYER_CLOSE);
	ms_filter_call_method(f1,MS_FILE_PLAYER_OPEN,(void*)name);
	ms_filter_call_method_noarg(f1,MS_FILE_PLAYER_START);
	ms_filter_call_method(f1,MS_FILE_PLAYER_LOOP,&loop);
	ticker=ms_ticker_new();
	ms_filter_link(f1,0,g729de,0);
	ms_filter_link(g729de,0,f2,0);
	ms_ticker_attach(ticker,f1);
#ifndef _WIN32_WCE
	while(run)
		ms_sleep(1);
#else
	ms_sleep(5);
#endif
	ms_ticker_detach(ticker,f1);
	ms_ticker_destroy(ticker);
	ms_filter_unlink(g729de,0,f2,0);
	ms_filter_unlink(f1,0,g729de,0);
	ms_filter_destroy(f1);
	ms_filter_destroy(g729de);
	ms_filter_destroy(f2);
	return 0;
}
コード例 #13
0
ファイル: rec.c プロジェクト: blueskycoco/hp
void rec(char *filename)
{
	MSFilter *f1_r,*f1_w,*record;
	MSSndCard *card_capture1;
	MSSndCard *card_playback1;
	MSTicker *ticker1;
	struct msg_st data_w;
	long int msgtype = 0;
	char *capt_card1=NULL,*play_card1=NULL;
	int rate = 8000;
	int nchan=2;
	int i;
	const char *alsadev=NULL;
	int  msgid = msgget((key_t)1234, 0666 | IPC_CREAT);  
	if(msgid == -1)  
	{  
		fprintf(stderr, "msgget failed with error: %d\n", errno);  
		exit(-1);  
	}  

	ortp_init();
	ortp_set_log_level_mask(/*ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|*/ORTP_FATAL);
	ms_init();

	card_capture1 = ms_snd_card_manager_get_default_capture_card(ms_snd_card_manager_get());
	card_playback1 = ms_snd_card_manager_get_default_playback_card(ms_snd_card_manager_get());
	if (card_playback1==NULL || card_capture1==NULL)
	{
		if(card_playback1==NULL)
			ms_error("No card. card_playback1 %s",capt_card1);
		if(card_capture1==NULL)
			ms_error("No card. card_capture1 %s",capt_card1);
		//return -1;
	}
	else
	{
		ms_warning("card_playback1 %s|%s|%s|%d|%d|%d",card_playback1->name,card_playback1->id,card_playback1->desc->driver_type,
				card_playback1->capabilities,card_playback1->latency,card_playback1->preferred_sample_rate);
	}
	record=ms_filter_new(MS_FILE_REC_ID);
	if(ms_filter_call_method(record,MS_FILE_REC_OPEN,(void*)filename)!=0)
		printf("record open file %s failed\n",filename);
	f1_r=ms_snd_card_create_reader(card_capture1);
	if(f1_r!=NULL&&record!=NULL)
	{
		if(ms_filter_call_method(f1_r, MS_FILTER_SET_SAMPLE_RATE,	&rate)!=0)
			printf("set sample rate f1_r failed\n");
		if(ms_filter_call_method(record, MS_FILTER_SET_SAMPLE_RATE,&rate)!=0)
			printf("set sample rate record failed\n");
		if(ms_filter_call_method(f1_r, MS_FILTER_SET_NCHANNELS,	&nchan)!=0)
			printf("set nchan f1_r failed\n");
		if(ms_filter_call_method(record, MS_FILTER_SET_NCHANNELS,&nchan)!=0)
			printf("set nchan record failed\n");
		ms_filter_call_method_noarg(record,MS_FILE_REC_START);
		ticker1=ms_ticker_new();
		ms_ticker_set_name(ticker1,"card1 to card2");
		ms_filter_link(f1_r,0,record,0);	 	
		ms_ticker_attach(ticker1,f1_r);
		msgtype=8;
		while(1)
		{
			msgrcv(msgid, (void*)&data_w, sizeof(struct msg_st)-sizeof(long int), msgtype, IPC_NOWAIT);
			if(data_w.id==1)
				break;
			ms_sleep(1);
		}

		ms_filter_call_method(record,MS_FILE_REC_STOP,NULL);
		ms_filter_call_method(record,MS_FILE_REC_CLOSE,NULL);
		if(ticker1) ms_ticker_detach(ticker1,f1_r);
		if(f1_r&&record) ms_filter_unlink(f1_r,0,record,0);
		if(ticker1) ms_ticker_destroy(ticker1);
		if(f1_r) ms_filter_destroy(f1_r);
		if(record) ms_filter_destroy(record);		
		printf("to get string from server\n");
		data_w.msg_type = 7;
		data_w.id=0;
		char *tmp=strrchr(get_from_server(filename),'=');
		if(tmp==NULL)
			strcpy(data_w.text,"can not find result from server");
		else
			strcpy(data_w.text, tmp+1);  
		if(msgsnd(msgid, (void*)&data_w, 512, IPC_NOWAIT) == -1)  
		{  
			fprintf(stderr, "msgsnd failed\n");  
			//exit(1);  
		}  
	}	
}
コード例 #14
0
ファイル: rec.c プロジェクト: blueskycoco/hp
int main(int argc, char *argv[])
{

	pid_t fpid;	
	int msgid = -1;

	msgid = msgget((key_t)1234, 0666 | IPC_CREAT);  
	if(msgid == -1)  
	{  
		fprintf(stderr, "msgget failed with error: %d\n", errno);  
		exit(-1);  
	}

	fpid=fork();
	if(fpid<0)
		printf("fork failed\n");
	else if(fpid==0)
	{
		//child process,capture audio when main process send start cmd, finish when receive stop cmd
		//rec((char *)argv[1]);		
		long int msgtype = 8;//MAIN_TO_AUDIO 8
		struct msg_st data_r;
		while(1)
		{
			printf("waiting audio capt cmd...\n");
			msgrcv(msgid, (void*)&data_r, sizeof(struct msg_st)-sizeof(long int), msgtype, 0);
			printf("data_r id %d,text %d\n",data_r.msg_type,data_r.id);
			switch (data_r.id)
			{
				case 0://start rec
				{
					rec("/tmp/rec.avi");
				}
				break;
				case 2://start transfer string and play
				{
					play(data_r.text,"/tmp/3.wav");
					playback("/tmp/3.wav");
				}
				break;
				default:
					break;
			}
		}
	}
	else
	{
		//father process
		long int msgtype = 8;//MAIN_TO_AUDIO 8
		struct msg_st data_r;
		int status;
		while(1)
		{
			ms_sleep(2);
			data_r.msg_type = 8;
			data_r.id=0;
			printf("start record\n");
			if(msgsnd(msgid, (void*)&data_r, sizeof(struct msg_st)-sizeof(long int), IPC_NOWAIT) == -1)  
			{  
				fprintf(stderr, "msgsnd failed %s msgid %d\n",strerror(errno),msgid);  
				exit(1);  
			}  
			ms_sleep(3);
			data_r.msg_type = 8;
			data_r.id=1;  
			printf("stop record\n");
			if(msgsnd(msgid, (void*)&data_r, sizeof(struct msg_st)-sizeof(long int), IPC_NOWAIT) == -1)  
			{  
				fprintf(stderr, "msgsnd failed %s\n",strerror(errno));  
				exit(1);  
			} 
			printf("waiting message 7\n"); 
			msgtype=7;
			msgrcv(msgid, (void*)&data_r, sizeof(struct msg_st)-sizeof(long int), msgtype, 0);

			printf("Get Result %s\n",data_r.text);
			
			data_r.msg_type = 8;    //注意2
			data_r.id=2;  
			printf("start transfer and playback\n");
			if(msgsnd(msgid, (void*)&data_r, sizeof(struct msg_st)-sizeof(long int), IPC_NOWAIT) == -1)  
			{  
				fprintf(stderr, "msgsnd failed %s\n",strerror(errno));  
				exit(1);  
			}
			system("rm /tmp/rec.avi");
			//system("ipcs -q");
		}
		waitpid(fpid, &status, 0);
	}
	return 0;
}
コード例 #15
0
ファイル: ws.c プロジェクト: davehorton/sofia-sip
static int establish_logical_layer(wsh_t *wsh)
{

	if (!wsh->sanity) {
		return -1;
	}

	if (wsh->logical_established) {
		return 0;
	}

	if (wsh->secure && !wsh->secure_established) {
		int code;

		if (!wsh->ssl) {
			wsh->ssl = SSL_new(wsh->ssl_ctx);
			assert(wsh->ssl);

			SSL_set_fd(wsh->ssl, wsh->sock);
		}

		do {
			code = SSL_accept(wsh->ssl);

			if (code == 1) {
				wsh->secure_established = 1;
				break;
			}

			if (code == 0) {
				return -1;
			}
			
			if (code < 0) {
				if (code == -1 && SSL_get_error(wsh->ssl, code) != SSL_ERROR_WANT_READ) {
					return -1;
				}
			}

			if (wsh->block) {
				ms_sleep(10);
			} else {
				ms_sleep(1);
			}

			wsh->sanity--;

			if (!wsh->block) {
				return -2;
			}

		} while (wsh->sanity > 0);
		
		if (!wsh->sanity) {
			return -1;
		}
		
	}

	while (!wsh->down && !wsh->handshake) {
		int r = ws_handshake(wsh);

		if (r < 0) {
			wsh->down = 1;
			return -1;
		}

		if (!wsh->handshake && !wsh->block) {
			return -2;
		}

	}

	wsh->logical_established = 1;
	
	return 0;
}
コード例 #16
0
ファイル: player.c プロジェクト: CBke/cmus
static void *producer_loop(void *arg)
{
	while (1) {
		/* number of chunks to fill
		 * too big   => seeking is slow
		 * too small => underruns?
		 */
		const int chunks = 1;
		int size, nr_read, i;
		char *wpos;

		producer_lock();
		if (!producer_running)
			break;

		if (producer_status == PS_UNLOADED ||
		    producer_status == PS_PAUSED ||
		    producer_status == PS_STOPPED || ip_eof(ip)) {
			pthread_cond_wait(&producer_playing, &producer_mutex);
			producer_unlock();
			continue;
		}
		for (i = 0; ; i++) {
			size = buffer_get_wpos(&wpos);
			if (size == 0) {
				/* buffer is full */
				producer_unlock();
				ms_sleep(50);
				break;
			}
			nr_read = ip_read(ip, wpos, size);
			if (nr_read < 0) {
				if (nr_read != -1 || errno != EAGAIN) {
					player_ip_error(nr_read, "reading file %s",
							ip_get_filename(ip));
					/* ip_read sets eof */
					nr_read = 0;
				} else {
					producer_unlock();
					ms_sleep(50);
					break;
				}
			}
			if (ip_metadata_changed(ip))
				metadata_changed();

			/* buffer_fill with 0 count marks current chunk filled */
			buffer_fill(nr_read);
			if (nr_read == 0) {
				/* consumer handles EOF */
				producer_unlock();
				ms_sleep(50);
				break;
			}
			if (i == chunks) {
				producer_unlock();
				/* don't sleep! */
				break;
			}
		}
		__producer_buffer_fill_update();
	}
	__producer_unload();
	producer_unlock();
	return NULL;
}
コード例 #17
0
ファイル: hu_usb.c プロジェクト: tdassonville/headunit
  int iusb_oap_start () {
    byte oap_protocol_data [2] = {0, 0};
    int oap_protocol_level   = 0;

    uint8_t       req_type= USB_SETUP_DEVICE_TO_HOST | USB_SETUP_TYPE_VENDOR | USB_SETUP_RECIPIENT_DEVICE;
    uint8_t       req_val = ACC_REQ_GET_PROTOCOL;
    uint16_t      val     = 0;
    uint16_t      idx     = 0;
    byte *        data    = oap_protocol_data;
    uint16_t      len     = sizeof (oap_protocol_data);
    unsigned int  tmo     = 1000;
                                                                        // Get OAP Protocol level
    val = 0;
    idx = 0;
    int usb_err = iusb_control_transfer (iusb_dev_hndl, req_type, req_val, val, idx, data, len, tmo);
    if (usb_err != 0) {
      loge ("Done iusb_control_transfer usb_err: %d (%s)", usb_err, iusb_error_get (usb_err));
      return (-1);
    }

    logd ("Done iusb_control_transfer usb_err: %d (%s)", usb_err, iusb_error_get (usb_err));

    oap_protocol_level = data [1] << 8 | data [0];
    if (oap_protocol_level < 2) {
      loge ("Error oap_protocol_level: %d", oap_protocol_level);
      return (-1);
    }
    logd ("oap_protocol_level: %d", oap_protocol_level);
    
    ms_sleep (50);//1);                                                        // Sometimes hangs on the next transfer

//if (iusb_best_vendor == USB_VID_GOO)
//  {logd ("Done USB_VID_GOO 1"); return (0); }

    req_type = USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_VENDOR | USB_SETUP_RECIPIENT_DEVICE;
    req_val = ACC_REQ_SEND_STRING;

    char AAP_VAL_MAN [31] = "Android";
    char AAP_VAL_MOD [97] = "Android Auto";    // "Android Open Automotive Protocol"

    int garb = -1;
    iusb_control_transfer (iusb_dev_hndl, req_type, req_val, val, ACC_IDX_MAN, AAP_VAL_MAN, strlen (AAP_VAL_MAN) + 1, tmo);
    iusb_control_transfer (iusb_dev_hndl, req_type, req_val, val, ACC_IDX_MOD, AAP_VAL_MOD, strlen (AAP_VAL_MOD) + 1, tmo);
    //iusb_control_transfer (iusb_dev_hndl, req_type, req_val, val, ACC_IDX_DES, AAP_VAL_DES, strlen (AAP_VAL_DES) + 1, tmo);
    //iusb_control_transfer (iusb_dev_hndl, req_type, req_val, val, ACC_IDX_VER, AAP_VAL_VER, strlen (AAP_VAL_VER) + 1, tmo);
    //iusb_control_transfer (iusb_dev_hndl, req_type, req_val, val, ACC_IDX_URI, AAP_VAL_URI, strlen (AAP_VAL_URI) + 1, tmo);
    //iusb_control_transfer (iusb_dev_hndl, req_type, req_val, val, ACC_IDX_SER, AAP_VAL_SER, strlen (AAP_VAL_SER) + 1, tmo);

    logd ("Accessory IDs sent");

//if (iusb_best_vendor == USB_VID_GOO)
//  {logd ("Done USB_VID_GOO 2"); return (0); }

/*
    req_val = ACC_REQ_AUDIO;
    val = 1;                                                            // 0 for no audio (default),    1 for 2 channel, 16-bit PCM at 44100 KHz
    idx = 0;
    if (iusb_control_transfer (iusb_dev_hndl, req_type, req_val, val, idx, NULL, 0, tmo) < 0) {
      loge ("Error Audio mode request sent");
      return (-1);
    }
    logd ("OK Audio mode request sent");
*/
    req_val = ACC_REQ_START;
    val = 0;
    idx = 0;
    if (iusb_control_transfer (iusb_dev_hndl, req_type, req_val, val, idx, NULL, 0, tmo) < 0) {
      loge ("Error Accessory mode start request sent");
      return (-1);
    }
    logd ("OK Accessory mode start request sent");

    return (0);
  }
コード例 #18
0
ファイル: loop_main.cpp プロジェクト: Sishio/cyberpvnk
void loop_run(loop_t *a){
	if((a->settings & LOOP_PRINT_THIS_TIME) != 0){
		printf_("settings: " + std::to_string(a->settings) + "\n", PRINTF_VITAL);
	}
	if(check_for_parameter("--no-mt", argc_, argv_)){
		a->settings &= ~LOOP_CODE_NEVEREND_MT;
		a->settings &= ~LOOP_CODE_PARTIAL_MT;
	}
	std::string summary = a->array.name + "\n";
	const uint_ code_size = a->code.size();
	const long double start_time = get_time();
	for(uint_ i = 0;i < a->code.size();i++){
		try{
			loop_entry_t *tmp_entry = (loop_entry_t*)find_pointer(a->code[i]);
			throw_if_nullptr(tmp_entry);
			if(check_for_parameter("--no-mt", argc_, argv_)){
				tmp_entry->set_settings(0);
				tmp_entry->set_settings(0);
			}
			tmp_entry->array.data_lock.lock();
			if(tmp_entry->term == true){
				if(tmp_entry->thread != nullptr){
					stop_infinite_loop(tmp_entry);
				}else{
					a->code.erase(a->code.begin()+i);
				}
			}else if(tmp_entry->code != nullptr){ // Deleting its place in the array allows for a seg fault if both pieces run
				if(tmp_entry->get_settings(LOOP_CODE_PARTIAL_MT)){
					//printf_("DEBUG: loop_run: Running the following loop_entry_t in its own thread (LOOP_CODE_PARTIAL_MT):" + tmp_entry->array.print() + "\n", PRINTF_DEBUG);
					tmp_entry->thread = new std::thread(tmp_entry->code);
					tmp_entry->start_time = get_time();
				}else if(tmp_entry->get_settings(LOOP_CODE_NEVEREND_MT)){
					if(tmp_entry->thread == nullptr){
						//printf_("DEBUG: loop_run: Running the following loop_entry_t in its own thread (LOOP_CODE_NEVEREND_MT):" + tmp_entry->array.print() + "\n", PRINTF_DEBUG);
						tmp_entry->thread = new std::thread(infinite_loop_function, tmp_entry->code, &(tmp_entry->term));
						tmp_entry->start_time = get_time();
					}
				}else if(likely(tmp_entry->iteration_skip == 0 || a->tick%(tmp_entry->iteration_skip+1) == 0)){
					if(tmp_entry->thread != nullptr){
						stop_infinite_loop(tmp_entry);
					}
					tmp_entry->start_time = get_time();
					//printf_("DEBUG: loop_run: Running the following loop_entry_t in the current thread:" + tmp_entry->array.print() + "\n", PRINTF_DEBUG);
					tmp_entry->code();
				}
			}
			tmp_entry->array.data_lock.unlock();
			/*
			  WARNING: be careful of throwing something that misses a vital unlock
			 */
		}catch(std::logic_error &e){}
	}
	for(uint_ i = 0;i < a->code.size();i++){
		try{
			loop_entry_t *tmp_entry = (loop_entry_t*)find_pointer(a->code[i]);
			throw_if_nullptr(tmp_entry);
			tmp_entry->array.data_lock.lock();
			if(tmp_entry->get_settings(LOOP_CODE_PARTIAL_MT)){
				tmp_entry->thread->join();
				tmp_entry->end_time = get_time();
				delete tmp_entry->thread;
				tmp_entry->thread = nullptr;
			}
			tmp_entry->array.data_lock.unlock();
		}catch(std::logic_error &e){}
	}
	const long double end_time = get_time();
	const long double current_rate = 1/(end_time-start_time);
	if(unlikely(a->average_rate == 0)){
		a->average_rate = current_rate;
	}
	a->average_rate += current_rate;
	a->average_rate *= .5;
	if((a->settings & LOOP_PRINT_THIS_TIME) != 0){
		summary += "current frame rate: " + std::to_string(current_rate) + "\naverage framerate: " + std::to_string(a->average_rate) + "\nloop_settings: " + std::to_string(a->settings) + "\n";
		summary += "\tTitle\tIteration Skip\n";
		for(uint_ i = 0;i < a->code.size();i++){
			try{
				loop_entry_t *tmp = (loop_entry_t*)find_pointer(a->code[i]);
				summary += "\t" + tmp->name + "\t" + std::to_string(tmp->iteration_skip) + "\n";
			}catch(std::logic_error &e){}
		}
		printf("%s", summary.c_str());
		a->settings &= ~LOOP_PRINT_THIS_TIME;
	}
	++a->tick;
	if(check_for_parameter("--debug", argc_, argv_)) ms_sleep(1000);
}
コード例 #19
0
int main(int argc, char *argv[]){
	MSFilter *src, *gen, *det, *rec;
	MSTicker *ticker;

	ms_init();
	ortp_set_log_level_mask (ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL);

	src=ms_filter_new(MS_FILE_PLAYER_ID);
	rec=ms_filter_new(MS_FILE_REC_ID);
	gen=ms_filter_new(MS_DTMF_GEN_ID);
	det=ms_filter_new(MS_TONE_DETECTOR_ID);
	
	ms_filter_link(src,0,gen,0);
	ms_filter_link(gen,0,det,0);
	//ms_filter_link(gen,0,rec,0);
	ms_filter_link(det,0,rec,0);

	ticker=ms_ticker_new();

	ms_ticker_attach(ticker,src);

	ms_filter_call_method(rec,MS_FILE_REC_OPEN,"/tmp/output.wav");
	ms_filter_call_method_noarg(rec,MS_FILE_REC_START);
	{
		/*generate and detect the tones*/
		MSDtmfGenCustomTone tone;
		MSToneDetectorDef expected_tone;
		char dtmf='*';
			
		tone.frequency=2000;
		tone.duration=400;
		tone.amplitude=0.6;

		expected_tone.frequency=2000;
		expected_tone.min_duration=200;
		expected_tone.min_amplitude=0.5;
		ms_filter_set_notify_callback(det,(MSFilterNotifyFunc)tone_detected_cb,NULL);
		ms_filter_set_notify_callback(gen,(MSFilterNotifyFunc)tone_sent_cb,NULL);
		
		ms_filter_call_method(det,MS_TONE_DETECTOR_ADD_SCAN,&expected_tone);

		ms_filter_call_method(gen,MS_DTMF_GEN_PLAY,&dtmf);
		ms_sleep(1);
		
		ms_filter_call_method(gen,MS_DTMF_GEN_PLAY_CUSTOM,&tone);
		ms_sleep(1);
		ms_filter_call_method(gen,MS_DTMF_GEN_PLAY_CUSTOM,&tone);
		ms_sleep(1);
		ms_filter_call_method(gen,MS_DTMF_GEN_PLAY_CUSTOM,&tone);
		ms_sleep(1);
		tone.frequency=1500;
		tone.amplitude=1.0;
		ms_filter_call_method(gen,MS_DTMF_GEN_PLAY_CUSTOM,&tone);
		ms_sleep(1);
	}

	ms_filter_call_method_noarg(rec,MS_FILE_REC_CLOSE);
	ms_ticker_detach(ticker,src);

	ms_filter_unlink(src,0,gen,0);
	ms_filter_unlink(gen,0,det,0);
	//ms_filter_unlink(gen,0,rec,0);
	ms_filter_unlink(det,0,rec,0);

	ms_ticker_destroy(ticker);

	ms_filter_destroy(src);
	ms_filter_destroy(gen);
	ms_filter_destroy(det);
	ms_filter_destroy(rec);

	ms_exit();
	return 0;
}
コード例 #20
0
ファイル: ec-calibrator.c プロジェクト: Accontech/ace-ios
static void ecc_play_tones(EcCalibrator *ecc){
	MSDtmfGenCustomTone tone;
	MSToneDetectorDef expected_tone;
	
	memset(&tone,0,sizeof(tone));
	memset(&expected_tone,0,sizeof(expected_tone));

	ms_filter_add_notify_callback(ecc->det,on_tone_received,ecc,TRUE);

	/* configure the tones to be scanned */
	
	strncpy(expected_tone.tone_name,"freq1",sizeof(expected_tone.tone_name));
	expected_tone.frequency=2000;
	expected_tone.min_duration=40;
	expected_tone.min_amplitude=0.1;

	ms_filter_call_method (ecc->det,MS_TONE_DETECTOR_ADD_SCAN,&expected_tone);
	
	strncpy(expected_tone.tone_name,"freq2",sizeof(expected_tone.tone_name));
	expected_tone.frequency=2300;
	expected_tone.min_duration=40;
	expected_tone.min_amplitude=0.1;

	ms_filter_call_method (ecc->det,MS_TONE_DETECTOR_ADD_SCAN,&expected_tone);
	
	strncpy(expected_tone.tone_name,"freq3",sizeof(expected_tone.tone_name));
	expected_tone.frequency=2500;
	expected_tone.min_duration=40;
	expected_tone.min_amplitude=0.1;

	ms_filter_call_method (ecc->det,MS_TONE_DETECTOR_ADD_SCAN,&expected_tone);
	
	/*play an initial tone to startup the audio playback/capture*/
	
	tone.frequencies[0]=140;
	tone.duration=1000;
	tone.amplitude=0.5;

	ms_filter_call_method(ecc->gen,MS_DTMF_GEN_PLAY_CUSTOM,&tone);
	ms_sleep(2);

	ms_filter_add_notify_callback(ecc->gen,on_tone_sent,ecc,TRUE);
	
	/* play the three tones*/
	
	tone.frequencies[0]=2000;
	tone.duration=100;
	ms_filter_call_method(ecc->gen,MS_DTMF_GEN_PLAY_CUSTOM,&tone);
	ms_usleep(300000);
	
	tone.frequencies[0]=2300;
	tone.duration=100;
	ms_filter_call_method(ecc->gen,MS_DTMF_GEN_PLAY_CUSTOM,&tone);
	ms_usleep(300000);
	
	tone.frequencies[0]=2500;
	tone.duration=100;
	ms_filter_call_method(ecc->gen,MS_DTMF_GEN_PLAY_CUSTOM,&tone);
	ms_sleep(1);
	
	if (ecc->freq1 && ecc->freq2 && ecc->freq3) {
		int delay=ecc->acc/3;
		if (delay<0){
			ms_error("Quite surprising calibration result, delay=%i",delay);
			ecc->status=LinphoneEcCalibratorFailed;
		}else{
			ms_message("Echo calibration estimated delay to be %i ms",delay);
			ecc->delay=delay;
			ecc->status=LinphoneEcCalibratorDone;
		}
	} else if ((ecc->freq1 || ecc->freq2 || ecc->freq3)==FALSE) {
			ms_message("Echo calibration succeeded, no echo has been detected");
			ecc->status = LinphoneEcCalibratorDoneNoEcho;
	} else {
			ecc->status = LinphoneEcCalibratorFailed;
	}

	if (ecc->status == LinphoneEcCalibratorFailed) {
		ms_error("Echo calibration failed.");
	}
}
コード例 #21
0
static void run_media_streams(int localport, const char *remote_ip, int remoteport, int payload, const char *fmtp,
          int jitter, int bitrate, MSVideoSize vs, bool_t ec, bool_t agc, bool_t eq)
{
	AudioStream *audio=NULL;
#ifdef VIDEO_ENABLED
	VideoStream *video=NULL;
#endif
	RtpSession *session=NULL;
	PayloadType *pt;
	RtpProfile *profile=rtp_profile_clone_full(&av_profile);
	OrtpEvQueue *q=ortp_ev_queue_new();	

	ms_init();
	signal(SIGINT,stop_handler);
	pt=rtp_profile_get_payload(profile,payload);
	if (pt==NULL){
		printf("Error: no payload defined with number %i.",payload);
		exit(-1);
	}
	if (fmtp!=NULL) payload_type_set_send_fmtp(pt,fmtp);
	if (bitrate>0) pt->normal_bitrate=bitrate;

	if (pt->type!=PAYLOAD_VIDEO){
		MSSndCardManager *manager=ms_snd_card_manager_get();
		MSSndCard *capt= capture_card==NULL ? ms_snd_card_manager_get_default_capture_card(manager) :
				ms_snd_card_manager_get_card(manager,capture_card);
		MSSndCard *play= playback_card==NULL ? ms_snd_card_manager_get_default_playback_card(manager) :
				ms_snd_card_manager_get_card(manager,playback_card);
		audio=audio_stream_new(localport,ms_is_ipv6(remote_ip));
		audio_stream_enable_automatic_gain_control(audio,agc);
		audio_stream_enable_noise_gate(audio,use_ng);
		audio_stream_set_echo_canceller_params(audio,ec_len_ms,ec_delay_ms,ec_framesize);
		printf("Starting audio stream.\n");
	
		audio_stream_start_full(audio,profile,remote_ip,remoteport,remoteport+1, payload, jitter,infile,outfile,
		                        outfile==NULL ? play : NULL ,infile==NULL ? capt : NULL,infile!=NULL ? FALSE: ec);
		
		if (audio) {
			if (use_ng && ng_threshold!=-1)
				ms_filter_call_method(audio->volsend,MS_VOLUME_SET_NOISE_GATE_THRESHOLD,&ng_threshold);
			session=audio->session;
		}
	}else{
#ifdef VIDEO_ENABLED
		if (eq){
			ms_fatal("Cannot put an audio equalizer in a video stream !");
			exit(-1);
		}
		printf("Starting video stream.\n");
		video=video_stream_new(localport, ms_is_ipv6(remote_ip));
		video_stream_set_sent_video_size(video,vs);
		video_stream_use_preview_video_window(video,two_windows);
		video_stream_start(video,profile,
					remote_ip,
					remoteport,remoteport+1,
					payload,
					jitter,
					ms_web_cam_manager_get_default_cam(ms_web_cam_manager_get()));
		session=video->session;
#else
		printf("Error: video support not compiled.\n");
#endif
	}
  if (eq || ec){ /*read from stdin interactive commands */
    char commands[128];
    commands[127]='\0';
    ms_sleep(1);  /* ensure following text be printed after ortp messages */
    if (eq)
      printf("\nPlease enter equalizer requests, such as 'eq active 1', 'eq active 0', 'eq 1200 0.1 200'\n");
    if (ec)
      printf("\nPlease enter echo canceller requests: ec reset; ec <delay ms> <tail_length ms'\n");
    while(fgets(commands,sizeof(commands)-1,stdin)!=NULL){
      int active,freq,freq_width;
      int delay_ms, tail_ms;
      float gain;
      if (sscanf(commands,"eq active %i",&active)==1){
        audio_stream_enable_equalizer(audio,active);
        printf("OK\n");
      }else if (sscanf(commands,"eq %i %f %i",&freq,&gain,&freq_width)==3){
        audio_stream_equalizer_set_gain(audio,freq,gain,freq_width);
        printf("OK\n");
      }else if (sscanf(commands,"eq %i %f",&freq,&gain)==2){
        audio_stream_equalizer_set_gain(audio,freq,gain,0);
        printf("OK\n");
      }else if (strstr(commands,"dump")){
        int n=0,i;
        float *t;
        ms_filter_call_method(audio->equalizer,MS_EQUALIZER_GET_NUM_FREQUENCIES,&n);
        t=(float*)alloca(sizeof(float)*n);
        ms_filter_call_method(audio->equalizer,MS_EQUALIZER_DUMP_STATE,t);
        for(i=0;i<n;++i){
          if (fabs(t[i]-1)>0.01){
            printf("%i:%f:0 ",(i*pt->clock_rate)/(2*n),t[i]);
          }
        }
        printf("\nOK\n");
      }else if (sscanf(commands,"ec reset %i",&active)==1){
          //audio_stream_enable_equalizer(audio,active);
          //printf("OK\n");
      }else if (sscanf(commands,"ec active %i",&active)==1){
          //audio_stream_enable_equalizer(audio,active);
          //printf("OK\n");
      }else if (sscanf(commands,"ec %i %i",&delay_ms,&tail_ms)==2){
        audio_stream_set_echo_canceller_params(audio,tail_ms,delay_ms,128);
        // revisit: workaround with old method call to force echo reset
        delay_ms*=8;
        ms_filter_call_method(audio->ec,MS_FILTER_SET_PLAYBACKDELAY,&delay_ms);
        printf("OK\n");
      }else if (strstr(commands,"quit")){
        break;
      }else printf("Cannot understand this.\n");
    }
	}else{  /* no interactive stuff - continuous debug output */
		rtp_session_register_event_queue(session,q);
		while(cond)
		{
			int n;
			for(n=0;n<100;++n){
	#ifdef WIN32
				MSG msg;
				Sleep(10);
				while (PeekMessage(&msg, NULL, 0, 0,1)){
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
	#else
				struct timespec ts;
				ts.tv_sec=0;
				ts.tv_nsec=10000000;
				nanosleep(&ts,NULL);
	#endif
	#if defined(VIDEO_ENABLED)
				if (video) video_stream_iterate(video);
	#endif
			}
			ortp_global_stats_display();
			if (session){
				printf("Bandwidth usage: download=%f kbits/sec, upload=%f kbits/sec\n",
					rtp_session_compute_recv_bandwidth(session)*1e-3,
					rtp_session_compute_send_bandwidth(session)*1e-3);
				parse_events(q);
			}
		}
					}
	
	printf("stopping all...\n");
	
	if (audio) audio_stream_stop(audio);
#ifdef VIDEO_ENABLED
	if (video) video_stream_stop(video);
#endif
	ortp_ev_queue_destroy(q);
	rtp_profile_destroy(profile);
}
コード例 #22
0
S32 LLQueuedThread::processNextRequest()
{
	QueuedRequest *req;
	// Get next request from pool
	lockData();
	while(1)
	{
		req = NULL;
		if (mRequestQueue.empty())
		{
			break;
		}
		req = *mRequestQueue.begin();
		mRequestQueue.erase(mRequestQueue.begin());
		if ((req->getFlags() & FLAG_ABORT) || (mStatus == QUITTING))
		{
			req->setStatus(STATUS_ABORTED);
			// Unlock, because we can't call finishRequest() while keeping this lock:
			// generateHandle() takes this lock too and is called while holding a lock
			// (ie LLTextureFetchWorker::mWorkMutex) that finishRequest will lock too,
			// causing a dead lock.
			// Although a complete rewrite of LLQueuedThread is in order because it's
			// far from robust the way it handles it's locking; the following rationale
			// at least makes plausible that releasing the lock here SHOULD work if
			// the original coder didn't completely f**k up: if before the QueuedRequest
			// req was only accessed while keeping the lock, then it still should
			// never happen that another thread is waiting for this lock in order to
			// access the QueuedRequest: a few lines lower we delete it.
			// In other words, if directly after releasing this lock another thread
			// would access req, then that can only happen by finding it again in
			// either mRequestQueue or mRequestHash. We already deleted it from the
			// first, so this access would have to happen by finding it in mRequestHash.
			// Such access happens in the following functions:
			// 1) LLQueuedThread::shutdown -- but it does that anyway, as it doesn't use any locking.
			// 2) LLQueuedThread::generateHandle -- might skip our handle while before it would block until we deleted it. Skipping it is actually better.
			// 3) LLQueuedThread::waitForResult -- this now doesn't touch the req when it has the flag FLAG_LOCKED set.
			// 4) LLQueuedThread::getRequest -- whereever this is used, FLAG_LOCKED is tested before using the req.
			// 5) LLQueuedThread::getRequestStatus -- this is a read-only operation on the status, which should never be changed from finishRequest().
			// 6) LLQueuedThread::abortRequest -- it doesn't seem to hurt to add flags (if this happens at all), while calling finishRequest().
			// 7) LLQueuedThread::setFlags -- same.
			// 8) LLQueuedThread::setPriority -- doesn't access req with status STATUS_ABORTED, STATUS_COMPLETE or STATUS_INPROGRESS.
			// 9) LLQueuedThread::completeRequest -- now sets FLAG_AUTO_COMPLETE instead of deleting the req, if FLAG_LOCKED is set, so that deletion happens here when finishRequest returns.
			req->setFlags(FLAG_LOCKED);
			unlockData();
			req->finishRequest(false);
			lockData();
			req->resetFlags(FLAG_LOCKED);
			if ((req->getFlags() & FLAG_AUTO_COMPLETE))
			{
				req->resetFlags(FLAG_AUTO_COMPLETE);
				mRequestHash.erase(req);
// 				check();
				unlockData();
				req->deleteRequest();
				lockData();
			}
			continue;
		}
		llassert_always(req->getStatus() == STATUS_QUEUED);
		break;
	}
	U32 start_priority = 0 ;
	if (req)
	{
		req->setStatus(STATUS_INPROGRESS);
		start_priority = req->getPriority();
	}
	unlockData();

	// This is the only place we will call req->setStatus() after
	// it has initially been seet to STATUS_QUEUED, so it is
	// safe to access req.
	if (req)
	{
		// process request
		bool complete = req->processRequest();

		if (complete)
		{
			lockData();
			req->setStatus(STATUS_COMPLETE);
			req->setFlags(FLAG_LOCKED);
			unlockData();
			req->finishRequest(true);
			if ((req->getFlags() & FLAG_AUTO_COMPLETE))
			{
				lockData();
				req->resetFlags(FLAG_AUTO_COMPLETE);
				mRequestHash.erase(req);
// 				check();
				req->resetFlags(FLAG_LOCKED);
				unlockData();
				req->deleteRequest();
			}
			else
			{
				req->resetFlags(FLAG_LOCKED);
			}
		}
		else
		{
			lockData();
			req->setStatus(STATUS_QUEUED);
			mRequestQueue.insert(req);
			unlockData();
			if (mThreaded && start_priority < PRIORITY_NORMAL)
			{
				ms_sleep(1); // sleep the thread a little
			}
		}
	}

	S32 pending = getPending();

	return pending;
}
コード例 #23
0
ファイル: llapp.cpp プロジェクト: AGoodPerson/Ascent
void default_unix_signal_handler(int signum, siginfo_t *info, void *)
{
	// Unix implementation of synchronous signal handler
	// This runs in the thread that threw the signal.
	// We do the somewhat sketchy operation of blocking in here until the error handler
	// has gracefully stopped the app.

	if (LLApp::sLogInSignal)
	{
		llinfos << "Signal handler - Got signal " << signum << " - " << apr_signal_description_get(signum) << llendl;
	}


	switch (signum)
	{
	case SIGCHLD:
		if (LLApp::sLogInSignal)
		{
			llinfos << "Signal handler - Got SIGCHLD from " << info->si_pid << llendl;
		}

		// Check result code for all child procs for which we've
		// registered callbacks THIS WILL NOT WORK IF SIGCHLD IS SENT
		// w/o killing the child (Go, launcher!)
		// TODO: Now that we're using SIGACTION, we can actually
		// implement the launcher behavior to determine who sent the
		// SIGCHLD even if it doesn't result in child termination
		if (LLApp::sChildMap.count(info->si_pid))
		{
			LLApp::sChildMap[info->si_pid].mGotSigChild = TRUE;
		}
		
		LLApp::incSigChildCount();

		return;
	case SIGABRT:
		// Abort just results in termination of the app, no funky error handling.
		if (LLApp::sLogInSignal)
		{
			llwarns << "Signal handler - Got SIGABRT, terminating" << llendl;
		}
		clear_signals();
		raise(signum);
		return;
	case SIGINT:
	case SIGHUP:
	case SIGTERM:
		if (LLApp::sLogInSignal)
		{
			llwarns << "Signal handler - Got SIGINT, HUP, or TERM, exiting gracefully" << llendl;
		}
		// Graceful exit
		// Just set our state to quitting, not error
		if (LLApp::isQuitting() || LLApp::isError())
		{
			// We're already trying to die, just ignore this signal
			if (LLApp::sLogInSignal)
			{
				llinfos << "Signal handler - Already trying to quit, ignoring signal!" << llendl;
			}
			return;
		}
		LLApp::setQuitting();
		return;
	case SIGALRM:
	case SIGPIPE:
	case SIGUSR2:
	default:
		if (signum == LL_SMACKDOWN_SIGNAL ||
		    signum == SIGBUS ||
		    signum == SIGILL ||
		    signum == SIGFPE ||
		    signum == SIGSEGV ||
		    signum == SIGQUIT)
		{ 
			if (signum == LL_SMACKDOWN_SIGNAL)
			{
				// Smackdown treated just like any other app termination, for now
				if (LLApp::sLogInSignal)
				{
					llwarns << "Signal handler - Handling smackdown signal!" << llendl;
				}
				else
				{
					// Don't log anything, even errors - this is because this signal could happen anywhere.
					LLError::setDefaultLevel(LLError::LEVEL_NONE);
				}
				
				// Change the signal that we reraise to SIGABRT, so we generate a core dump.
				signum = SIGABRT;
			}
			
			if (LLApp::sLogInSignal)
			{
				llwarns << "Signal handler - Handling fatal signal!" << llendl;
			}
			if (LLApp::isError())
			{
				// Received second fatal signal while handling first, just die right now
				// Set the signal handlers back to default before handling the signal - this makes the next signal wipe out the app.
				clear_signals();
				
				if (LLApp::sLogInSignal)
				{
					llwarns << "Signal handler - Got another fatal signal while in the error handler, die now!" << llendl;
				}
				raise(signum);
				return;
			}
			
			if (LLApp::sLogInSignal)
			{
				llwarns << "Signal handler - Flagging error status and waiting for shutdown" << llendl;
			}
									
			if(LLApp::sDisableCrashlogger)	//Don't gracefully handle any signals crash and core for a gdb post mortum
			{
				clear_signals();
				llwarns << "Fatal signal received, not handling the crash here, passing back to operating system" << llendl;
				raise(signum);
				return;
			}		
			
			// Flag status to ERROR, so thread_error does its work.
			LLApp::setError();
			// Block in the signal handler until somebody says that we're done.
			while (LLApp::sErrorThreadRunning && !LLApp::isStopped())
			{
				ms_sleep(10);
			}
			
			if (LLApp::sLogInSignal)
			{
				llwarns << "Signal handler - App is stopped, reraising signal" << llendl;
			}
			clear_signals();
			raise(signum);
			return;
		} else {
			if (LLApp::sLogInSignal)
			{
				llinfos << "Signal handler - Unhandled signal " << signum << ", ignoring!" << llendl;
			}
		}
	}
}
コード例 #24
0
ファイル: lldir.cpp プロジェクト: wish-ds/firestorm-ds
S32 LLDir::deleteFilesInDir(const std::string &dirname, const std::string &mask)
{
	if (!fileExists(dirname)) return 0;

	S32 count = 0;
	std::string filename; 
	std::string fullpath;
	S32 result;

	// File masks starting with "/" will match nothing, so we consider them invalid.
	if (LLStringUtil::startsWith(mask, getDirDelimiter()))
	{
		llwarns << "Invalid file mask: " << mask << llendl;
		llassert(!"Invalid file mask");
	}

	LLDirIterator iter(dirname, mask);
	while (iter.next(filename))
	{
		fullpath = dirname;
		fullpath += getDirDelimiter();
		fullpath += filename;

		if(LLFile::isdir(fullpath))
		{
			// skipping directory traversal filenames
			count++;
			continue;
		}

		S32 retry_count = 0;
		while (retry_count < 5)
		{
			if (0 != LLFile::remove(fullpath))
			{
				retry_count++;
				result = errno;
				llwarns << "Problem removing " << fullpath << " - errorcode: "
						<< result << " attempt " << retry_count << llendl;

				if(retry_count >= 5)
				{
					llwarns << "Failed to remove " << fullpath << llendl ;
					return count ;
				}

				ms_sleep(100);
			}
			else
			{
				if (retry_count)
				{
					llwarns << "Successfully removed " << fullpath << llendl;
				}
				break;
			}			
		}
		count++;
	}
	return count;
}