BOOL
pthread_win32_process_attach_np ()
{
  BOOL result = TRUE;

  result = ptw32_processInitialize ();
#ifdef _UWIN
  pthread_count++;
#endif

#ifndef TEST_ICE

  /*
   * Load KERNEL32 and try to get address of InterlockedCompareExchange
   */
  ptw32_h_kernel32 = LoadLibrary(TEXT("KERNEL32.DLL"));

  ptw32_interlocked_compare_exchange =
    (PTW32_INTERLOCKED_LONG (WINAPI *)(PTW32_INTERLOCKED_LPLONG, PTW32_INTERLOCKED_LONG, PTW32_INTERLOCKED_LONG))
#if defined(NEED_UNICODE_CONSTS)
    GetProcAddress(ptw32_h_kernel32,
                   (const TCHAR *)TEXT("InterlockedCompareExchange"));
#else
    GetProcAddress(ptw32_h_kernel32,
                   (LPCSTR) "InterlockedCompareExchange");
#endif

  if (ptw32_interlocked_compare_exchange == NULL)
    {
      ptw32_interlocked_compare_exchange = ptw32_InterlockedCompareExchange;

      /*
       * If InterlockedCompareExchange is not being used, then free
       * the kernel32.dll handle now, rather than leaving it until
       * DLL_PROCESS_DETACH.
       *
       * Note: this is not a pedantic exercise in freeing unused
       * resources!  It is a work-around for a bug in Windows 95
       * (see microsoft knowledge base article, Q187684) which
       * does Bad Things when FreeLibrary is called within
       * the DLL_PROCESS_DETACH code, in certain situations.
       * Since w95 just happens to be a platform which does not
       * provide InterlockedCompareExchange, the bug will be
       * effortlessly avoided.
       */
      (void) FreeLibrary(ptw32_h_kernel32);
      ptw32_h_kernel32 = 0;
    }

#else /* TEST_ICE */

  ptw32_interlocked_compare_exchange = ptw32_InterlockedCompareExchange;

#endif /* TEST_ICE */

  return result;
}
Ejemplo n.º 2
0
int main(int argc, char *argv[]) {
#ifdef __MINGW32__
	ptw32_processInitialize();
	//ptw32_processTerminate();
#endif

	printf("test SDLMOD_TIMER\n");
	if (SDLMOD_TimerInit() != 0)
	{
		fprintf(stderr, "SDLMOD_TimerInit failed\n");
		return 0;
	}
	SDLMOD_AddTimer(TEST_DELAY, test_timer, "hello");
	
	while(1)
	{
		SDLMOD_Delay(100);
	}
	
	SDLMOD_TimerQuit();
	return 0;
}
BOOL
pthread_win32_process_attach_np ()
{
  TCHAR QuserExDLLPathBuf[1024];
  BOOL result = TRUE;
  const UINT QuserExDLLPathBufSize = sizeof(QuserExDLLPathBuf) / sizeof(QuserExDLLPathBuf[0]);

  result = ptw32_processInitialize ();

#if defined(_UWIN)
  pthread_count++;
#endif

#if defined(__GNUC__)
  ptw32_features = 0;
#else
  /*
   * This is obsolete now.
   */
  ptw32_features = PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE;
#endif

  /*
   * Load QUSEREX.DLL and try to get address of QueueUserAPCEx.
   * Because QUSEREX.DLL requires a driver to be installed we will
   * assume the DLL is in the system directory.
   *
   * This should take care of any security issues.
   */
#if defined(__GNUC__) || defined(PTW32_CONFIG_MSVC7)
  if(GetSystemDirectory(QuserExDLLPathBuf, QuserExDLLPathBufSize))
  {
    (void) strncat(QuserExDLLPathBuf,
                   "\\QUSEREX.DLL",
                   QuserExDLLPathBufSize - strlen(QuserExDLLPathBuf) - 1);
    ptw32_h_quserex = LoadLibrary(QuserExDLLPathBuf);
  }
#else
  /* strncat is secure - this is just to avoid a warning */
  if(GetSystemDirectory(QuserExDLLPathBuf, QuserExDLLPathBufSize) &&
     0 == _tcsncat_s(QuserExDLLPathBuf, QuserExDLLPathBufSize, _T("\\QUSEREX.DLL"), 12))
  {
    ptw32_h_quserex = LoadLibrary(QuserExDLLPathBuf);
  }
#endif

  if (ptw32_h_quserex != NULL)
    {
      ptw32_register_cancellation = (DWORD (*)(PAPCFUNC, HANDLE, DWORD))
#if defined(NEED_UNICODE_CONSTS)
	GetProcAddress (ptw32_h_quserex,
			(const TCHAR *) TEXT ("QueueUserAPCEx"));
#else
	GetProcAddress (ptw32_h_quserex, (LPCSTR) "QueueUserAPCEx");
#endif
    }

  if (NULL == ptw32_register_cancellation)
    {
      ptw32_register_cancellation = ptw32_Registercancellation;

      if (ptw32_h_quserex != NULL)
	{
	  (void) FreeLibrary (ptw32_h_quserex);
	}
      ptw32_h_quserex = 0;
    }
  else
    {
      /* Initialise QueueUserAPCEx */
      BOOL (*queue_user_apc_ex_init) (VOID);

      queue_user_apc_ex_init = (BOOL (*)(VOID))
#if defined(NEED_UNICODE_CONSTS)
	GetProcAddress (ptw32_h_quserex,
			(const TCHAR *) TEXT ("QueueUserAPCEx_Init"));
#else
	GetProcAddress (ptw32_h_quserex, (LPCSTR) "QueueUserAPCEx_Init");
#endif

      if (queue_user_apc_ex_init == NULL || !queue_user_apc_ex_init ())
	{
	  ptw32_register_cancellation = ptw32_Registercancellation;

	  (void) FreeLibrary (ptw32_h_quserex);
	  ptw32_h_quserex = 0;
	}
    }

  if (ptw32_h_quserex)
    {
      ptw32_features |= PTW32_ALERTABLE_ASYNC_CANCEL;
    }

  return result;
}
BOOL
pthread_win32_process_attach_np ()
{
    BOOL result = TRUE;

    result = ptw32_processInitialize ();
#ifdef _UWIN
    pthread_count++;
#endif

    ptw32_features = 0;

#ifndef TEST_ICE

    /*
     * Load KERNEL32 and try to get address of InterlockedCompareExchange
     */
    ptw32_h_kernel32 = LoadLibrary (TEXT ("KERNEL32.DLL"));

    ptw32_interlocked_compare_exchange =
        (PTW32_INTERLOCKED_LONG (WINAPI *)
         (PTW32_INTERLOCKED_LPLONG, PTW32_INTERLOCKED_LONG,
          PTW32_INTERLOCKED_LONG))
#if defined(NEED_UNICODE_CONSTS)
        GetProcAddress (ptw32_h_kernel32,
                        (const TCHAR *) TEXT ("InterlockedCompareExchange"));
#else
        GetProcAddress (ptw32_h_kernel32, (LPCSTR) "InterlockedCompareExchange");
#endif

    if (ptw32_interlocked_compare_exchange == NULL)
    {
        ptw32_interlocked_compare_exchange = ptw32_InterlockedCompareExchange;

        /*
         * If InterlockedCompareExchange is not being used, then free
         * the kernel32.dll handle now, rather than leaving it until
         * DLL_PROCESS_DETACH.
         *
         * Note: this is not a pedantic exercise in freeing unused
         * resources!  It is a work-around for a bug in Windows 95
         * (see microsoft knowledge base article, Q187684) which
         * does Bad Things when FreeLibrary is called within
         * the DLL_PROCESS_DETACH code, in certain situations.
         * Since w95 just happens to be a platform which does not
         * provide InterlockedCompareExchange, the bug will be
         * effortlessly avoided.
         */
        (void) FreeLibrary (ptw32_h_kernel32);
        ptw32_h_kernel32 = 0;
    }
    else
    {
        ptw32_features |= PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE;
    }

#else /* TEST_ICE */

    ptw32_interlocked_compare_exchange = ptw32_InterlockedCompareExchange;

#endif /* TEST_ICE */

    /*
     * Load QUSEREX.DLL and try to get address of QueueUserAPCEx
     */
    ptw32_h_quserex = LoadLibrary (TEXT ("QUSEREX.DLL"));

    if (ptw32_h_quserex != NULL)
    {
        ptw32_register_cancelation = (DWORD (*)(PAPCFUNC, HANDLE, DWORD))
#if defined(NEED_UNICODE_CONSTS)
                                     GetProcAddress (ptw32_h_quserex,
                                             (const TCHAR *) TEXT ("QueueUserAPCEx"));
#else
                                     GetProcAddress (ptw32_h_quserex, (LPCSTR) "QueueUserAPCEx");
#endif
    }

    if (NULL == ptw32_register_cancelation)
    {
        ptw32_register_cancelation = ptw32_RegisterCancelation;

        if (ptw32_h_quserex != NULL)
        {
            (void) FreeLibrary (ptw32_h_quserex);
        }
        ptw32_h_quserex = 0;
    }
    else
    {
        /* Initialise QueueUserAPCEx */
        BOOL (*queue_user_apc_ex_init) (VOID);

        queue_user_apc_ex_init = (BOOL (*)(VOID))
#if defined(NEED_UNICODE_CONSTS)
                                 GetProcAddress (ptw32_h_quserex,
                                         (const TCHAR *) TEXT ("QueueUserAPCEx_Init"));
#else
                                 GetProcAddress (ptw32_h_quserex, (LPCSTR) "QueueUserAPCEx_Init");
#endif

        if (queue_user_apc_ex_init == NULL || !queue_user_apc_ex_init ())
        {
            ptw32_register_cancelation = ptw32_RegisterCancelation;

            (void) FreeLibrary (ptw32_h_quserex);
            ptw32_h_quserex = 0;
        }
    }

    if (ptw32_h_quserex)
    {
        ptw32_features |= PTW32_ALERTABLE_ASYNC_CANCEL;
    }

    return result;
}
Ejemplo n.º 5
0
int main(int argc, char *argv[]) {
	int exit_code = 0;
	slimproto_t slimproto;
	slimaudio_t slimaudio;

	PaDeviceIndex output_device_id = PA_DEFAULT_DEVICE;
	char *output_device_name = NULL;
	char *hostapi_name = NULL;

	unsigned int output_predelay = 0;
	unsigned int output_predelay_amplitude = 0;
#ifdef EMPEG
	bool power_bypass = false, power_last = false;
	bool geteq = false;
	long key, ir;
#endif
#ifdef EMPEG
	slimaudio_volume_t volume_control = VOLUME_DRIVER;
#else
	slimaudio_volume_t volume_control = VOLUME_SOFTWARE;
#endif
	unsigned int retry_interval = RETRY_DEFAULT;

	char macaddress[6] = { 0, 0, 0, 0, 0, 1 };

	int keepalive_interval = -1;

	bool listdevs = false;
	bool listservers = false;
	bool discover_server = false;
	unsigned int json_port;

#ifdef SLIMPROTO_ZONES
	bool default_macaddress = true;
	unsigned int zone = 0;
	unsigned int num_zones = 1;
#endif
#ifdef DAEMONIZE
	bool should_daemonize = false;
	char *logfile = NULL;
#endif
#ifdef PORTAUDIO_DEV
	/* User suggested latency */
	bool modify_latency = false;
	unsigned int user_latency = 0L;
#endif
	char slimserver_address[INET_FQDNSTRLEN] = "127.0.0.1";

	char getopt_options[OPTLEN] = "a:FId:Y:e:f:hk:Lm:n:o:P:p:Rr:TO:Vv:";

	static struct option long_options[] = {
		{"predelay_amplitude", required_argument, 0, 'a'},
		{"discover",           no_argument,       0, 'F'},
		{"debug",              required_argument, 0, 'd'},
		{"debuglog",           required_argument, 0, 'Y'},
		{"help",               no_argument,       0, 'h'},
		{"keepalive",          required_argument, 0, 'k'},
		{"list",               no_argument,       0, 'L'},
		{"findservers",        no_argument,       0, 'I'},
		{"mac",	               required_argument, 0, 'm'},
		{"name",               required_argument, 0, 'n'},
		{"output",             required_argument, 0, 'o'},
		{"playerid",           required_argument, 0, 'e'},
		{"firmware",           required_argument, 0, 'f'},
		{"port",               required_argument, 0, 'P'},
		{"predelay",           required_argument, 0, 'p'},
		{"threshold_override", no_argument,       0, 'T'},
		{"output_threshold",   required_argument, 0, 'O'},
#ifdef EMPEG
		{"puteq",              no_argument,       0, 'Q'},
		{"geteq",              no_argument,       0, 'q'},
#endif
		{"retry",              no_argument,       0, 'R'},
		{"intretry",           required_argument, 0, 'r'},
		{"version",            no_argument,       0, 'V'},
		{"volume",             required_argument, 0, 'v'},
		{"zone",               required_argument, 0, 'z'},
#ifdef PORTAUDIO_DEV
		{"latency",            required_argument, 0, 'y'},
		{"audiotype",          required_argument, 0, 't'},
#else
		{"paframes",           required_argument, 0, 'g'},
		{"pabuffers",          required_argument, 0, 'j'},
#endif
#ifdef DAEMONIZE
		{"daemonize",          required_argument, 0, 'M'},
#endif
#ifdef __WIN32__
		{"highpriority",       no_argument,       0, 'H'},
#ifdef PADEV_WASAPI
		{"shared",             no_argument,       0, 'S'},
#endif
#endif
#ifdef INTERACTIVE
		{"lircrc",             required_argument, 0, 'c'},
		{"lirc",               no_argument,       0, 'i'},
		{"lcd",                no_argument,       0, 'l'},
		{"lcdc",               no_argument,       0, 'C'},
		{"display",            no_argument,       0, 'D'},
		{"width",              required_argument, 0, 'w'},
#endif
#ifdef SLIMPROTO_RENICE
		{"renice",             no_argument,       0, 'N'},
#endif
#ifdef SLIMPROTO_ZONES
		{"zone",               required_argument, 0, 'z'},
#endif
		{0, 0, 0, 0}
	};

#ifdef INTERACTIVE
        fd_set read_fds;
        fd_set write_fds;
        int key = 0;
        unsigned long ir = 0;
	int maxfd = 0;
	char *home;
	struct timeval timeout;
	timeout.tv_usec = 0;

#ifdef __WIN32__
	int WSAerrno;
	int ptw32_processInitialize (void);
	ptw32_processInitialize();
#endif /* __WIN32__ */
        /* default lircrc file ($HOME/.lircrc) */
	home = getenv("HOME");
	if (home == NULL) home = "";
	lircrc = (char *)malloc((strlen(home) + strlen("/.lircrc") + 1) * sizeof(char));
	strcpy(lircrc,home);
	strcat(lircrc,"/.lircrc");
#endif /* INTERACTIVE */

#ifdef EMPEG
	strcat (getopt_options, "Qq");
#endif
#ifdef PORTAUDIO_DEV
	strcat (getopt_options, "y:t:");
#else
	strcat (getopt_options, "g:j:");
#endif	
#ifdef DAEMONIZE	
	strcat (getopt_options, "M:");
#endif
#ifdef INTERACTIVE
	strcat (getopt_options, "c:CDilw:");
#endif
#ifdef __WIN32__
	strcat (getopt_options, "H");
#ifdef PADEV_WASAPI
	strcat (getopt_options, "S");
#endif
#endif
#ifdef SLIMPROTO_RENICE
	strcat (getopt_options, "N");
#endif
#ifdef SLIMPROTO_ZONES
	strcat (getopt_options, "z:");
#endif
#ifdef EMPEG
	empeg_getmac(macaddress);
#endif

	while (true) {
		const char shortopt =
			getopt_long_only(argc, argv, getopt_options, long_options, NULL);

		if (shortopt == (char) -1) {
			break;
		}

		switch (shortopt) {
		case 'a':
			output_predelay_amplitude = strtoul(optarg, NULL, 0);
			break;
		case 'F':
			discover_server = true;
			break;
		case 'd':
#ifdef SLIMPROTO_DEBUG
			if (strcmp(optarg, "all") == 0)
			{
				slimproto_debug = true;
				slimaudio_debug = true;
				slimaudio_buffer_debug = true;
				slimaudio_buffer_debug_v = true;
				slimaudio_decoder_debug = true;
				slimaudio_decoder_debug_r = true;
				slimaudio_decoder_debug_v = true;
				slimaudio_http_debug = true;
				slimaudio_http_debug_v = true;
				slimaudio_output_debug = true;
				slimaudio_output_debug_v = true;
			}
			else if (strcmp(optarg, "slimproto") == 0)
				slimproto_debug = true;
			else if (strcmp(optarg, "slimaudio") == 0)
				slimaudio_debug = true;
			else if (strcmp(optarg, "slimaudio_buffer") == 0)
				slimaudio_buffer_debug = true;
			else if (strcmp(optarg, "slimaudio_buffer_v") == 0)
				slimaudio_buffer_debug_v = true;
			else if (strcmp(optarg, "slimaudio_decoder") == 0)
				slimaudio_decoder_debug = true;
			else if (strcmp(optarg, "slimaudio_decoder_r") == 0)
				slimaudio_decoder_debug_r = true;
			else if (strcmp(optarg, "slimaudio_decoder_v") == 0)
				slimaudio_decoder_debug_v = true;
			else if (strcmp(optarg, "slimaudio_http") == 0)
				slimaudio_http_debug = true;
			else if (strcmp(optarg, "slimaudio_http_v") == 0)
				slimaudio_http_debug_v = true;
			else if (strcmp(optarg, "slimaudio_output") == 0)
				slimaudio_output_debug = true;
			else if (strcmp(optarg, "slimaudio_output_v") == 0)
				slimaudio_output_debug_v = true;
			else
				fprintf(stderr, "%s: Unknown debug option %s\n", argv[0], optarg);
#else
				fprintf(stderr, "%s: Recompile with -DSLIMPROTO_DEBUG to enable debugging.\n", argv[0]);
#endif
			break;
		case 'Y':
#ifdef SLIMPROTO_DEBUG
                        if ( optarg == NULL )
                        {
                                fprintf(stderr, "%s: Cannot parse debug log filename %s\n", argv[0], optarg);
                                exit(-1);
                        } else
                        {
				debuglog = freopen( optarg, "a", stderr);
				if ( debuglog )
					debug_logfile = true;
				else
					fprintf(stderr, "%s: Redirection of stderr to %s failed.\n", argv[0], optarg);
                        }
#endif
			break;

/* From server/Slim/Networking/Slimproto.pm from 7.5r28596
** squeezebox(2)
** softsqueeze(3)
** squeezebox2(4)
** transporter(5)
** softsqueeze3(6)
** receiver(7)
** squeezeslave(8)
** controller(9)
** boom(10)
** softboom(11)
** squeezeplay(12)
** radio(13)
** touch(14)
*/
		case 'e':
			player_type = strtoul(optarg, NULL, 0);
			if ( (player_type < 2) || (player_type > 14) )
			{
				player_type = PLAYER_TYPE;
				fprintf(stderr, "%s: Unknown player type, using (%d)\n", argv[0], player_type);
			}
			break;
		case 'f':
			firmware = strtoul(optarg, NULL, 0);
			if ( (firmware < 0) || (firmware > 254) )
			{
				firmware = FIRMWARE_VERSION;
				fprintf(stderr, "%s: Invalid firmware value, using (%d)\n", argv[0], firmware);
			}
			break;
		case 'h':
			print_help();
			exit(0);	
		case 'k':
			keepalive_interval = strtoul(optarg, NULL, 0);
			break;
		case 'T':
			threshold_override = true;
			break;
		case 'O':
			output_threshold = strtoul(optarg, NULL, 0);
			if ( (output_threshold < 0) || (output_threshold > 1000000) )
			{
				output_threshold = OUTPUT_THRESHOLD;
				fprintf(stderr, "%s: Invalid output threshold, using (%d)\n",
					argv[0], output_threshold);
			}
			break;
		case 'm':
			if (parse_macaddress(macaddress, optarg) != 0) {
				fprintf(stderr, "%s: Cannot parse mac address %s\n", argv[0], optarg);
				exit(-1);	
			}
#ifdef SLIMPROTO_ZONES
			default_macaddress = false;
#endif
			break;
#ifdef DAEMONIZE
		case 'M':
			if ( optarg == NULL )
			{
				fprintf(stderr, "%s: Cannot parse log filename %s\n", argv[0], optarg);
				exit(-1);	
			} else
			{
				logfile = optarg;
			}
			should_daemonize = true;
			break;
#endif

#ifdef __WIN32__
		case 'H':
			/* Change Window process priority class to HIGH */
			if ( !SetPriorityClass ( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
			{
				int dwError = GetLastError();
				fprintf(stderr, "%s: Failed to set priority (%d), using default.\n", argv[0],
					dwError);
			} 
			break;
#ifdef PADEV_WASAPI
		case 'S':
			wasapi_exclusive = false;
			break;
#endif
#endif
#ifdef SLIMPROTO_RENICE
		case 'N':
			renice = true;
			break;
#endif
		case 'n':
			output_device_name = optarg;
			output_change = true;
			break;
		case 'o':
			output_device_id = strtoul(optarg, NULL, 0);
			output_change = true;
			break;
		case 'p':
			output_predelay = strtoul(optarg, NULL, 0);
			break;
		case 'P':
			port = strtoul(optarg, NULL, 0);
			if ( (port < 0) || (port > 65535) )
			{
				port = SLIMPROTOCOL_PORT;
				fprintf(stderr, "%s: Invalid port number, using %d.\n", argv[0], port);
			}
			break;
			break;
#ifdef EMPEG
		case 'Q':
			empeg_puteq_tofile();
			exit(0);
			break;
		case 'q':
			geteq = true;
			break;
#endif
		case 'R':
			retry_connection = true;
			break;
		case 'r':
			retry_connection = true;
			retry_interval = strtoul(optarg, NULL, 0);
			if ( ( retry_interval < 1 ) || ( retry_interval > 120 ) )
			{
				retry_interval = RETRY_DEFAULT;
				fprintf (stderr, "Invalid retry interval, using %d seconds.\n", retry_interval );
			}
			break;
#ifdef INTERACTIVE
		case 'c':
		        free(lircrc);
			lircrc = optarg;
			break;
#ifndef __WIN32__
		case 'i':
			using_lirc = true;
			break;
		case 'l':
			use_lcdd_menu = true;
			break;
		case 'C':
			use_lcdd_menu = true;
			lcdd_compat = true;
			break;
#endif
		case 'D':
			using_curses = 1;
			break;
		case 'w':
			linelen = strtoul(optarg, NULL, 0);
			break;
#endif
		case 'L':
			listdevs = true;
			break;
		case 'I':
			listservers = true;
			break;
		case 'V':
			print_version();
			exit(0);
			break;
		case 'v':
		 	if (strcmp(optarg, "sw") == 0) {
				volume_control = VOLUME_SOFTWARE;
			}
#ifndef PORTAUDIO_DEV
			else if (strcmp(optarg, "on") == 0 ) {
				volume_control = VOLUME_DRIVER;
			}
#endif
			else if (strcmp(optarg, "off") == 0 ) {
				volume_control = VOLUME_NONE;
			}
			break;
#ifdef PORTAUDIO_DEV
		case 'y':
			modify_latency = true;
			user_latency = strtoul(optarg, NULL, 0);

			if ( user_latency > 1000 )
			{
				fprintf (stderr, "Suggested latency invalid, using device default.\n");
				modify_latency = false;
			}
			break;
		case 't':
			hostapi_name = optarg;
			break;
#else
		case 'g':
			pa_framesPerBuffer = strtoul(optarg, NULL, 0);

			if ( (pa_framesPerBuffer > 65536) || (pa_framesPerBuffer < 64) )
			{
				fprintf (stderr,
					"Portaudio frames per buffer invalid, using default (%d).\n",
					PA_FRAMES_PER_BUFFER);
				pa_framesPerBuffer = PA_FRAMES_PER_BUFFER ;
			}
			break;
		case 'j':
			pa_numberOfBuffers = strtoul(optarg, NULL, 0);

			if ( (pa_numberOfBuffers > 64) || (pa_numberOfBuffers < 0) )
			{
				fprintf (stderr,
					"Number of Portaudio buffers invalid, using default (%d).\n",
					PA_NUM_BUFFERS);
				pa_numberOfBuffers = PA_NUM_BUFFERS;
			}
			break;
#endif
#ifdef SLIMPROTO_ZONES
		case 'z':
			if (sscanf(optarg, "%u/%u", &zone, &num_zones) != 2)
			{
				fprintf (stderr, "Invalid zone specification, using default.\n");
			}
			if (num_zones > MAX_ZONES)
			{
				fprintf(stderr, "Number of zones > %d not supported\n", MAX_ZONES);
				zone=0;
				num_zones=1;
			}
			if (num_zones <= zone)
			{
				fprintf (stderr, "Invalid zone specification, using default.\n");
				zone = 0;
				num_zones = 1;
			}
			break;
#endif
		default:
			break;
		}
	}

	if (listdevs) {
		GetAudioDevices(output_device_id, output_device_name, hostapi_name, output_change, true);
		exit(0);
	}

	if (listservers) {
		slimproto_discover(slimserver_address, sizeof(slimserver_address), port, &json_port, true);
		exit(0);
	}

	if (optind < argc)
		strncpy(slimserver_address, argv[optind], sizeof(slimserver_address));

#ifdef DAEMONIZE
	if ( should_daemonize ) {
#ifdef INTERACTIVE
		if ( using_curses || use_lcdd_menu )
		{
			fprintf(stderr, "Daemonize not supported with display modes.\n");
			exit(-1);
		}
		else
#endif
			init_daemonize();
	}
#endif
	signal(SIGTERM, &exit_handler);
	signal(SIGINT, &exit_handler);
	install_restart_handler();

#ifdef INTERACTIVE
	install_toggle_handler();  /*SIGUSR2 to toggle IR/LCD on and off */
#endif
	if (slimproto_init(&slimproto) < 0) {
		fprintf(stderr, "Failed to initialize slimproto\n");
		exit(-1);	
	}

#ifdef SLIMPROTO_ZONES
	if (slimaudio_init(&slimaudio, &slimproto, output_device_id, output_device_name,
		hostapi_name, output_change, zone, num_zones) < 0)
#else
	if (slimaudio_init(&slimaudio, &slimproto, output_device_id, output_device_name,
		hostapi_name, output_change) < 0)
#endif
	{
		fprintf(stderr, "Failed to initialize slimaudio\n");
		exit(-1);
	}
#ifdef SLIMPROTO_ZONES
	if (default_macaddress)
		macaddress[5] += zone;
#endif
#ifdef PORTAUDIO_DEV
	if( modify_latency ) {
		slimaudio_set_latency( &slimaudio, user_latency );
	}
#endif	
	slimaudio_set_renice( &slimaudio, renice );
	slimproto_add_connect_callback(&slimproto, connect_callback, macaddress);

#ifdef INTERACTIVE
	/* Process VFD (display) commands */
	if ( using_curses || using_lirc || use_lcdd_menu )
		slimproto_add_command_callback(&slimproto, "vfdc", vfd_callback, macaddress);
#endif
#ifdef EMPEG
	slimproto_add_command_callback(&slimproto, "grfe", empeg_vfd_callback, macaddress);
	slimproto_add_command_callback(&slimproto, "grfb", empeg_vfdbrt_callback, macaddress);
	slimproto_add_command_callback(&slimproto, "aude", empeg_aude_callback, macaddress);
#endif

	slimaudio_set_volume_control(&slimaudio, volume_control);
	slimaudio_set_output_predelay(&slimaudio, output_predelay, output_predelay_amplitude);

	if (keepalive_interval >= 0) {
		slimaudio_set_keepalive_interval(&slimaudio, keepalive_interval);
	}

#ifdef INTERACTIVE
	init_lcd();
#endif
#ifdef EMPEG
	empeg_init();
	if (geteq)
	   empeg_geteq_fromfile();
	power_last = empeg_state.power_on;
	empeg_state.power_on = false;
#endif

	if (slimaudio_open(&slimaudio) < 0) {
		fprintf(stderr, "Failed to open slimaudio\n");
		exit_code = -1;
		goto exit;
	}

#ifdef SLIMPROTO_DEBUG
	if (slimaudio_debug)
		fprintf ( stderr, "Using audio device index: %d\n", slimaudio.output_device_id );
#endif

#ifdef INTERACTIVE
        init_lirc();

	setlocale(LC_ALL, "");
	initcurses();
#endif
#ifdef DAEMONIZE
	if ( should_daemonize ) {
		daemonize(logfile);
	}
#endif
	/* When retry_connection is true, retry connecting to Squeezebox Server 
	** until we succeed, unless the signal handler tells us to give up.
	*/
	do {
		if (signal_restart_flag) { 
#ifdef INTERACTIVE
			exitcurses();
#endif
			fprintf(stderr,"Retry in %d seconds.\n", retry_interval);
			Pa_Sleep(1000 * retry_interval);
#ifdef INTERACTIVE
	   	        initcurses();
#endif
		}
#ifdef EMPEG
		if (discover_server && empeg_state.last_server[0] != '\0')
		{
			strcpy(slimserver_address, (char *)empeg_state.last_server);
			empeg_state.last_server[0] = '\0';
		}
		else
#endif
		if (discover_server && slimproto_discover(slimserver_address,
			sizeof(slimserver_address), port, &json_port, false) < 0)
		{
			fprintf(stderr,"Discover failed.\n");
			if (!retry_connection) {
				exit_code = -1;
				goto exit;
			}
			signal_restart_flag = true;
			continue;
		}

		if (slimproto_connect(
			&slimproto, slimserver_address, port) < 0) {
			fprintf(stderr, "Connection to Squeezebox Server %s failed.\n", slimserver_address);
			if (!retry_connection) {
				exit_code = -1;
				goto exit;
			}
			signal_restart_flag = true;
			continue;
		}
		signal_restart_flag = false;
		discover_server = false;
#ifdef EMPEG
		strcpy((char *)empeg_state.last_server, slimserver_address);
		if (power_last)
			while (!empeg_state.power_on)
			{
				Pa_Sleep(100);
				slimproto_ir(&slimproto, 1, 1, 0x76898F70);
			}
#endif
                while (!signal_exit_flag && !signal_restart_flag) {
#ifdef EMPEG
		   int rc = empeg_idle();
		   if (power_bypass)
		   {
		      if (rc == 0 || !empeg_state.power_on)
		      {
		         power_last = false;
		         power_bypass = false;
		      }
		   }
		   else if (rc == -1)
		   {
		      fprintf(stderr, "Power loss detected.\n");
		      power_last = empeg_state.power_on;
                      slimproto_ir(&slimproto, 1, 1, 0x76898778);
		      while (empeg_state.power_on)
		         Pa_Sleep(250);
		   }
		   else if (rc == -2 && empeg_state.power_on)
		   {
		      fprintf(stderr, "Manual override, aborting power down.\n");
		      power_bypass = true;
		   }
		   else if (rc == -3)
		   {
		      fprintf(stderr, "Power restored.\n");
		      if (power_last)
                         slimproto_ir(&slimproto, 1, 1, 0x76898F70);
		   }
		   else if (rc == -4)
		   {
		      fprintf(stderr, "Powering down.\n");
		      slimproto_goodbye(&slimproto, 0x00);
		      Pa_Sleep(400);
		      slimproto_close(&slimproto);
		      empeg_state.power_on = power_last;
		      empeg_poweroff();
		      signal_restart_flag = true;
		   }
#endif
#ifdef INTERACTIVE
                   if (using_curses == 1 || use_lcdd_menu || using_lirc) {
                      FD_ZERO(&read_fds);
                      FD_ZERO(&write_fds);
		      if (using_curses == 1)
     	                 FD_SET(0, &read_fds); /* watch stdin */
   	              if  (use_lcdd_menu) {
		         FD_SET(lcd_fd, &read_fds); 
		         maxfd = lcd_fd;
		      }
   	              if (using_lirc) {
		         FD_SET(lirc_fd, &read_fds); 
                         if (lirc_fd > maxfd) 
		            maxfd = lirc_fd;
                      }
		      timeout.tv_sec = 5;
                      if(select(maxfd + 1, &read_fds, NULL, NULL, &timeout) == -1) {
#ifndef __WIN32__
    	                 if (errno != EINTR)
			 {
		           fprintf(stderr,"Select Error:%d\n", errno);
#else
			 WSAerrno = WSAGetLastError();
			 if ( (WSAerrno != WSAEINTR) && (WSAerrno != WSAENOTSOCK) )
			 {	
		           fprintf(stderr,"Select Error:%d\n", WSAerrno);
#endif
   	                   abort();
	                 }
#ifdef __WIN32__
			 else
				 WaitForSingleObject( GetStdHandle(STD_INPUT_HANDLE), 5000 );
#endif
                      }
		      if (FD_ISSET(0, &read_fds)) {
                         while ((key = getch()) != ERR) {
                            ir = getircode(key);
	                    if (ir == (unsigned long) 0x01) {
  		               signal_exit_flag = 1;
                            }else{
			       if (ir != 0) slimproto_ir(&slimproto, 1, 1, ir);
			    }
		         }
		      } 
		      if (using_lirc && FD_ISSET(lirc_fd, &read_fds)) {
                         while((key = read_lirc()) != 0 ) { 
                            ir = getircode(key);
	                    if (ir == 0x01) { 
  		               signal_exit_flag = 1;
                            } else {
			       if (ir != 0) slimproto_ir(&slimproto, 1, 1, ir);
			    }
		         }
		      } 
		      if (use_lcdd_menu && FD_ISSET(lcd_fd, &read_fds)) {
                         while(read_lcd()); 
		      }
		   } else {
                      wait_for_restart_signal();
		   }
#else
#ifdef EMPEG
                   while ((key = empeg_getkey()) != -1)
                   {
                      ir = empeg_getircode(key);
                      if (ir != 0)
                         slimproto_ir(&slimproto, 1, 1, ir);
                   }
#else
                   wait_for_restart_signal();
#endif
#endif
		}
#ifdef INTERACTIVE
                FD_ZERO(&read_fds);
                FD_ZERO(&write_fds);
#endif
        } while (signal_restart_flag && !signal_exit_flag);

exit:
	slimaudio_close(&slimaudio);

	slimproto_goodbye(&slimproto, 0x00);

	/* Wait 200ms for BYE! message send to complete */
	Pa_Sleep(200);

	slimproto_close(&slimproto);

#ifdef INTERACTIVE
	exitcurses();
	close_lirc();
#endif

#if defined(EMPEG) || defined(INTERACTIVE)
	close_lcd();
#endif

#ifdef SLIMPROTO_DEBUG
	if (debug_logfile)
	{
		fclose (debuglog);
	}
#endif

	slimproto_destroy(&slimproto);
	slimaudio_destroy(&slimaudio);

	return exit_code;
} 
Ejemplo n.º 6
0
pthread_t
pthread_self (void)
     /*
      * ------------------------------------------------------
      * DOCPUBLIC
      *      This function returns a reference to the current running
      *      thread.
      *
      * PARAMETERS
      *      N/A
      *
      *
      * DESCRIPTION
      *      This function returns a reference to the current running
      *      thread.
      *
      * RESULTS
      *              pthread_t       reference to the current thread
      *
      * ------------------------------------------------------
      */
{
  pthread_t self;
  pthread_t nil = {NULL, 0};
  ptw32_thread_t * sp;

  if (!ptw32_processInitialize())
	return nil;

#if defined(_UWIN)
  if (!ptw32_selfThreadKey)
    return nil;
#endif

  sp = (ptw32_thread_t *) pthread_getspecific (ptw32_selfThreadKey);

  if (sp != NULL)
    {
      self = sp->ptHandle;
    }
  else
    {
      /*
       * Need to create an implicit 'self' for the currently
       * executing thread.
       */
      self = ptw32_new ();
      sp = (ptw32_thread_t *) self.p;

      if (sp != NULL)
	{
	  /*
	   * This is a non-POSIX thread which has chosen to call
	   * a POSIX threads function for some reason. We assume that
	   * it isn't joinable, but we do assume that it's
	   * (deferred) cancelable.
	   */
	  sp->implicit = 1;
	  sp->detachState = PTHREAD_CREATE_DETACHED;
	  sp->thread = GetCurrentThreadId ();

#if defined(NEED_DUPLICATEHANDLE)
	  /*
	   * DuplicateHandle does not exist on WinCE.
	   *
	   * NOTE:
	   * GetCurrentThread only returns a pseudo-handle
	   * which is only valid in the current thread context.
	   * Therefore, you should not pass the handle to
	   * other threads for whatever purpose.
	   */
	  sp->threadH = GetCurrentThread ();
#else
	  if (!DuplicateHandle (GetCurrentProcess (),
				GetCurrentThread (),
				GetCurrentProcess (),
				&sp->threadH,
				0, FALSE, DUPLICATE_SAME_ACCESS))
	    {
	      /*
	       * Should not do this, but we have no alternative if
	       * we can't get a Win32 thread handle.
	       * Thread structs are never freed.
	       */
		  sp->threadH = 0;
	      ptw32_threadReusePush (self);
	      /*
	       * As this is a win32 thread calling us and we have failed,
	       * return a value that makes sense to win32.
	       */
	      return nil;
	    }
#endif

	  /*
	   * No need to explicitly serialise access to sched_priority
	   * because the new handle is not yet public.
	   */
	  sp->sched_priority = GetThreadPriority (sp->threadH);
	  pthread_setspecific (ptw32_selfThreadKey, (void *) sp);
	}
    }

  return (self);
}				/* pthread_self */
Ejemplo n.º 7
0
int main(int argc, char *argv[]) {
	slimproto_t slimproto;
	slimaudio_t slimaudio;

	PaDeviceIndex output_device_id = PA_DEFAULT_DEVICE;

	unsigned int output_predelay = 0;
	unsigned int output_predelay_amplitude = 0;

	slimaudio_volume_t volume_control = VOLUME_SOFTWARE;

	unsigned int retry_interval = RETRY_DEFAULT;

	char macaddress[6] = { 0, 0, 0, 0, 0, 1 };

	int keepalive_interval = -1;

	bool listdevs = false;

#ifdef DAEMONIZE
	bool should_daemonize = false;
	char *logfile = NULL;
#endif


#ifdef INTERACTIVE
        fd_set read_fds;
        fd_set write_fds;
        int key = 0;
        unsigned long ir = 0;
	int maxfd = 0;
	char *home;
	struct timeval timeout;
	timeout.tv_usec = 0;

#ifdef __WIN32__
	int WSAerrno;
	int ptw32_processInitialize (void);
	ptw32_processInitialize();
#endif
        // default lircrc file ($HOME/.lircrc)
	home = getenv("HOME");
	if (home == NULL) home = "";
	lircrc = (char *)malloc((strlen(home) + strlen("/.lircrc") + 1) * sizeof(char));
	strcpy(lircrc,home);
	strcat(lircrc,"/.lircrc");
#endif

	char getopt_options[OPTLEN] = "a:d:Y:e:f:hk:Lm:o:P:p:Rr:Vv:";
	static struct option long_options[] = {
		{"predelay_amplitude", required_argument, 0, 'a'},
		{"debug",              required_argument, 0, 'd'},
		{"debuglog",           required_argument, 0, 'Y'},
		{"help",               no_argument,       0, 'h'},
		{"keepalive",          required_argument, 0, 'k'},
		{"list",               no_argument,       0, 'L'},
		{"mac",	               required_argument, 0, 'm'},
		{"output",             required_argument, 0, 'o'},
		{"playerid",           required_argument, 0, 'e'},
		{"firmware",           required_argument, 0, 'f'},
		{"port",               required_argument, 0, 'P'},
		{"predelay",           required_argument, 0, 'p'},
		{"retry",              no_argument,       0, 'R'},
		{"intretry",           required_argument, 0, 'r'},
		{"version",            no_argument,       0, 'V'},
		{"volume",             required_argument, 0, 'v'},
#ifdef PORTAUDIO_DEV
		{"latency",            required_argument, 0, 'y'},
#endif
#ifdef DAEMONIZE
		{"daemonize",          required_argument, 0, 'M'},
#endif
#ifdef __WIN32__
		{"highpriority",       no_argument,       0, 'H'},
#ifdef PA_WASAPI
		{"shared",             no_argument,       0, 'S'},
#endif
#endif
#ifdef INTERACTIVE
		{"lircrc",             required_argument, 0, 'c'},
		{"lirc",               no_argument,       0, 'i'},
		{"lcd",                no_argument,       0, 'l'},
		{"display",            no_argument,       0, 'D'},
		{"width",              required_argument, 0, 'w'},
#endif
		{0, 0, 0, 0}
	};
#ifdef PORTAUDIO_DEV
	strcat (getopt_options, "y:");
#endif	
#ifdef DAEMONIZE	
	strcat (getopt_options, "M:");
#endif
#ifdef INTERACTIVE
	strcat (getopt_options, "c:Dilw:");
#endif
#ifdef __WIN32__
	strcat (getopt_options, "H");
#ifdef PA_WASAPI
	strcat (getopt_options, "S");
#endif
#endif
	while (true) {
		const char shortopt =
			getopt_long_only(argc, argv, getopt_options, long_options, NULL);

		if (shortopt == (char) -1) {
			break;
		}

		switch (shortopt) {
		case 'a':
			output_predelay_amplitude = strtoul(optarg, NULL, 0);
			break;
		case 'd':
#ifdef SLIMPROTO_DEBUG
			if (strcmp(optarg, "all") == 0)
			{
				slimproto_debug = true;
				slimaudio_debug = true;
				slimaudio_buffer_debug = true;
				slimaudio_buffer_debug_v = true;
				slimaudio_decoder_debug = true;
				slimaudio_decoder_debug_r = true;
				slimaudio_decoder_debug_v = true;
				slimaudio_http_debug = true;
				slimaudio_http_debug_v = true;
				slimaudio_output_debug = true;
				slimaudio_output_debug_v = true;
			}
			else if (strcmp(optarg, "slimproto") == 0)
				slimproto_debug = true;
			else if (strcmp(optarg, "slimaudio") == 0)
				slimaudio_debug = true;
			else if (strcmp(optarg, "slimaudio_buffer") == 0)
				slimaudio_buffer_debug = true;
			else if (strcmp(optarg, "slimaudio_buffer_v") == 0)
				slimaudio_buffer_debug_v = true;
			else if (strcmp(optarg, "slimaudio_decoder") == 0)
				slimaudio_decoder_debug = true;
			else if (strcmp(optarg, "slimaudio_decoder_r") == 0)
				slimaudio_decoder_debug_r = true;
			else if (strcmp(optarg, "slimaudio_decoder_v") == 0)
				slimaudio_decoder_debug_v = true;
			else if (strcmp(optarg, "slimaudio_http") == 0)
				slimaudio_http_debug = true;
			else if (strcmp(optarg, "slimaudio_http_v") == 0)
				slimaudio_http_debug_v = true;
			else if (strcmp(optarg, "slimaudio_output") == 0)
				slimaudio_output_debug = true;
			else if (strcmp(optarg, "slimaudio_output_v") == 0)
				slimaudio_output_debug_v = true;
			else
				fprintf(stderr, "%s: Unknown debug option %s\n", argv[0], optarg);
#else
				fprintf(stderr, "%s: Recompile with -DSLIMPROTO_DEBUG to enable debugging.\n", argv[0]);
#endif
			break;
		case 'Y':
#ifdef SLIMPROTO_DEBUG
                        if ( optarg == NULL )
                        {
                                fprintf(stderr, "%s: Cannot parse debug log filename %s\n", argv[0], optarg);
                                exit(-1);
                        } else
                        {
				debuglog = freopen( optarg, "a", stderr);
				if ( debuglog )
					debug_logfile = true;
				else
					fprintf(stderr, "%s: Redirection of stderr to %s failed.\n", argv[0], optarg);
                        }
#endif
			break;

// From server/Slim/Networking/Slimproto.pm from 7.5r28596
// squeezebox(2)
// softsqueeze(3)
// squeezebox2(4)
// transporter(5)
// softsqueeze3(6)
// receiver(7)
// squeezeslave(8)
// controller(9)
// boom(10)
// softboom(11)
// squeezeplay(12)
// radio(13)
// touch(14)

		case 'e':
			player_type = strtoul(optarg, NULL, 0);
			if ( (player_type < 2) || (player_type > 14) )
			{
				player_type = PLAYER_TYPE;
				fprintf(stderr, "%s: Unknown player type, using (%d)\n", argv[0], player_type);
			}
			break;
		case 'f':
			firmware = strtoul(optarg, NULL, 0);
			if ( (firmware < 0) || (firmware > 254) )
			{
				firmware = FIRMWARE_VERSION;
				fprintf(stderr, "%s: Invalid firmware value, using (%d)\n", argv[0], firmware);
			}
			break;
		case 'h':
			print_help();
			exit(0);	
		case 'k':
			keepalive_interval = strtoul(optarg, NULL, 0);
			break;
		case 'm':
			if (parse_macaddress(macaddress, optarg) != 0) {
				fprintf(stderr, "%s: Cannot parse mac address %s\n", argv[0], optarg);
				exit(-1);	
			}
			break;
#ifdef DAEMONIZE
		case 'M':
			if ( optarg == NULL )
			{
				fprintf(stderr, "%s: Cannot parse log filename %s\n", argv[0], optarg);
				exit(-1);	
			} else
			{
				logfile = optarg;
			}
			should_daemonize = true;
			break;
#endif

#ifdef __WIN32__
		case 'H':
			/* Change Window process priority class to HIGH */
			if ( !SetPriorityClass ( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
			{
				int dwError = GetLastError();
				fprintf(stderr, "%s: Failed to set priority (%d), using default.\n", argv[0],
					dwError);
			} 
			break;
#ifdef PA_WASAPI
		case 'S':
			wasapi_exclusive = false;
			break;
#endif
#endif
		case 'o':
			output_device_id = strtoul(optarg, NULL, 0);
			output_change = true;
			break;
		case 'p':
			output_predelay = strtoul(optarg, NULL, 0);
			break;
		case 'P':
			port = strtoul(optarg, NULL, 0);
			if ( (port < 0) || (port > 65535) )
			{
				port = SLIMPROTOCOL_PORT;
				fprintf(stderr, "%s: Invalid port value, using (%d)\n", argv[0], port);
			}
			break;
			break;
		case 'R':
			retry_connection = true;
			break;
		case 'r':
			retry_connection = true;
			retry_interval = strtoul(optarg, NULL, 0);
			if ( retry_interval < 1 )
			{
				fprintf (stderr, "Retry option requires value in seconds.\n");
				exit(-1);
			}
			break;
#ifdef INTERACTIVE
		case 'c':
		        free(lircrc);
			lircrc = optarg;
			break;
#ifndef __WIN32__
		case 'i':
			using_lirc = true;
			break;
		case 'l':
			use_lcdd_menu = true;
			break;
#endif
		case 'D':
			using_curses = 1;
			break;
		case 'w':
			linelen = strtoul(optarg, NULL, 0);
			break;
#endif
		case 'L':
			listdevs = true;
			break;
		case 'V':
			print_version();
			exit(0);
			break;
		case 'v':
		 	if (strcmp(optarg, "sw") == 0) {
				volume_control = VOLUME_SOFTWARE;
			}
#ifndef PORTAUDIO_DEV
			else if (strcmp(optarg, "on") == 0 ) {
				volume_control = VOLUME_DRIVER;
			}
#endif
			else if (strcmp(optarg, "off") == 0 ) {
				volume_control = VOLUME_NONE;
			}
			break;
#ifdef PORTAUDIO_DEV
		case 'y':
			modify_latency = true;
			user_latency = strtoul(optarg, NULL, 0);

			if ( user_latency > 1000 )
			{
				fprintf (stderr, "Suggested latency invalid, using device default.\n");
				modify_latency = false;
			}
			break;
#endif
		default:
			break;
		}
	}

	if (listdevs) {
		GetAudioDevices(output_device_id, output_change, true);
		exit(0);
	}

#ifdef DAEMONIZE
	if ( should_daemonize ) {
#ifdef INTERACTIVE
		if ( using_curses || using_lirc || use_lcdd_menu )
		{
			fprintf(stderr, "Daemonize not supported with lirc or display modes.\n");
			exit(-1);
		}
		else
#endif
			init_daemonize();
	}
#endif

	char *slimserver_address = "127.0.0.1";
	if (optind < argc)
		slimserver_address = argv[optind];

	signal(SIGTERM, &exit_handler);
	install_restart_handler();

#ifdef INTERACTIVE
	install_toggle_handler();  //SIGUSR2 to toggle IR/LCD on and off
#endif
	if (slimproto_init(&slimproto) < 0) {
		fprintf(stderr, "Failed to initialize slimproto\n");
		exit(-1);	
	}

	if (slimaudio_init(&slimaudio, &slimproto, output_device_id, output_change) < 0) {
		fprintf(stderr, "Failed to initialize slimaudio\n");
		exit(-1);
	}

	slimproto_add_connect_callback(&slimproto, connect_callback, macaddress);

#ifdef INTERACTIVE
	// Process VFD (display) commands
	if ( using_curses || using_lirc || use_lcdd_menu )
		slimproto_add_command_callback(&slimproto, "vfdc", vfd_callback, macaddress);
#endif

	slimaudio_set_volume_control(&slimaudio, volume_control);
	slimaudio_set_output_predelay(&slimaudio, output_predelay, output_predelay_amplitude);

	if (keepalive_interval >= 0) {
		slimaudio_set_keepalive_interval(&slimaudio, keepalive_interval);
	}

#ifdef INTERACTIVE
	init_lcd();
#endif

	if (slimaudio_open(&slimaudio) < 0) {
		fprintf(stderr, "Failed to open slimaudio\n");
#ifdef INTERACTIVE
		close (lcd_fd);
#endif
		exit(-1);
	}

#ifdef SLIMPROTO_DEBUG
	if (slimaudio_debug)
		fprintf ( stderr, "Using audio device index: %d\n", slimaudio.output_device_id );
#endif

#ifdef INTERACTIVE
        init_lirc();

	setlocale(LC_ALL, "");
	initcurses();
#endif
#ifdef DAEMONIZE
	if ( should_daemonize ) {
		daemonize(logfile);
	}
#endif
	// When retry_connection is true, retry connecting to Squeezebox Server 
	// until we succeed, unless the signal handler tells us to give up.
	do {
		while (slimproto_connect(
			&slimproto, slimserver_address, port) < 0) {
			if (!retry_connection || signal_exit_flag) {
				if (signal_exit_flag) {
					// No message when the exit is triggered
					// by the user.
#ifdef INTERACTIVE
					exitcurses();
					close_lirc();
					close_lcd();
#endif
					exit(0);
				}
#ifdef INTERACTIVE
				exitcurses();
				close_lirc();
				close_lcd();
#endif
				fprintf(stderr, "Connection to Squeezebox Server %s failed.\n", slimserver_address);
				exit(-1);
			}
#ifdef INTERACTIVE
			exitcurses();
#endif
			fprintf(stderr,"Retry in %d seconds.\n", retry_interval);
			Pa_Sleep(1000 * retry_interval);
#ifdef INTERACTIVE
	   	        initcurses();
#endif
		}
                signal_restart_flag = false;
                while (!signal_exit_flag && !signal_restart_flag) {
#ifdef INTERACTIVE
                   if (using_curses == 1 || use_lcdd_menu) {
                      FD_ZERO(&read_fds);
                      FD_ZERO(&write_fds);
		      if (using_curses == 1)
     	                 FD_SET(0, &read_fds); /* watch stdin */
   	              if (use_lcdd_menu) {
		         FD_SET(lcd_fd, &read_fds); 
		         maxfd = lcd_fd;
		      }
   	              if (using_lirc) {
		         FD_SET(lirc_fd, &read_fds); 
                         if (lirc_fd > maxfd) 
		            maxfd = lirc_fd;
                      }
		      timeout.tv_sec = 5;
                      if(select(maxfd + 1, &read_fds, NULL, NULL, &timeout) == -1) {
#ifndef __WIN32__
    	                 if (errno != EINTR)
			 {
		           fprintf(stderr,"Select Error:%d\n", errno);
#else
			 WSAerrno = WSAGetLastError();
			 if ( (WSAerrno != WSAEINTR) && (WSAerrno != WSAENOTSOCK) )
			 {	
		           fprintf(stderr,"Select Error:%d\n", WSAerrno);
#endif
   	                   abort();
	                 }
#ifdef __WIN32__
			 else
				 WaitForSingleObject( GetStdHandle(STD_INPUT_HANDLE), 5000 );
#endif
                      }
		      if (FD_ISSET(0, &read_fds)) {
                         while ((key = getch()) != ERR) {
                            ir = getircode(key);
	                    if (ir == (unsigned long) 0x01) {
  		               signal_exit_flag = 1;
                            }else{
			       if (ir != 0) slimproto_ir(&slimproto, 1, 1, ir);
			    }
		         }
		      } 
		      if (using_lirc && FD_ISSET(lirc_fd, &read_fds)) {
                         while((key = read_lirc()) != 0 ) { 
                            ir = getircode(key);
	                    if (ir == 0x01) { 
  		               signal_exit_flag = 1;
                            } else {
			       if (ir != 0) slimproto_ir(&slimproto, 1, 1, ir);
			    }
		         }
		      } 
		      if (use_lcdd_menu && FD_ISSET(lcd_fd, &read_fds)) {
                         while(read_lcd()); 
		      }
		   } else {
                      wait_for_restart_signal();
		   }
#else
                   wait_for_restart_signal();
#endif
		}
#ifdef INTERACTIVE
                FD_ZERO(&read_fds);
                FD_ZERO(&write_fds);
#endif
		if (signal_restart_flag) { 
#ifdef INTERACTIVE
			exitcurses();
#endif
			fprintf(stderr,"Retry in %d seconds.\n", retry_interval);
			Pa_Sleep(1000 * retry_interval);
#ifdef INTERACTIVE
	   	        initcurses();
#endif
		}
        } while (signal_restart_flag && !signal_exit_flag);

#ifdef INTERACTIVE
	close_lirc();
#endif
	slimaudio_close(&slimaudio);
	slimproto_close(&slimproto);

#ifdef INTERACTIVE
        exitcurses();
        close_lcd();
#endif
#ifdef SLIMPROTO_DEBUG
	if (debug_logfile)
	{
		fclose (debuglog);
	}
#endif
	slimaudio_destroy(&slimaudio);
	slimproto_destroy(&slimproto);
	return 0;
} 
Ejemplo n.º 8
0
Archivo: main.c Proyecto: theqvd/vcxsrv
int
dix_main(int argc, char *argv[], char *envp[])
{
    int i;
    HWEventQueueType alwaysCheckForInput[2];
    #ifdef _DEBUG
    //int TmpFlag=_CrtSetDbgFlag( _CRTDBG_REPORT_FLAG);
    
    //TmpFlag|=_CRTDBG_ALLOC_MEM_DF;
    //TmpFlag|=_CRTDBG_DELAY_FREE_MEM_DF;
    //TmpFlag|=_CRTDBG_CHECK_ALWAYS_DF;
    //TmpFlag|=_CRTDBG_CHECK_CRT_DF;
    //TmpFlag|=_CRTDBG_LEAK_CHECK_DF;
    
    //_CrtSetDbgFlag(TmpFlag);
    #endif

    ptw32_processInitialize();
    display = "0";

    #ifdef WIN32

    if (InitWSA()<0)
    {
      printf("Error initialising WSA\n");
      return -1;
    }
    /* In Win32 we have different threads call Xlib functions (depending
       on the commandline options given).
       XInitThreads has to be called before
       any xlib function is called (aoccording to the man page) */
    XInitThreads();
    /* change the current directory to the directory where the vcxsrv.exe executable is installed.
       This is needed because the font directories are relative to the current directory.
     */
     {
       char ModuleFilename[MAX_PATH];
       char *pSlash;
       GetModuleFileName(NULL,ModuleFilename,sizeof(ModuleFilename));
       pSlash=strrchr(ModuleFilename,'\\');
       if (pSlash)
       {
         *pSlash='\0';
         chdir(ModuleFilename);
       }
     }
    OsVendorPreInit(argc, argv);
    #endif

    InitRegions();

    CheckUserParameters(argc, argv, envp);

    CheckUserAuthorization();

    InitConnectionLimits();

    ProcessCommandLine(argc, argv);

    alwaysCheckForInput[0] = 0;
    alwaysCheckForInput[1] = 1;
    while (1) {
        serverGeneration++;
        ScreenSaverTime = defaultScreenSaverTime;
        ScreenSaverInterval = defaultScreenSaverInterval;
        ScreenSaverBlanking = defaultScreenSaverBlanking;
        ScreenSaverAllowExposures = defaultScreenSaverAllowExposures;
#ifdef DPMSExtension
        DPMSStandbyTime = DPMSSuspendTime = DPMSOffTime = ScreenSaverTime;
        DPMSEnabled = TRUE;
        DPMSPowerLevel = 0;
#endif
        InitBlockAndWakeupHandlers();
        /* Perform any operating system dependent initializations you'd like */
        if (serverGeneration == 1) {
            CreateWellKnownSockets();
            for (i = 1; i < MAXCLIENTS; i++)
                clients[i] = NullClient;
            serverClient = calloc(sizeof(ClientRec), 1);
            if (!serverClient)
                FatalError("couldn't create server client");
            InitClient(serverClient, 0, (void *) NULL);
        }
        else
            ResetWellKnownSockets();
        clients[0] = serverClient;
        currentMaxClients = 1;
        OsInit();

        /* clear any existing selections */
        InitSelections();

        /* Initialize privates before first allocation */
        dixResetPrivates();

        /* Initialize server client devPrivates, to be reallocated as
         * more client privates are registered
         */
        if (!dixAllocatePrivates(&serverClient->devPrivates, PRIVATE_CLIENT))
            FatalError("failed to create server client privates");

        if (!InitClientResources(serverClient)) /* for root resources */
            FatalError("couldn't init server resources");

        SetInputCheck(&alwaysCheckForInput[0], &alwaysCheckForInput[1]);
        screenInfo.numScreens = 0;

        InitAtoms();
        InitEvents();
        InitGlyphCaching();
        dixResetRegistry();
        ResetFontPrivateIndex();
        InitCallbackManager();
        InitOutput(&screenInfo, argc, argv);

        if (screenInfo.numScreens < 1)
            FatalError("no screens found");
        InitExtensions(argc, argv);

        for (i = 0; i < screenInfo.numGPUScreens; i++) {
            ScreenPtr pScreen = screenInfo.gpuscreens[i];
            if (!CreateScratchPixmapsForScreen(pScreen))
                FatalError("failed to create scratch pixmaps");
            if (pScreen->CreateScreenResources &&
                !(*pScreen->CreateScreenResources) (pScreen))
                FatalError("failed to create screen resources");
        }

        for (i = 0; i < screenInfo.numScreens; i++) {
            ScreenPtr pScreen = screenInfo.screens[i];

            if (!CreateScratchPixmapsForScreen(pScreen))
                FatalError("failed to create scratch pixmaps");
            if (pScreen->CreateScreenResources &&
                !(*pScreen->CreateScreenResources) (pScreen))
                FatalError("failed to create screen resources");
            if (!CreateGCperDepth(i))
                FatalError("failed to create scratch GCs");
            if (!CreateDefaultStipple(i))
                FatalError("failed to create default stipple");
            if (!CreateRootWindow(pScreen))
                FatalError("failed to create root window");
        }

        InitFonts();
        if (SetDefaultFontPath(defaultFontPath) != Success) {
            ErrorF("[dix] failed to set default font path '%s'",
                   defaultFontPath);
        }
        if (!SetDefaultFont(defaultTextFont)) {
            FatalError("could not open default font '%s'", defaultTextFont);
        }

        if (!(rootCursor = CreateRootCursor(NULL, 0))) {
            FatalError("could not open default cursor font '%s'",
                       defaultCursorFont);
        }

#ifdef DPMSExtension
        /* check all screens, looking for DPMS Capabilities */
        DPMSCapableFlag = DPMSSupported();
        if (!DPMSCapableFlag)
            DPMSEnabled = FALSE;
#endif

#ifdef PANORAMIX
        /*
         * Consolidate window and colourmap information for each screen
         */
        if (!noPanoramiXExtension)
            PanoramiXConsolidate();
#endif

        for (i = 0; i < screenInfo.numScreens; i++)
            InitRootWindow(screenInfo.screens[i]->root);

        InitCoreDevices();
        InitInput(argc, argv);
        InitAndStartDevices();
        ReserveClientIds(serverClient);

        dixSaveScreens(serverClient, SCREEN_SAVER_FORCER, ScreenSaverReset);

        dixCloseRegistry();

#ifdef PANORAMIX
        if (!noPanoramiXExtension) {
            if (!PanoramiXCreateConnectionBlock()) {
                FatalError("could not create connection block info");
            }
        }
        else
#endif
        {
            if (!CreateConnectionBlock()) {
                FatalError("could not create connection block info");
            }
        }

#ifdef XQUARTZ
        /* Let the other threads know the server is done with its init */
        pthread_mutex_lock(&serverRunningMutex);
        serverRunning = TRUE;
        pthread_cond_broadcast(&serverRunningCond);
        pthread_mutex_unlock(&serverRunningMutex);
#endif

        NotifyParentProcess();

        #ifdef _MSC_VER
        // initialise here because doing it in InitInput failes because keyboard device is not started yet then
        winInitializeModeKeyStates ();
        #endif

        Dispatch();

#ifdef XQUARTZ
        /* Let the other threads know the server is no longer running */
        pthread_mutex_lock(&serverRunningMutex);
        serverRunning = FALSE;
        pthread_mutex_unlock(&serverRunningMutex);
#endif

        UndisplayDevices();
        DisableAllDevices();

        /* Now free up whatever must be freed */
        if (screenIsSaved == SCREEN_SAVER_ON)
            dixSaveScreens(serverClient, SCREEN_SAVER_OFF, ScreenSaverReset);
        FreeScreenSaverTimer();
        CloseDownExtensions();

#ifdef PANORAMIX
        {
            Bool remember_it = noPanoramiXExtension;

            noPanoramiXExtension = TRUE;
            FreeAllResources();
            noPanoramiXExtension = remember_it;
        }
#else
        FreeAllResources();
#endif

        CloseInput();

        for (i = 0; i < screenInfo.numScreens; i++)
            screenInfo.screens[i]->root = NullWindow;

        CloseDownDevices();

        CloseDownEvents();

        for (i = screenInfo.numGPUScreens - 1; i >= 0; i--) {
            ScreenPtr pScreen = screenInfo.gpuscreens[i];
            FreeScratchPixmapsForScreen(pScreen);
            (*pScreen->CloseScreen) (pScreen);
            dixFreePrivates(pScreen->devPrivates, PRIVATE_SCREEN);
            free(pScreen);
            screenInfo.numGPUScreens = i;
        }

        for (i = screenInfo.numScreens - 1; i >= 0; i--) {
            FreeScratchPixmapsForScreen(screenInfo.screens[i]);
            FreeGCperDepth(i);
            FreeDefaultStipple(i);
            dixFreeScreenSpecificPrivates(screenInfo.screens[i]);
            (*screenInfo.screens[i]->CloseScreen) (screenInfo.screens[i]);
            dixFreePrivates(screenInfo.screens[i]->devPrivates, PRIVATE_SCREEN);
            free(screenInfo.screens[i]);
            screenInfo.numScreens = i;
        }

        ReleaseClientIds(serverClient);
        dixFreePrivates(serverClient->devPrivates, PRIVATE_CLIENT);
        serverClient->devPrivates = NULL;

	dixFreeRegistry();

        FreeFonts();

        FreeAllAtoms();

        FreeAuditTimer();

        DeleteCallbackManager();

        if (dispatchException & DE_TERMINATE) {
            CloseWellKnownConnections();
        }

        OsCleanup((dispatchException & DE_TERMINATE) != 0);

        if (dispatchException & DE_TERMINATE) {
            ddxGiveUp(EXIT_NO_ERROR);
            break;
        }

        free(ConnectionInfo);
        ConnectionInfo = NULL;
    }
    return 0;
}
Ejemplo n.º 9
0
pthread_t
pthread_self (void)
     /*
      * ------------------------------------------------------
      * DOCPUBLIC
      *      This function returns a reference to the current running
      *      thread.
      *
      * PARAMETERS
      *      N/A
      *
      *
      * DESCRIPTION
      *      This function returns a reference to the current running
      *      thread.
      *
      * RESULTS
      *              pthread_t       reference to the current thread
      *
      * ------------------------------------------------------
      */
{
  pthread_t self;
  DWORD_PTR vThreadMask, vProcessMask, vSystemMask;
  pthread_t nil = {NULL, 0};
  ptw32_thread_t * sp;

  if (!ptw32_processInitialize())
	return nil;

#if defined(_UWIN)
  if (!ptw32_selfThreadKey)
    return nil;
#endif

  sp = (ptw32_thread_t *) pthread_getspecific (ptw32_selfThreadKey);

  if (sp != NULL)
    {
      self = sp->ptHandle;
    }
  else
    {
	  int fail = PTW32_FALSE;
      /*
       * Need to create an implicit 'self' for the currently
       * executing thread.
       */
      self = ptw32_new ();
      sp = (ptw32_thread_t *) self.p;

      if (sp != NULL)
        {
    	  /*
    	   * This is a non-POSIX thread which has chosen to call
    	   * a POSIX threads function for some reason. We assume that
    	   * it isn't joinable, but we do assume that it's
    	   * (deferred) cancelable.
    	   */
    	  sp->implicit = 1;
    	  sp->detachState = PTHREAD_CREATE_DETACHED;
    	  sp->thread = GetCurrentThreadId ();

#if defined(NEED_DUPLICATEHANDLE)
    	  /*
    	   * DuplicateHandle does not exist on WinCE.
    	   *
    	   * NOTE:
    	   * GetCurrentThread only returns a pseudo-handle
    	   * which is only valid in the current thread context.
    	   * Therefore, you should not pass the handle to
    	   * other threads for whatever purpose.
    	   */
    	  sp->threadH = GetCurrentThread ();
#else
    	  if (!DuplicateHandle (GetCurrentProcess (),
				GetCurrentThread (),
				GetCurrentProcess (),
				&sp->threadH,
				0, FALSE, DUPLICATE_SAME_ACCESS))
    	    {
    		  fail = PTW32_TRUE;
    	    }
#endif
    	  /*
    	   * Get this threads CPU affinity by temporarily setting the threads
    	   * affinity to that of the process to get the old thread affinity,
    	   * then reset to the old affinity.
    	   */
    	  if (!fail)
    	    {
    		  if (GetProcessAffinityMask(GetCurrentProcess(), &vProcessMask, &vSystemMask))
    		    {
    			  vThreadMask = SetThreadAffinityMask(sp->threadH, vProcessMask);
    			  if (vThreadMask)
    			    {
    				  if (SetThreadAffinityMask(sp->threadH, vThreadMask))
    				    {
    					  sp->cpuset = (size_t) vThreadMask;
    				    }
    				  else fail = PTW32_TRUE;
    			    }
    			  else fail = PTW32_TRUE;
    		    }
    		  else fail = PTW32_TRUE;

    		  /*
    		   * No need to explicitly serialise access to sched_priority
    		   * because the new handle is not yet public.
    		   */
    		  sp->sched_priority = GetThreadPriority (sp->threadH);
    		  pthread_setspecific (ptw32_selfThreadKey, (void *) sp);
    	    }
        }

      if (fail)
        {
    	  /*
    	   * Thread structs are never freed but are reused so if this
    	   * continues to fail at least we don't leak memory.
    	   */
		  sp->threadH = 0;	// [i_a]
    	  ptw32_threadReusePush (self);
    	  /*
    	   * As this is a win32 thread calling us and we have failed,
    	   * return a value that makes sense to win32.
    	   */
    	  return nil;
        }
    }

  return (self);
}
Ejemplo n.º 10
0
int main(int argc, char *argv[]) {
	double			pos;
    VideoState      *is;


    if(argc < 2) {
        fprintf(stderr, "Usage: test <file>\n");
        exit(1);
    }

#ifdef __MINGW32__
	ptw32_processInitialize();
	//ptw32_processTerminate();
#endif

	//XInitThreads();

    is = (VideoState *)av_mallocz(sizeof(VideoState));

	avcodec_register_all();
	//avdevice_register_all();
	avfilter_register_all();
    av_register_all();
	avformat_network_init();

	if (USE_EVENT_MULTI_THREAD)
	{
		if ( SDLMOD_StartEventLoop(SDLMOD_INIT_EVENTTHREAD) < 0 ) {
			fprintf(stderr, "Could not start SDLMOD event loop (multi thread)\n");
			exit(1);
		}
	}
	else
	{
		if ( SDLMOD_StartEventLoop(0) < 0 ) {
			fprintf(stderr, "Could not start SDLMOD event loop (main thread)\n");
			exit(1);
		}
	}
	if (SDLMOD_TimerInit() != 0)
	{
		fprintf(stderr, "SDLMOD_TimerInit failed\n");
		exit(1);
	}

	g_video_width = 640;
	g_video_height = 480;
	g_video_resized = 0;

	//screen = SDL_SetVideoMode(g_video_width, g_video_height, SDL_VIDEO_MODE_BPP, SDL_VIDEO_MODE_FLAGS);
	screen = SDLMOD_CreateRGBSurface(0,
		g_video_width, g_video_height, SDL_VIDEO_MODE_BPP,
		Rmask, Gmask, Bmask, Amask
		);
	if(!screen) {
		fprintf(stderr, "SDL: could not set video mode - exiting\n");
		exit(1);
	}

    screen_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
    pthread_mutex_init(screen_mutex, NULL);

    av_strlcpy(is->filename, argv[1], sizeof(is->filename));

	is->pictq_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
    pthread_mutex_init(is->pictq_mutex, NULL);
    is->pictq_cond = (pthread_cond_t *)malloc(sizeof(pthread_cond_t));
    pthread_cond_init(is->pictq_cond, NULL);
    
	schedule_refresh(is, 40);

	is->av_sync_type = AV_SYNC_VIDEO_MASTER;

    {
		int err;
		is->parse_tid = (pthread_t *)malloc(sizeof(pthread_t));
		err = pthread_create(is->parse_tid, NULL, decodeThread, is);
		if (err!=0)
		{
			free(is->parse_tid);
			printf("can't create thread: %s\n", strerror(err));
			exit(0);
		}
	}
    if (!is->parse_tid) {
        av_free(is);
        return -1;
    }

	av_init_packet(&flush_pkt);
	flush_pkt.data = (uint8_t*)"FLUSH";

#if USE_EVENT_LOOP_MT
	{
		pthread_t pid;
		pthread_create(&pid, NULL, event_loop, is);
		if (0)
		{
			pthread_join(pid, NULL);
		}
		else
		{
#if USE_GL
			glutInit(&argc, argv);
			glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH);
			glutInitWindowSize(g_video_width, g_video_height);
			glutInitWindowPosition(0, 0);
			
			win = glutCreateWindow(TITLE);
			createMenu();

			glutDisplayFunc(display);
			glutReshapeFunc(reshape);
			glutMouseFunc(mouse);
			glutMotionFunc(motion);
			glutIdleFunc(idle);

			if (initEnvironment())
			{
				glutMainLoop();
			}
#else
			printf(">>>>>>Please input command (exit, quit, save):<<<<<<\n");
			char string[256];
			char* ret;
			while(1)
			{
				ret = gets(string);
				if (strcmp(string, "exit") == 0 || 
				    strcmp(string, "quit") == 0 ||
				    strcmp(string, "e") == 0 ||
				    strcmp(string, "q") == 0
				    )
				{
					break;
				}
				else if (strcmp(string, "save") == 0 ||
					strcmp(string, "s") == 0
				    )
				{
					save_bmp();
					printf("save_bmp() finish.\n");
				}
				else
				{
					printf("Please input command (exit, quit, save):\n");
				}
			}
#endif
		}
	}
#else
	event_loop(is);
#endif

    return 0;
}