Esempio n. 1
0
void
init_jack (void)
{
   int err;

#ifdef WITH_LASH
   lash_event_t *event;
#endif

   jack_client = jack_client_open(PROGRAM_NAME, JackNullOption, NULL);

   if (jack_client == NULL)
   {
      g_critical("Could not connect to the JACK server; run jackd first?");
      exit(EX_UNAVAILABLE);
   }

#ifdef WITH_LASH
   event = lash_event_new_with_type(LASH_Client_Name);
// assert(event); /* Documentation does not say anything about return value. */
   lash_event_set_string(event, jack_get_client_name(jack_client));
   lash_send_event(lash_client, event);
   lash_jack_client_name(lash_client, jack_get_client_name(jack_client));
#endif

   err = jack_set_process_callback(jack_client, process_callback, 0);
   if (err)
   {
      g_critical("Could not register JACK process callback.");
      exit(EX_UNAVAILABLE);
   }

   /*
    * The above is pretty close to COMMON CODE.
    */

   input_port = jack_port_register
   (
      jack_client, INPUT_PORT_NAME, JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0
   );
   if (input_port == NULL)
   {
      g_critical("Could not register JACK input port.");
      exit(EX_UNAVAILABLE);
   }

   if (jack_activate(jack_client)) {
      g_critical("Cannot activate JACK client.");
      exit(EX_UNAVAILABLE);
   }
}
Esempio n. 2
0
int
add(Tjost_Module *module)
{
	Tjost_Host *host = module->host;
	lua_State *L = host->L;
	Data *dat = tjost_alloc(module->host, sizeof(Data));
	memset(dat, 0, sizeof(Data));

	lua_getfield(L, 1, "device");
	const char *device = luaL_optstring(L, -1, "seq");
	lua_pop(L, 1);

	lua_getfield(L, 1, "api");
	RtMidiC_API api = luaL_optint(L, -1, RTMIDIC_API_UNSPECIFIED);
	lua_pop(L, 1);

	dat->cb = _rtmidic_cb;
	
	if(!(dat->dev = rtmidic_in_new(api, jack_get_client_name(module->host->client))))
		MOD_ADD_ERR(module->host, MOD_NAME, "could not create device");
	if(rtmidic_in_virtual_port_open(dat->dev, device))
		MOD_ADD_ERR(module->host, MOD_NAME, "could not open virtual port");
	if(rtmidic_in_callback_set(dat->dev, &dat->cb))
		MOD_ADD_ERR(module->host, MOD_NAME, "could not set callback");

	if(tjost_pipe_init(&dat->pipe))
		MOD_ADD_ERR(module->host, MOD_NAME, "could not initialize tjost pipe");
	
	module->dat = dat;
	module->type = TJOST_MODULE_INPUT;

	return 0;
}
Esempio n. 3
0
void JACKInput::PortConnectCallback(jack_port_id_t a, jack_port_id_t b, int connect, void* arg) {
	// This callback is called from the notification thread (not the realtime processing thread), so sadly the timing can never be fully accurate.
	// To make things worse, we're not allowed to connect/disconnect ports from this thread, so we have to send a command to the input thread instead.
	JACKInput *input = (JACKInput*) arg;
	if(input->m_connect_system_playback) {
		jack_port_t *port_a = jack_port_by_id(input->m_jack_client, a);
		if(port_a == NULL)
			return;
		jack_port_t *port_b = jack_port_by_id(input->m_jack_client, b);
		if(port_b == NULL)
			return;
		const char *port_a_name = jack_port_name(port_a);
		const char *port_b_name = jack_port_name(port_b);
		for(unsigned int i = 0; i < input->m_channels; ++i) {
			std::string playback_name = "system:playback_" + NumToString(i + 1);
			if(port_b_name == playback_name) {
				std::string port_name_full = std::string(jack_get_client_name(input->m_jack_client)) + ":in_" + NumToString(i + 1);
				SharedLock lock(&input->m_shared_data);
				ConnectCommand cmd;
				cmd.m_connect = connect;
				cmd.m_source = port_a_name;
				cmd.m_destination = port_name_full;
				lock->m_connect_commands.push_back(cmd);
			}
		}
	}
}
Esempio n. 4
0
PRIVATE void clock_handler(AClock *clock, AClockReason reason) {

    switch (reason) {
	case CLOCK_DISABLE:
	    jack_deactivate( jack_client );
	    break;

	case CLOCK_ENABLE:
	    jack_set_process_callback( jack_client, (JackProcessCallback) process_callback, NULL ); 
	    jack_on_shutdown (jack_client, jack_shutdown, 0);

	    jack_activate( jack_client );

	    lash_event_t *event;
	    if( lash_enabled( galan_lash_get_client() ) ) {
		event = lash_event_new_with_type(LASH_Jack_Client_Name);
		lash_event_set_string(event, jack_get_client_name( jack_client ) );
		lash_send_event( galan_lash_get_client(), event);
	    }
	    break;

	default:
	    g_message("Unreachable code reached (jack_output)... reason = %d", reason);
	    break;
    }
}
Esempio n. 5
0
jack_client_t* init_jack(void)
{
	jack_client_t *client;
	const char *client_name = "simple_talker";
	const char *server_name = NULL;
	jack_options_t options = JackNullOption;
	jack_status_t status;

	client = jack_client_open (client_name, options, &status, server_name);

	if (NULL == client) {
		fprintf (stderr, "jack_client_open() failed\n ");
		exit (1);
	}
	if (status & JackServerStarted) {
		fprintf (stderr, "JACK server started\n");
	}
	if (status & JackNameNotUnique) {
		client_name = jack_get_client_name(client);
		fprintf (stderr, "unique name `%s' assigned\n", client_name);
	}

	jack_set_process_callback(client, process, 0);
	jack_on_shutdown(client, jack_shutdown, 0);

	if (jack_activate (client))
		fprintf (stderr, "cannot activate client");

	inputports = (jack_port_t**) malloc (CHANNELS * sizeof (jack_port_t*));
	in = (jack_default_audio_sample_t**) malloc (CHANNELS * sizeof (jack_default_audio_sample_t*));
	ringbuffer = jack_ringbuffer_create (SAMPLE_SIZE * DEFAULT_RINGBUFFER_SIZE * CHANNELS);
	jack_ringbuffer_mlock(ringbuffer);

	memset(in, 0, sizeof (jack_default_audio_sample_t*)*CHANNELS);
	memset(ringbuffer->buf, 0, ringbuffer->size);

	for(int i = 0; i < CHANNELS; i++)
	{
		char* portName;
		if (asprintf(&portName, "input%d", i) < 0) 
		{
			fprintf(stderr, "Could not create portname for port %d", i);
			exit(1);
		}	
		
		inputports[i] = jack_port_register (client, portName,
				JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
		if (NULL == inputports[i]) 
		{
			fprintf (stderr, "cannot register input port \"%d\"!\n", i);
			jack_client_close (client);
			exit (1);
		}
	}

	return client;
}
Esempio n. 6
0
static PyObject * get_client_name(PyObject* self, PyObject* args)
{
    pyjack_client_t * client = self_or_global_client(self);
    if(client->pjc == NULL) {
        PyErr_SetString(JackNotConnectedError, "Jack connection has not yet been established.");
        return NULL;
    }
    return Py_BuildValue("s", jack_get_client_name(client->pjc));
}
Esempio n. 7
0
    void open_client(std::string const & server_name, std::string const & name, uint32_t input_port_count,
                     uint32_t output_port_count, uint32_t blocksize)
    {
        blocksize_ = blocksize;

        /* open client */
        client = server_name.empty() ? jack_client_open(name.c_str(), JackNoStartServer, &status)
                                     : jack_client_open(name.c_str(), jack_options_t(JackNoStartServer | JackServerName),
                                                        &status, server_name.c_str());
        boost::atomic_thread_fence(boost::memory_order_release); // ensure visibility on other threads

        if (status & JackServerFailed)
            throw std::runtime_error("Unable to connect to JACK server");

        if (status & JackNameNotUnique) {
            const char * client_name = jack_get_client_name(client);
            std::cout << "unique client name: " << client_name << std::endl;
        }

        /* initialize callbacks */
        jack_set_thread_init_callback (client, jack_thread_init_callback, this);
        jack_set_process_callback (client, jack_process_callback, this);
        jack_set_xrun_callback(client, jack_xrun_callback, this);
        jack_on_info_shutdown(client, (JackInfoShutdownCallback)jack_on_info_shutdown_callback, NULL);

        /* register ports */
        input_ports.clear();
        for (uint32_t i = 0; i != input_port_count; ++i) {
            std::string portname ("input_");
            portname += std::to_string(i+1);
            jack_port_t * port =
                jack_port_register(client, portname.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
            input_ports.push_back(port);
        }
        input_channels = input_port_count;
        super::input_samples.resize(input_port_count);

        output_ports.clear();
        for (uint32_t i = 0; i != output_port_count; ++i) {
            std::string portname ("output_");
            portname += std::to_string(i+1);
            jack_port_t * port =
                jack_port_register(client, portname.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
            output_ports.push_back(port);
        }
        output_channels = output_port_count;
        super::output_samples.resize(output_port_count);

        samplerate_ = jack_get_sample_rate(client);
        jack_frames = jack_get_buffer_size(client);

        if (jack_frames % blocksize_)
            throw std::runtime_error("Jack buffer size is not a multiple of blocksize");
    }
Esempio n. 8
0
// stage 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// JACK client initialization
int jack_init(){

    short i;
    char* client_name;
    jack_status_t status;

    client = jack_client_open (default_client_name, options, &status, default_server_name);

    if (client == NULL){
        return 1;
    }

    if (status & JackServerStarted){
        fprintf(stderr, "JACK server started\n");
    }

    if (status & JackNameNotUnique){
        client_name = jack_get_client_name ( client );
        fprintf ( stderr, "unique name `%s' assigned\n", client_name );
    }

    char port_name[16];
    jack_ports = (jack_port_t**)calloc(n_channels, sizeof(jack_port_t*));

    if(amiserver){
        for(i=0;i<n_channels;i++){
                sprintf(port_name, "%s%d", default_in_port_basename, i+1);
                jack_ports[i] = jack_port_register(client, port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
                if(jack_ports[i] == NULL){
                    fprintf ( stderr, "no more JACK ports available\n" );
                    return 1;
                }
        }
    }

    else{
        for(i=0;i<n_channels;i++){
            sprintf(port_name, "%s%d", default_out_port_basename, i+1);
            jack_ports[i] = jack_port_register(client, port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
            if(jack_ports[i] == NULL){
                fprintf ( stderr, "no more JACK ports available\n" );
                return 1;
            }
        }
    }

    bufsize = jack_get_buffer_size(client);
    printf("JACK Client initialized\n");
    printf("JACK Buffer size = %d\n", bufsize);
    printf("Audio Channels %hd\n", n_channels);

    return 0;
}
Esempio n. 9
0
bool JackClient::setup(volatile bool* p_runFlag, uint32_t nrOfFramesInRingBuffer)
{
    m_p_runFlag = p_runFlag;

    const char *server_name = NULL;
    jack_options_t options = JackNoStartServer;
    jack_status_t status;

    // create a jack client
    m_p_jackClient = jack_client_open(s_jackClientName.c_str(), options, &status, server_name);
    if (m_p_jackClient == NULL) {
        DEBUG_PRINT("jack_client_open() failed, status = 0x%2.0x",
                status);
        if (status & JackServerFailed) {
            DEBUG_PRINT("unable to connect to JACK server");
        }
        return false;
    }
    if (status & JackServerStarted) {
        DEBUG_PRINT("jack server up and running");
    }
    if (status & JackNameNotUnique) {
        char* client_name = jack_get_client_name(m_p_jackClient);
        DEBUG_PRINT("unique name `%s' assigned", client_name);
    }


    // create ringbuffer
    m_p_ringBuffer = jack_ringbuffer_create(sizeof(jack_default_audio_sample_t) * jack_get_buffer_size(m_p_jackClient) * nrOfFramesInRingBuffer);
    if (m_p_ringBuffer == NULL) {
        DEBUG_PRINT("failed to create ringbuffer");
        return false;
    }

    // setup callbacks
    int check;
    if ((check = jack_set_process_callback(m_p_jackClient, JackClient::processJackCallback, this))) {
        return false;
    }

    jack_on_shutdown(m_p_jackClient, JackClient::shutdownJackCallback, this);

    if ((check = jack_set_port_connect_callback(m_p_jackClient, JackClient::connectionJackCallback, this))) {
        return false;
    }

    if (!registerPorts()) {
        return false;
    }


    return true;
}
Esempio n. 10
0
static int
_jack_init(prog_t *handle, const char *id)
{
	jack_options_t opts = JackNullOption | JackNoStartServer;
	if(handle->server_name)
		opts |= JackServerName;
	if(handle->session_id)
		opts |= JackSessionID;

	jack_status_t status;
	if(!(handle->client = jack_client_open(id, opts, &status,
		handle->server_name ? handle->server_name : handle->session_id,
		handle->server_name ? handle->session_id : NULL)))
	{
		return -1;
	}

	//TODO check status

	// set client pretty name
#if defined(JACK_HAS_METADATA_API)
	jack_uuid_t uuid;
	const char *client_name = jack_get_client_name(handle->client);
	const char *uuid_str = jack_get_uuid_for_client_name(handle->client, client_name);
	if(uuid_str)
		jack_uuid_parse(uuid_str, &uuid);
	else
		jack_uuid_clear(&uuid);

	if(!jack_uuid_empty(uuid))
	{
		jack_set_property(handle->client, uuid,
			JACK_METADATA_PRETTY_NAME, "Synthpod", "text/plain");
	}
#endif

	// set client process callback
	if(jack_set_process_callback(handle->client, _process, handle))
		return -1;
	if(jack_set_session_callback(handle->client, _session, handle))
		return -1;
	if(jack_set_sample_rate_callback(handle->client, _sample_rate, handle))
		return -1;
	if(jack_set_buffer_size_callback(handle->client, _buffer_size, handle))
		return -1;
	jack_on_shutdown(handle->client, _shutdown, handle);
	jack_set_xrun_callback(handle->client, _xrun, handle);

	return 0;
}
Esempio n. 11
0
int lash_clinit(int argc, char** argv, jack_client_t *jack_client, snd_seq_t *alsa_handle)
{
    lash_jackname = jack_get_client_name(jack_client);
    lash_client = lash_init(lash_extract_args(&argc, &argv), lash_jackname, LASH_Config_File, LASH_PROTOCOL(2, 0));
    if (lash_enabled(lash_client)) 
    {
        lash_jack_client_name(lash_client, lash_jackname);
        lash_event_t *event = lash_event_new_with_type(LASH_Client_Name);
        lash_event_set_string(event, lash_jackname);
        lash_send_event(lash_client, event);
        lash_alsaid = alsa_handle;
        lash_alsa_client_id(lash_client, (unsigned char)snd_seq_client_id(alsa_handle));
        return 0;
    }
    return -1;
}
Esempio n. 12
0
bool SC_JackDriver::DriverSetup(int* outNumSamples, double* outSampleRate)
{
	char* clientName = 0;
	char* serverName = 0;

	if (mWorld->hw->mInDeviceName && (strlen(mWorld->hw->mInDeviceName) > 0)) {
		// parse string <serverName>:<clientName>
		SC_StringParser sp(mWorld->hw->mInDeviceName, ':');
		if (!sp.AtEnd()) serverName = strdup(sp.NextToken());
		if (!sp.AtEnd()) clientName = strdup(sp.NextToken());
		if (clientName == 0) {
			// no semicolon found
			clientName = serverName;
			serverName = 0;
		} else if (strlen(clientName) == 0) {
			free(clientName);
			clientName = 0;
		}
	}

	mClient = jack_client_open(
		clientName ? clientName : kJackDefaultClientName,
		serverName ? JackServerName : JackNullOption,
		NULL, serverName);
	if (serverName) free(serverName); if (clientName) free(clientName);
	if (mClient == 0) return false;

	scprintf("%s: client name is '%s'\n", kJackDriverIdent, jack_get_client_name(mClient));

	// create jack I/O ports
	mInputList = new SC_JackPortList(mClient, mWorld->mNumInputs, JackPortIsInput);
	mOutputList = new SC_JackPortList(mClient, mWorld->mNumOutputs, JackPortIsOutput);

	// register callbacks
	jack_set_process_callback(mClient, sc_jack_process_cb, this);
	jack_set_buffer_size_callback(mClient, sc_jack_bufsize_cb, this);
	jack_set_sample_rate_callback(mClient, sc_jack_srate_cb, this);
	jack_set_graph_order_callback(mClient, sc_jack_graph_order_cb, this);
	jack_set_xrun_callback(mClient, sc_jack_xrun_cb, this);
	jack_on_shutdown(mClient, sc_jack_shutdown_cb, mWorld);

	*outNumSamples = (int)jack_get_buffer_size(mClient);
	*outSampleRate = (double)jack_get_sample_rate(mClient);

	return true;
}
Esempio n. 13
0
// Initialise Jack related stuff
int init_jack( const char* client_name, jack_options_t jack_opt )
{
  jack_status_t status;

  // Register with Jack
  if ((client = jack_client_open(client_name, jack_opt, &status)) == 0) {
    rotter_fatal("Failed to start jack client: 0x%x", status);
    return -1;
  }
  rotter_info( "JACK client registered as '%s'.", jack_get_client_name( client ) );


  // Create our input port(s)
  if (channels==1) {
    if (!(inport[0] = jack_port_register(client, "mono", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0))) {
      rotter_fatal("Cannot register mono input port.");
      return -1;
    }
  } else {
    if (!(inport[0] = jack_port_register(client, "left", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0))) {
      rotter_fatal("Cannot register left input port.");
      return -1;
    }

    if (!(inport[1] = jack_port_register(client, "right", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0))) {
      rotter_fatal( "Cannot register left input port.");
      return -1;
    }
  }

  // Register xrun callback
  jack_set_xrun_callback(client, xrun_callback_jack, client);

  // Register shutdown callback
  jack_on_shutdown(client, shutdown_callback_jack, NULL);

  // Register callback
  if (jack_set_process_callback(client, callback_jack, NULL)) {
    rotter_fatal( "Failed to set Jack process callback.");
    return -1;
  }

  // Success
  return 0;
}
Esempio n. 14
0
static SCM start_jack(void *data) {
	int i;
	char name[16];
	jack_status_t jstatus;
	jack_client = jack_client_open(client_name,
					JackServerName,
					&jstatus, server_name);
	if (jack_client == 0) {
		log_msg("JACK server not running?\n") ;
		cleanup();
		return SCM_UNSPECIFIED;
		}
	log_msg("JACK status: %04x\n", jstatus);
	if (jstatus & JackServerStarted)
		log_msg("\tserver started\n");
	if (jstatus & JackServerFailed)
		log_msg("\tcan't connect\n");
	if (jstatus & JackInitFailure)
		log_msg("\tcan't initialize client\n");
	client_name = (const char *)jack_get_client_name(jack_client);
	sampling_rate = jack_get_sample_rate(jack_client) ;
	period_frames = jack_get_buffer_size(jack_client);
	jack_set_error_function(jack_error);
	jack_set_info_function(jack_info);
	jack_set_xrun_callback(jack_client, jack_xrun, NULL);
	jack_set_process_callback(jack_client, mixmaster, NULL);
	jack_set_port_registration_callback(jack_client, check_ports, NULL);
	jack_on_shutdown(jack_client, jack_shutdown, 0);
	for (i = 0; i < QMX_CHANNELS; i++) {
		sprintf(name, "out%02d", i + 1);
		jack_cauldron[i] = jack_port_register(jack_client, name,
				JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
		}
	if (jack_activate(jack_client)) {
		log_msg("Cannot activate client.\n");
		cleanup();
		return SCM_UNSPECIFIED;
		}
	log_msg("JACK client activated: '%s'\n", client_name);
	return SCM_UNSPECIFIED;
	}
Esempio n. 15
0
static
jack_client_t* init_jack( const char * client_name, const char* connect_port ) 
{
	jack_status_t status;
	jack_options_t options = JackNoStartServer;
	jack_client_t *client = NULL;

	// Register with Jack
	if ((client = jack_client_open(client_name, options, &status)) == 0) {
		fprintf(stderr, "Failed to start jack client: %d\n", status);
		exit(1);
	}
	if (!quiet) printf("JACK client registered as '%s'.\n", jack_get_client_name( client ) );

	// Create our pair of output ports
	if (!(input_port = jack_port_register(client, "in", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0))) {
		fprintf(stderr, "Cannot register input port 'in'.\n");
		exit(1);
	}
	
	// Register shutdown callback
	jack_on_shutdown (client, shutdown_callback_jack, NULL );

	// Register the peak audio callback
	jack_set_process_callback(client, process_peak, 0);

	// Activate the client
	if (jack_activate(client)) {
		fprintf(stderr, "Cannot activate client.\n");
		exit(1);
	}
	
	// Connect up our input port ?
	if (connect_port) {
		connect_jack_port( client, input_port, connect_port );
	}
	
	return client;
}
Esempio n. 16
0
File: Client.C Progetto: 0mk/non
/** Connect to JACK using client name /client_name/. Return a static
 * pointer to actual name as reported by JACK */
    const char *
    Client::init ( const char *client_name, unsigned int opts )
    {
        if (( _client = jack_client_open ( client_name, (jack_options_t)0, NULL )) == 0 )
            return NULL;

#define set_callback( name ) jack_set_ ## name ## _callback( _client, &Client:: name , this )

        set_callback( thread_init );
        set_callback( process );
        set_callback( xrun );
        set_callback( freewheel );
        set_callback( buffer_size );
        set_callback( port_connect );

        jack_set_sample_rate_callback( _client, &Client::sample_rate_changed, this );
  
#ifdef HAVE_JACK_PORT_GET_LATENCY_RANGE
        set_callback( latency );
#endif

        /* FIXME: should we wait to register this until after the project
           has been loaded (and we have disk threads running)? */
        if ( opts & SLOW_SYNC )
            set_callback( sync );

        if ( opts & TIMEBASE_MASTER )
            jack_set_timebase_callback( _client, 0, &Client::timebase, this );

        jack_on_shutdown( _client, &Client::shutdown, this );

        activate();

//        _sample_rate = frame_rate();

        return jack_get_client_name( _client );
    }
Esempio n. 17
0
static void
_jack_deinit(prog_t *handle)
{
	if(handle->client)
	{
		// remove client properties
#if defined(JACK_HAS_METADATA_API)
		jack_uuid_t uuid;
		const char *client_name = jack_get_client_name(handle->client);
		const char *uuid_str = jack_get_uuid_for_client_name(handle->client, client_name);
		if(uuid_str)
			jack_uuid_parse(uuid_str, &uuid);
		else
			jack_uuid_clear(&uuid);

		if(!jack_uuid_empty(uuid))
			jack_remove_properties(handle->client, uuid);
#endif

		jack_deactivate(handle->client);
		jack_client_close(handle->client);
		handle->client = NULL;
	}
}
int JackAudioDriver::init( unsigned bufferSize )
{
	// Destination ports the output of Hydrogen will be connected
	// to.
	Preferences* pPref = Preferences::get_instance();
	output_port_name_1 = pPref->m_sJackPortName1;
	output_port_name_2 = pPref->m_sJackPortName2;

	QString sClientName = "Hydrogen";

#ifdef H2CORE_HAVE_OSC
	QString sNsmClientId = pPref->getNsmClientId();

	if(!sNsmClientId.isEmpty()){
		sClientName = sNsmClientId;
	}
#endif

	// The address of the status object will be used by JACK to
	// return information from the open operation.
	jack_status_t status;
	// Sometimes jackd doesn't stop and start fast enough.
	int nTries = 2;
	while ( nTries > 0 ) {
		--nTries;

		// Open an external client session with the JACK
		// server.  The `jack_client_open' function is defined
		// in the jack/jack.h header. With it, clients may
		// choose which of several servers to connect, and
		// control whether and how to start the server
		// automatically, if it was not already running. Its
		// first argument _client_name_ of is at most
		// jack_client_name_size() characters. The name scope
		// is local to each server. Unless forbidden by the
		// JackUseExactName option, the server will modify
		// this name to create a unique variant, if
		// needed. The second argument _options_ is formed by
		// OR-ing together JackOptions bits. Only the
		// JackOpenOptions bits are allowed. _status_ (if
		// non-NULL) is an address for JACK to return
		// information from the open operation. This status
		// word is formed by OR-ing together the relevant
		// JackStatus bits.  Depending on the _status_, an
		// optional argument _server_name_ selects from among
		// several possible concurrent server
		// instances. Server names are unique to each user. It
		// returns an opaque client handle if successful. If
		// this is NULL, the open operation failed, *status
		// includes JackFailure and the caller is not a JACK
		// client.
#ifdef H2CORE_HAVE_JACKSESSION
		if (pPref->getJackSessionUUID().isEmpty()){
			m_pClient = jack_client_open( sClientName.toLocal8Bit(),
						      JackNullOption,
						      &status);
		} else {
			// Unique name of the JACK server used within
			// the JACK session.
			const QByteArray uuid = pPref->getJackSessionUUID().toLocal8Bit();
			// Using the JackSessionID option and the
			// supplied SessionID Token the sessionmanager
			// is able to identify the client again.
			m_pClient = jack_client_open( sClientName.toLocal8Bit(),
						      JackSessionID,
						      &status,
						      uuid.constData());
		}
#else
		m_pClient = jack_client_open( sClientName.toLocal8Bit(),
					      JackNullOption,
					      &status);
#endif
		// Check what did happen during the opening of the
		// client. CLIENT_SUCCESS sets the nTries variable
		// to 0 while CLIENT_FAILURE resets m_pClient to the
		// nullptr.
		switch(status) {
		case JackFailure:
			CLIENT_FAILURE("unknown error");
			break;
		case JackInvalidOption:
			CLIENT_FAILURE("invalid option");
			break;
		case JackNameNotUnique:
			if (m_pClient) {
				sClientName = jack_get_client_name(m_pClient);
				CLIENT_SUCCESS(QString("Jack assigned the client name '%1'").arg(sClientName));
			} else {
				CLIENT_FAILURE("name not unique");
			}
			break;
		case JackServerStarted:
			CLIENT_SUCCESS("JACK Server started for Hydrogen.");
			break;
		case JackServerFailed:
			CLIENT_FAILURE("unable to connect");
			break;
		case JackServerError:
			CLIENT_FAILURE("communication error");
			break;
		case JackNoSuchClient:
			CLIENT_FAILURE("unknown client type");
			break;
		case JackLoadFailure:
			CLIENT_FAILURE("can't load internal client");
			break;
		case JackInitFailure:
			CLIENT_FAILURE("can't initialize client");
			break;
		case JackShmFailure:
			CLIENT_FAILURE("unable to access shared memory");
			break;
		case JackVersionError:
			CLIENT_FAILURE("client/server protocol version mismatch");
			break;
		default:
			if (status) {
				ERRORLOG("Unknown status with JACK server.");
				if (m_pClient) {
					CLIENT_SUCCESS("Client pointer is *not* null..."
						       " assuming we're OK");
				}
			} else {
				CLIENT_SUCCESS("Connected to JACK server");
			}
		}
	}

	if (m_pClient == 0) return -1;

	// Here, client should either be valid, or NULL.
	jack_server_sampleRate = jack_get_sample_rate( m_pClient );
	jack_server_bufferSize = jack_get_buffer_size( m_pClient );

	pPref->m_nSampleRate = jack_server_sampleRate;
	pPref->m_nBufferSize = jack_server_bufferSize;

	/* tell the JACK server to call `process()' whenever
	   there is work to be done.
	*/
	jack_set_process_callback( m_pClient, this->processCallback, 0 );

	/* tell the JACK server to call `srate()' whenever
	   the sample rate of the system changes.
	*/
	jack_set_sample_rate_callback( m_pClient, jackDriverSampleRate, this );

	/* tell JACK server to update us if the buffer size
	   (frames per process cycle) changes.
	*/
	jack_set_buffer_size_callback( m_pClient, jackDriverBufferSize, 0 );

	/* tell the JACK server to call `jack_shutdown()' if
	   it ever shuts down, either entirely, or if it
	   just decides to stop calling us.
	*/
	jack_on_shutdown( m_pClient, jackDriverShutdown, 0 );

	// Create two new ports for Hydrogen's client. These are
	// objects used for moving data of any type in or out of the
	// client. Ports may be connected in various ways. The
	// function `jack_port_register' (jack/jack.h) is called like
	// jack_port_register( jack_client_t *client, 
	//                     const char *port_name,
        //                     const char *port_type,
        //                     unsigned long flags,
        //                     unsigned long buffer_size)
	//
	// All ports have a type, which may be any non-NULL and non-zero
	// length string, passed as an argument. Some port types are built
	// into the JACK API, currently only JACK_DEFAULT_AUDIO_TYPE.
	// It returns a _jack_port_t_ pointer on success, otherwise NULL.
	output_port_1 = jack_port_register( m_pClient, "out_L", JACK_DEFAULT_AUDIO_TYPE,
					    JackPortIsOutput, 0 );
	output_port_2 = jack_port_register( m_pClient, "out_R", JACK_DEFAULT_AUDIO_TYPE,
					    JackPortIsOutput, 0 );

	Hydrogen *pEngine = Hydrogen::get_instance();
	if ( ( output_port_1 == NULL ) || ( output_port_2 == NULL ) ) {
		pEngine->raiseError( Hydrogen::JACK_ERROR_IN_PORT_REGISTER );
		return 4;
	}

#ifdef H2CORE_HAVE_LASH
	if ( pPref->useLash() ){
		LashClient* lashClient = LashClient::get_instance();
		if (lashClient->isConnected()) {
			lashClient->setJackClientName(sClientName.toLocal8Bit().constData());
		}
	}
#endif

#ifdef H2CORE_HAVE_JACKSESSION
	jack_set_session_callback(m_pClient, jack_session_callback, (void*)this);
#endif

	if ( pPref->m_bJackMasterMode == Preferences::USE_JACK_TIME_MASTER ){
		// Make Hydrogen the timebase master, regardless if there
		// is already a timebase master present.
		m_nJackConditionalTakeOver = 0;
		// Make Hydrogen the JACK timebase master.
		initTimeMaster();
	}
	
	return 0;
}
int pa__init(pa_module*m) {
    struct userdata *u = NULL;
    pa_sample_spec ss;
    pa_channel_map map;
    pa_modargs *ma = NULL;
    jack_status_t status;
    const char *server_name, *client_name;
    uint32_t channels = 0;
    pa_bool_t do_connect = TRUE;
    unsigned i;
    const char **ports = NULL, **p;
    pa_sink_new_data data;

    pa_assert(m);

    jack_set_error_function(jack_error_func);

    if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
        pa_log("Failed to parse module arguments.");
        goto fail;
    }

    if (pa_modargs_get_value_boolean(ma, "connect", &do_connect) < 0) {
        pa_log("Failed to parse connect= argument.");
        goto fail;
    }

    server_name = pa_modargs_get_value(ma, "server_name", NULL);
    client_name = pa_modargs_get_value(ma, "client_name", "PulseAudio JACK Sink");

    m->userdata = u = pa_xnew0(struct userdata, 1);
    u->core = m->core;
    u->module = m;
    u->saved_frame_time_valid = FALSE;
    u->rtpoll = pa_rtpoll_new();
    pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);

    /* The queue linking the JACK thread and our RT thread */
    u->jack_msgq = pa_asyncmsgq_new(0);

    /* The msgq from the JACK RT thread should have an even higher
     * priority than the normal message queues, to match the guarantee
     * all other drivers make: supplying the audio device with data is
     * the top priority -- and as long as that is possible we don't do
     * anything else */
    u->rtpoll_item = pa_rtpoll_item_new_asyncmsgq_read(u->rtpoll, PA_RTPOLL_EARLY-1, u->jack_msgq);

    if (!(u->client = jack_client_open(client_name, server_name ? JackServerName : JackNullOption, &status, server_name))) {
        pa_log("jack_client_open() failed.");
        goto fail;
    }

    ports = jack_get_ports(u->client, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortIsPhysical|JackPortIsInput);

    channels = 0;
    for (p = ports; *p; p++)
        channels++;

    if (!channels)
        channels = m->core->default_sample_spec.channels;

    if (pa_modargs_get_value_u32(ma, "channels", &channels) < 0 ||
        channels <= 0 ||
        channels > PA_CHANNELS_MAX) {
        pa_log("Failed to parse channels= argument.");
        goto fail;
    }

    if (channels == m->core->default_channel_map.channels)
        map = m->core->default_channel_map;
    else
        pa_channel_map_init_extend(&map, channels, PA_CHANNEL_MAP_ALSA);

    if (pa_modargs_get_channel_map(ma, NULL, &map) < 0 || map.channels != channels) {
        pa_log("Failed to parse channel_map= argument.");
        goto fail;
    }

    pa_log_info("Successfully connected as '%s'", jack_get_client_name(u->client));

    u->channels = ss.channels = (uint8_t) channels;
    ss.rate = jack_get_sample_rate(u->client);
    ss.format = PA_SAMPLE_FLOAT32NE;

    pa_assert(pa_sample_spec_valid(&ss));

    for (i = 0; i < ss.channels; i++) {
        if (!(u->port[i] = jack_port_register(u->client, pa_channel_position_to_string(map.map[i]), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput|JackPortIsTerminal, 0))) {
            pa_log("jack_port_register() failed.");
            goto fail;
        }
    }

    pa_sink_new_data_init(&data);
    data.driver = __FILE__;
    data.module = m;
    pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
    pa_sink_new_data_set_sample_spec(&data, &ss);
    pa_sink_new_data_set_channel_map(&data, &map);
    pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "jack");
    if (server_name)
        pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, server_name);
    pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Jack sink (%s)", jack_get_client_name(u->client));
    pa_proplist_sets(data.proplist, "jack.client_name", jack_get_client_name(u->client));

    if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
        pa_log("Invalid properties");
        pa_sink_new_data_done(&data);
        goto fail;
    }

    u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
    pa_sink_new_data_done(&data);

    if (!u->sink) {
        pa_log("Failed to create sink.");
        goto fail;
    }

    u->sink->parent.process_msg = sink_process_msg;
    u->sink->userdata = u;

    pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
    pa_sink_set_rtpoll(u->sink, u->rtpoll);
    pa_sink_set_max_request(u->sink, jack_get_buffer_size(u->client) * pa_frame_size(&u->sink->sample_spec));

    jack_set_process_callback(u->client, jack_process, u);
    jack_on_shutdown(u->client, jack_shutdown, u);
    jack_set_thread_init_callback(u->client, jack_init, u);
    jack_set_buffer_size_callback(u->client, jack_buffer_size, u);

    if (!(u->thread = pa_thread_new(thread_func, u))) {
        pa_log("Failed to create thread.");
        goto fail;
    }

    if (jack_activate(u->client)) {
        pa_log("jack_activate() failed");
        goto fail;
    }

    if (do_connect) {
        for (i = 0, p = ports; i < ss.channels; i++, p++) {

            if (!*p) {
                pa_log("Not enough physical output ports, leaving unconnected.");
                break;
            }

            pa_log_info("Connecting %s to %s", jack_port_name(u->port[i]), *p);

            if (jack_connect(u->client, jack_port_name(u->port[i]), *p)) {
                pa_log("Failed to connect %s to %s, leaving unconnected.", jack_port_name(u->port[i]), *p);
                break;
            }
        }
    }

    pa_sink_put(u->sink);

    free(ports);
    pa_modargs_free(ma);

    return 0;

fail:
    if (ma)
        pa_modargs_free(ma);

    free(ports);

    pa__done(m);

    return -1;
}
Esempio n. 20
0
gboolean cbox_io_init_jack(struct cbox_io *io, struct cbox_open_params *const params, struct cbox_command_target *fb, GError **error)
{
    const char *client_name = cbox_config_get_string_with_default("io", "client_name", "cbox");
    
    jack_client_t *client = NULL;
    jack_status_t status = 0;
    client = jack_client_open(client_name, JackNoStartServer, &status);
    if (client == NULL)
    {
        if (!cbox_hwcfg_setup_jack())
        {
            g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Cannot set up JACK server configuration based on current hardware");
            return FALSE;
        }
        
        status = 0;
        client = jack_client_open(client_name, 0, &status);
    }
    if (client == NULL)
    {
        g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Cannot create JACK instance");
        return FALSE;
    }
    
    // XXXKF would use a callback instead
    io->io_env.buffer_size = jack_get_buffer_size(client);
    io->cb = NULL;
    io->io_env.input_count = cbox_config_get_int("io", "inputs", 0);
    io->input_buffers = malloc(sizeof(float *) * io->io_env.input_count);
    io->io_env.output_count = cbox_config_get_int("io", "outputs", 2);
    io->output_buffers = malloc(sizeof(float *) * io->io_env.output_count);

    struct cbox_jack_io_impl *jii = malloc(sizeof(struct cbox_jack_io_impl));
    io->impl = &jii->ioi;
    jii->enable_common_midi_input = cbox_config_get_int("io", "enable_common_midi_input", 1);
    jii->debug_transport = cbox_config_get_int("debug", "jack_transport", 0);
    jii->last_transport_state = JackTransportStopped;

    cbox_command_target_init(&io->cmd_target, cbox_jack_io_process_cmd, jii);
    jii->ioi.pio = io;
    jii->ioi.getsampleratefunc = cbox_jackio_get_sample_rate;
    jii->ioi.startfunc = cbox_jackio_start;
    jii->ioi.stopfunc = cbox_jackio_stop;
    jii->ioi.getstatusfunc = cbox_jackio_get_status;
    jii->ioi.pollfunc = cbox_jackio_poll_ports;
    jii->ioi.cyclefunc = cbox_jackio_cycle;
    jii->ioi.getmidifunc = cbox_jackio_get_midi_data;
    jii->ioi.createmidiinfunc = cbox_jackio_create_midi_in;
    jii->ioi.destroymidiinfunc = cbox_jackio_destroy_midi_in;
    jii->ioi.createmidioutfunc = cbox_jackio_create_midi_out;
    jii->ioi.destroymidioutfunc = cbox_jackio_destroy_midi_out;
    jii->ioi.updatemidiinroutingfunc = NULL;
    jii->ioi.controltransportfunc = cbox_jackio_control_transport;
    jii->ioi.getsynccompletedfunc = cbox_jackio_get_sync_completed;
    jii->ioi.destroyfunc = cbox_jackio_destroy;
    
    jii->client_name = g_strdup(jack_get_client_name(client));
    jii->client = client;
    jii->rb_autoconnect = jack_ringbuffer_create(sizeof(jack_port_t *) * 128);
    jii->error_str = NULL;
    io->io_env.srate = jack_get_sample_rate(client);
    
    jii->inputs = malloc(sizeof(jack_port_t *) * io->io_env.input_count);
    jii->outputs = malloc(sizeof(jack_port_t *) * io->io_env.output_count);
    for (int i = 0; i < io->io_env.input_count; i++)
        jii->inputs[i] = NULL;
    for (int i = 0; i < io->io_env.output_count; i++)
        jii->outputs[i] = NULL;
    for (int i = 0; i < io->io_env.input_count; i++)
    {
        gchar *name = g_strdup_printf("in_%d", 1 + i);
        jii->inputs[i] = jack_port_register(jii->client, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
        if (!jii->inputs[i])
        {
            g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Cannot create input port %d (%s)", i, name);
            g_free(name);
            goto cleanup;
        }
        g_free(name);
    }
    for (int i = 0; i < io->io_env.output_count; i++)
    {
        gchar *name = g_strdup_printf("out_%d", 1 + i);
        jii->outputs[i] = jack_port_register(jii->client, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
        if (!jii->outputs[i])
        {
            g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Cannot create output port %d (%s)", i, name);
            g_free(name);
            goto cleanup;
        }
        g_free(name);
    }
    if (jii->enable_common_midi_input)
    {
        jii->midi = jack_port_register(jii->client, "midi", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
        if (!jii->midi)
        {
            g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Cannot create MIDI port");
            return FALSE;
        }
    }
    else
        jii->midi = NULL;
    
    if (fb)
        cbox_execute_on(fb, NULL, "/io/jack_client_name", "s", NULL, jii->client_name);
    
    cbox_io_poll_ports(io, fb);

    return TRUE;

cleanup:
    if (jii->inputs)
    {
        for (int i = 0; i < io->io_env.input_count; i++)
            free(jii->inputs[i]);
        free(jii->inputs);
    }
    if (jii->outputs)
    {
        for (int i = 0; i < io->io_env.output_count; i++)
            free(jii->outputs[i]);
        free(jii->outputs);
    }
    cbox_io_destroy_all_midi_ports(io);
    if (jii->client_name)
        free(jii->client_name);
    jack_client_close(jii->client);
    free(jii);
    io->impl = NULL;
    return FALSE;
};
Esempio n. 21
0
extern jack_client_t *jack_start(t_callback callback, bool autoconnect) {
  const char *client_name = "dirt";
  const char *server_name = NULL;
  jack_options_t options = JackNullOption;
  jack_status_t status;
  int i;
  char portname[16];

  /* open a client connection to the JACK server */
  
  client = jack_client_open(client_name, options, &status, server_name);
  if (client == NULL) {
    fprintf(stderr, "jack_client_open() failed, "
             "status = 0x%2.0x\n", status);
    if (status & JackServerFailed) {
      fprintf(stderr, "Unable to connect to JACK server\n");
    }
    exit(1);
  }
  if (status & JackServerStarted) {
    fprintf(stderr, "JACK server started\n");
  }
  if (status & JackNameNotUnique) {
    client_name = jack_get_client_name(client);
    fprintf(stderr, "unique name `%s' assigned\n", client_name);
  }
  
  jack_set_process_callback(client, process, (void *) callback);
  
  jack_on_shutdown(client, jack_shutdown, 0);

  printf("engine sample rate: %" PRIu32 "\n",
          jack_get_sample_rate(client));

#ifdef INPUT
  strcpy(portname, "input");
  input_port = jack_port_register(client, portname,
                                  JACK_DEFAULT_AUDIO_TYPE,
                                  JackPortIsInput, 0);

  if (input_port == NULL) {
    fprintf(stderr, "no JACK input ports available\n");
    exit(1);
  }
#endif

  output_ports = malloc((g_num_channels + 1) * sizeof(jack_port_t*));
  if (!output_ports) {
    fprintf(stderr, "no memory to allocate `output_ports'\n");
    exit(1);
  }

  for (i = 0; i < g_num_channels; ++i) {
    sprintf(portname, "output_%d", i);
    output_ports[i] = jack_port_register(client, portname,
                                         JACK_DEFAULT_AUDIO_TYPE,
                                         JackPortIsOutput, 0);
    if (output_ports[i] == NULL) {
      fprintf(stderr, "no more JACK ports available\n");
      if (output_ports) free(output_ports);
      exit(1);
    }
  }
  
  output_ports[g_num_channels] = NULL;
  
  if (jack_activate(client)) {
    fprintf(stderr, "cannot activate client");
    if (output_ports) free(output_ports);
    exit(1);
  }

  if (autoconnect) {
    const char **ports;
    ports = jack_get_ports(client, NULL, NULL,
                           JackPortIsPhysical|JackPortIsInput);
    if (!ports) {
      fprintf(stderr, "cannot find any physical capture ports\n");
    } else {
      for (i = 0; i < g_num_channels; ++i) {
        if (ports[i] == NULL) {
          break;
        }
        //sprintf(portname, "output_%d", i);
        if (jack_connect(client, jack_port_name(output_ports[i]), ports[i])) {
          fprintf(stderr, "cannot connect output ports\n");
        }
      }
      free(ports);
    }

#ifdef INPUT
    ports = jack_get_ports(client, NULL, NULL,
                           JackPortIsPhysical|JackPortIsOutput);
    //strcpy(portname, "input");
    if (!ports) {
      fprintf(stderr, "cannot find any physical capture ports\n");
    } else {
      if (jack_connect(client, ports[0], jack_port_name(input_port))) {
        fprintf(stderr, "cannot connect input port\n");
      }
      free(ports);
    }
#endif
  }

  return(client);
}
Esempio n. 22
0
void *
start_jack_client(void *ptr)
{
    const char *client_name = "filter";
    const char *server_name = NULL;
    jack_options_t options = (JackNoStartServer|JackUseExactName|JackSessionID);
    jack_status_t status;

    /* open a client connection to the JACK server */
    client = jack_client_open (client_name, options, &status, server_name);
    if (client == NULL) {
	fprintf (stderr, "jack_client_open() failed, "
		"status = 0x%2.0x\n", status);
	if (status & JackServerFailed) {
	    fprintf (stderr, "Unable to connect to JACK server\n");
	}
	exit (1);
    }
    if (status & JackServerStarted) {
	fprintf (stderr, "JACK server started\n");
    }
    if (status & JackNameNotUnique) {
	client_name = jack_get_client_name(client);
	fprintf (stderr, "unique name `%s' assigned\n", client_name);
    }

    /* tell the JACK server to call `process()' whenever
       there is work to be done.  */
    jack_set_process_callback (client, process, 0);


    /* tell the JACK server to call `jack_shutdown()' if
       it ever shuts down, either entirely, or if it
       just decides to stop calling us.  */
    jack_on_shutdown (client, jack_shutdown, 0);


    /* display the current sample rate.  */
    printf ("engine sample rate: %" PRIu32 "\n",
	    jack_get_sample_rate (client));


    /* create two ports */

    input_port = jack_port_register (client, "input",
	    JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);

    output_port = jack_port_register (client, "output",
	    JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);

    if ((input_port == NULL) || (output_port == NULL)) {
	fprintf(stderr, "no more JACK ports available\n");
	exit (1);
    }

    /* create and initialize the control list */
    ctrls = malloc(sizeof(control_list));

    /* set with default values */
    ctrls->ftype = LPF;
    ctrls->dBgain = 0;	// dB value
    ctrls->fc = 100;	//Hz value
    ctrls->fs = (smp_type)jack_get_sample_rate(client);
    ctrls->bw = 0.25;	//bandwidth (ocataves)

    /* Compute default biquad lpf */
    filter = compute_biquad(ctrls->ftype, 
			    ctrls->dBgain, 
			    ctrls->fc, 
			    ctrls->fs, 
			    ctrls->bw); 

    printf("initial coefficients:\n");
    printf("b0=%f, b1=%f, b2=%f, a1=%f, a2=%f \n", filter->b0, filter->b1, filter->b2, filter->a1, filter->a2);


    /* Tell the JACK server that we are ready to roll.  Our
     * process() callback will start running now. */

    if (jack_activate (client)) {
	fprintf (stderr, "cannot activate client");
	exit (1);
    }


    /* Connect the ports.  You can't do this before the client is
     * activated, because we can't make connections to clients
     * that aren't running.  Note the confusing (but necessary)
     * orientation of the driver backend ports: playback ports are
     * "input" to the backend, and capture ports are "output" from
     * it.  */

    /**********************************************************
     Automatic Port Connections! -> Not usually recommended!
    ***********************************************************
    const char **ports;

    ports = jack_get_ports (client, NULL, NULL, JackPortIsPhysical|JackPortIsOutput);
    if (ports == NULL) {
	fprintf(stderr, "no physical capture ports\n");
	exit (1);
    }

    if (jack_connect (client, ports[0], jack_port_name (input_port))) {
	fprintf (stderr, "cannot connect input ports\n");
    }

    free (ports);

    ports = jack_get_ports (client, NULL, NULL, 
			    JackPortIsPhysical|JackPortIsInput);

    if (ports == NULL) {
	fprintf(stderr, "no physical playback ports\n");
	exit (1);
    }

    if (jack_connect (client, jack_port_name (output_port), ports[0])) {
	fprintf (stderr, "cannot connect output ports\n");
    }

    free (ports);
*/
    /* keep running until stopped by the user */

    sleep (-1);

    /* this is never reached, but if the program
       had some other way to exit besides being killed,
       they would be important to call.  */

    jack_client_close (client);
    exit (0);
}
Esempio n. 23
0
int main ( int argc, char *argv[] ) {
    int i;
    const char **ports;
    const char *client_name;
    const char *server_name = NULL;
    jack_status_t status;

#ifdef JACK_SESSION
    /*
     * Extra code for JS
     */
    int c;
    char *uuid = "13";
    while ((c = getopt (argc, argv, "u:")) != -1)
	switch (c) {
	case 'u':
	    uuid = optarg;
	    break;
	}
    printf("UUID is %s\n", uuid);
#endif

    client_name = strrchr ( argv[0], '/' );
    if ( client_name == 0 ) {
	client_name = argv[0];
    }
    else {
	client_name++;
    }

    /* open a client connection to the JACK server */
    /* Changed args for JS */

#ifdef JACK_SESSION
    client = jack_client_open ( client_name, JackSessionID, &status, uuid);
#else
    client = jack_client_open ( client_name, JackNullOption, &status);
#endif
    if ( client == NULL )
	{
	    fprintf ( stderr, "jack_client_open() failed, "
		      "status = 0x%2.0x\n", status );
	    if ( status & JackServerFailed )
		{
		    fprintf ( stderr, "Unable to connect to JACK server\n" );
		}
	    exit ( 1 );
	}
    if ( status & JackServerStarted )
	{
	    fprintf ( stderr, "JACK server started\n" );
	}
    if ( status & JackNameNotUnique )
	{
	    client_name = jack_get_client_name ( client );
	    fprintf ( stderr, "unique name `%s' assigned\n", client_name );
	}

#ifdef JACK_SESSION
    /* Set callback function for JS
     */
    jack_set_session_callback(client, session_callback, NULL);
#endif

    /* tell the JACK server to call `process()' whenever
       there is work to be done.
    */
    jack_set_process_callback ( client, process, 0 );

    /* tell the JACK server to call `jack_shutdown()' if
       it ever shuts down, either entirely, or if it
       just decides to stop calling us.
    */

    jack_on_shutdown ( client, jack_shutdown, 0 );

    /* create two ports pairs*/
    input_ports = ( jack_port_t** ) calloc ( 2, sizeof ( jack_port_t* ) );
    output_ports = ( jack_port_t** ) calloc ( 2, sizeof ( jack_port_t* ) );

    char port_name[16];
    for ( i = 0; i < 2; i++ )
	{
	    sprintf ( port_name, "input_%d", i + 1 );
	    input_ports[i] = jack_port_register ( client, port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
	    sprintf ( port_name, "output_%d", i + 1 );
	    output_ports[i] = jack_port_register ( client, port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
	    if ( ( input_ports[i] == NULL ) || ( output_ports[i] == NULL ) )
		{
		    fprintf ( stderr, "no more JACK ports available\n" );
		    exit ( 1 );
		}
	}

    bzero(buffer, SIZE * sizeof ( jack_default_audio_sample_t ));
    delay_idx = 0;
    idx = DELAY;

    /* Tell the JACK server that we are ready to roll.  Our
     * process() callback will start running now. */

    if ( jack_activate ( client ) )
	{
	    fprintf ( stderr, "cannot activate client" );
	    exit ( 1 );
	}

    /* Connect the ports.  You can't do this before the client is
     * activated, because we can't make connections to clients
     * that aren't running.  Note the confusing (but necessary)
     * orientation of the driver backend ports: playback ports are
     * "input" to the backend, and capture ports are "output" from
     * it.
     */

    ports = jack_get_ports ( client, NULL, NULL, JackPortIsPhysical|JackPortIsOutput );
    if ( ports == NULL )
	{
	    fprintf ( stderr, "no physical capture ports\n" );
	    exit ( 1 );
	}

    for ( i = 0; i < 2; i++ )
	if ( jack_connect ( client, ports[i], jack_port_name ( input_ports[i] ) ) )
	    fprintf ( stderr, "cannot connect input ports\n" );

    free ( ports );

    ports = jack_get_ports ( client, NULL, NULL, JackPortIsPhysical|JackPortIsInput );
    if ( ports == NULL )
	{
	    fprintf ( stderr, "no physical playback ports\n" );
	    exit ( 1 );
	}

    for ( i = 0; i < 2; i++ )
	if ( jack_connect ( client, jack_port_name ( output_ports[i] ), ports[i] ) )
	    fprintf ( stderr, "cannot connect input ports\n" );

    free ( ports );

    /* install a signal handler to properly quits jack client */
#ifdef WIN32
    signal ( SIGINT, signal_handler );
    signal ( SIGABRT, signal_handler );
    signal ( SIGTERM, signal_handler );
#else
    signal ( SIGQUIT, signal_handler );
    signal ( SIGTERM, signal_handler );
    signal ( SIGHUP, signal_handler );
    signal ( SIGINT, signal_handler );
#endif

    /* keep running until the transport stops */

    while (1)
	{
#ifdef WIN32
	    Sleep ( 1000 );
#else
	    sleep ( 1 );
#endif
	}

    jack_client_close ( client );
    exit ( 0 );
}
Esempio n. 24
0
JackAudioSystem::JackAudioSystem()
	: bActive(false)
	, client(NULL)
	, in_port(NULL)
	, output_buffer(NULL)
	, iBufferSize(0)
	, bJackIsGood(false)
	, bInputIsGood(false)
	, bOutputIsGood(false)
	, iSampleRate(0)
{
	if (g.s.qsJackAudioOutput.isEmpty()) {
		iOutPorts = 1;
	} else {
		iOutPorts = g.s.qsJackAudioOutput.toInt();
	}
	memset(reinterpret_cast<void *>(&out_ports), 0, sizeof(out_ports));

	qhInput.insert(QString(), tr("Hardware Ports"));
	qhOutput.insert(QString::number(1), tr("Mono"));
	qhOutput.insert(QString::number(2), tr("Stereo"));

	jack_status_t status = static_cast<jack_status_t>(0);
	int err = 0;

	jack_options_t jack_option = g.s.bJackStartServer ? JackNullOption : JackNoStartServer;
	client = jack_client_open(g.s.qsJackClientName.toStdString().c_str(), jack_option, &status);

	if (!client) {
		QStringList errors = jackStatusToStringList(status);
		qWarning("JackAudioSystem: unable to open client due to %i errors:", errors.count());
		for (int i = 0; i < errors.count(); ++i) {
			qWarning("JackAudioSystem: %s", qPrintable(errors.at(i)));
		}

		return;
	}

	qWarning("JackAudioSystem: client \"%s\" opened successfully", jack_get_client_name(client));
	iBufferSize = jack_get_buffer_size(client);
	iSampleRate = jack_get_sample_rate(client);

	err = jack_set_process_callback(client, process_callback, this);
	if (err != 0) {
		qWarning("JackAudioSystem: unable to set process callback - jack_set_process_callback() returned %i", err);
		return;
	}

	err = jack_set_sample_rate_callback(client, srate_callback, this);
	if (err != 0) {
		qWarning("JackAudioSystem: unable to set sample rate callback - jack_set_sample_rate_callback() returned %i", err);
		return;
	}

	err = jack_set_buffer_size_callback(client, buffer_size_callback, this);
	if (err != 0) {
		qWarning("JackAudioSystem: unable to set buffer size callback - jack_set_buffer_size_callback() returned %i", err);
		return;
	}

	jack_on_shutdown(client, shutdown_callback, this);

	// If we made it this far, then everything is okay
	bJackIsGood = true;
}
Esempio n. 25
0
File: tw.c Progetto: Andux/jack2
int
main (int argc, char *argv[])
{
	const char **ports;
	const char *client_name;
	const char *server_name = NULL;
	jack_options_t options = JackNullOption;
	jack_status_t status;

	if (argc >= 2) {		/* client name specified? */
		client_name = argv[1];
		if (argc >= 3) {	/* server name specified? */
			server_name = argv[2];
			options |= JackServerName;
		}
	} else {			/* use basename of argv[0] */
		client_name = strrchr(argv[0], '/');
		if (client_name == 0) {
			client_name = argv[0];
		} else {
			client_name++;
		}
	}

	/* open a client connection to the JACK server */

	client = jack_client_open (client_name, options, &status, server_name);
	if (client == NULL) {
		fprintf (stderr, "jack_client_open() failed, "
			 "status = 0x%2.0x\n", status);
		if (status & JackServerFailed) {
			fprintf (stderr, "Unable to connect to JACK server\n");
		}
		exit (1);
	}
	if (status & JackServerStarted) {
		fprintf (stderr, "JACK server started\n");
	}
	if (status & JackNameNotUnique) {
		client_name = jack_get_client_name(client);
		fprintf (stderr, "unique name `%s' assigned\n", client_name);
	}

	/* tell the JACK server to call `process()' whenever
	   there is work to be done.
	*/
    if (jack_set_process_thread(client, jack_thread, client) < 0)
		exit(1);

	/* tell the JACK server to call `jack_shutdown()' if
	   it ever shuts down, either entirely, or if it
	   just decides to stop calling us.
	*/

	jack_on_shutdown (client, jack_shutdown, 0);

	/* display the current sample rate.
	 */

	printf ("engine sample rate: %" PRIu32 "\n",
		jack_get_sample_rate (client));

	/* create two ports */

	input_port = jack_port_register (client, "input",
					 JACK_DEFAULT_AUDIO_TYPE,
					 JackPortIsInput, 0);
	output_port = jack_port_register (client, "output",
					  JACK_DEFAULT_AUDIO_TYPE,
					  JackPortIsOutput, 0);

	if ((input_port == NULL) || (output_port == NULL)) {
		fprintf(stderr, "no more JACK ports available\n");
		exit (1);
	}

	/* Tell the JACK server that we are ready to roll.  Our
	 * process() callback will start running now. */

	if (jack_activate (client)) {
		fprintf (stderr, "cannot activate client");
		exit (1);
	}

	/* Connect the ports.  You can't do this before the client is
	 * activated, because we can't make connections to clients
	 * that aren't running.  Note the confusing (but necessary)
	 * orientation of the driver backend ports: playback ports are
	 * "input" to the backend, and capture ports are "output" from
	 * it.
	 */

	ports = jack_get_ports (client, NULL, NULL,
				JackPortIsPhysical|JackPortIsOutput);
	if (ports == NULL) {
		fprintf(stderr, "no physical capture ports\n");
		exit (1);
	}

	if (jack_connect (client, ports[0], jack_port_name (input_port))) {
		fprintf (stderr, "cannot connect input ports\n");
	}

	jack_free (ports);

	ports = jack_get_ports (client, NULL, NULL,
				JackPortIsPhysical|JackPortIsInput);
	if (ports == NULL) {
		fprintf(stderr, "no physical playback ports\n");
		exit (1);
	}

	if (jack_connect (client, jack_port_name (output_port), ports[0])) {
		fprintf (stderr, "cannot connect output ports\n");
	}

	jack_free (ports);

    /* install a signal handler to properly quits jack client */
    signal(SIGQUIT, signal_handler);
	signal(SIGTERM, signal_handler);
	signal(SIGHUP, signal_handler);
	signal(SIGINT, signal_handler);

	/* keep running until the transport stops */

	while (client_state != Exit) {
		sleep (1);
	}

	jack_client_close (client);
	exit (0);
}
Esempio n. 26
0
int
main (int argc, char *argv[])
{
	const char **ports;
	const char *client_name;
	const char *server_name = NULL;
	jack_options_t options = JackNullOption;
	jack_status_t status;

	client_name = "jacktester";
	if (argc > 1) {
		chunksize = atoi (argv[1]);
		printf ("using chunksize of %d\n", chunksize);
	}

	/* open a client connection to the JACK server */

	client = jack_client_open (client_name, options, &status, server_name);
	if (client == NULL) {
		fprintf (stderr, "jack_client_open() failed, status = 0x%x\n",
			 status);
		if (status & JackServerFailed) {
			fprintf (stderr, "Unable to connect to JACK server\n");
		}
		exit (1);
	}
	if (status & JackServerStarted) {
		fprintf (stderr, "JACK server started\n");
	}
	if (status & JackNameNotUnique) {
		client_name = jack_get_client_name(client);
		fprintf (stderr, "unique name `%s' assigned\n", client_name);
	}

	/* tell the JACK server to call `process()' whenever
	   there is work to be done.
	*/

	jack_set_process_callback (client, process, 0);
	jack_set_xrun_callback (client, jack_xrun, 0);
	jack_on_shutdown (client, jack_shutdown, 0);

	/* create two ports */

	input_port = jack_port_register (client, "input",
					 JACK_DEFAULT_AUDIO_TYPE,
					 JackPortIsInput, 0);
	output_port = jack_port_register (client, "output",
					  JACK_DEFAULT_AUDIO_TYPE,
					  JackPortIsOutput, 0);

	if ((input_port == NULL) || (output_port == NULL)) {
		fprintf(stderr, "no more JACK ports available\n");
		exit (1);
	}

	at_loop_size = jack_get_sample_rate (client) * 2;
	if ((thechunk = (char *) malloc (chunksize)) == NULL) {
		fprintf (stderr, "cannot allocate chunk\n");
		exit (1);
	}

	/* Tell the JACK server that we are ready to roll.  Our
	 * process() callback will start running now. */

	if (jack_activate (client)) {
		fprintf (stderr, "cannot activate client");
		exit (1);
	}

	/* connect the ports. Note: you can't do this before the
	   client is activated, because we can't allow connections to
	   be made to clients that aren't running.
	*/

	ports = jack_get_ports (client, NULL, NULL,
				JackPortIsPhysical|JackPortIsOutput);
	if (ports == NULL) {
		fprintf(stderr, "no physical capture ports\n");
		exit (1);
	}

	if (jack_connect (client, ports[0], jack_port_name (input_port))) {
		fprintf (stderr, "cannot connect input ports\n");
	}

	free (ports);

	ports = jack_get_ports (client, NULL, NULL,
				JackPortIsPhysical|JackPortIsInput);
	if (ports == NULL) {
		fprintf(stderr, "no physical playback ports\n");
		exit (1);
	}

	if (jack_connect (client, jack_port_name (output_port), ports[0])) {
		fprintf (stderr, "cannot connect output ports\n");
	}

	free (ports);

	while (1) {
		sleep (1);
	}

	jack_client_close (client);
	exit (0);
}
Esempio n. 27
0
jack_client_t* init_jack(void)
{
	const char* client_name = "simple_listener";
	const char* server_name = NULL;
	jack_options_t options = JackNullOption;
	jack_status_t status;

	client = jack_client_open (client_name, options, &status, server_name);

	if (NULL == client) {
		fprintf (stderr, "jack_client_open() failed\n ");
		shutdown_all(0);
		exit (1);
	}

	if (status & JackServerStarted) {
		fprintf (stderr, "JACK server started\n");
	}

	if (status & JackNameNotUnique) {
		client_name = jack_get_client_name(client);
		fprintf (stderr, "unique name `%s' assigned\n", client_name);
	}

	jack_set_process_callback(client, process_jack, 0);
	jack_on_shutdown(client, jack_shutdown, 0);

	outputports = (jack_port_t**) malloc (CHANNELS * sizeof (jack_port_t*));
	out = (jack_default_audio_sample_t**) malloc (CHANNELS * sizeof (jack_default_audio_sample_t*));
	ringbuffer = jack_ringbuffer_create (SAMPLE_SIZE * DEFAULT_RINGBUFFER_SIZE * CHANNELS);
	jack_ringbuffer_mlock(ringbuffer);

	memset(out, 0, sizeof (jack_default_audio_sample_t*)*CHANNELS);
	memset(ringbuffer->buf, 0, ringbuffer->size);

	for(int i = 0; i < CHANNELS; i++) {
		
		char* portName;
		if (asprintf(&portName, "output%d", i) < 0) {
			fprintf(stderr, "could not create portname for port %d\n", i);
			shutdown_all(0);
			exit(1);
		}	
		
		outputports[i] = jack_port_register (client, portName, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
		if (NULL == outputports[i]) {
			fprintf (stderr, "cannot register output port \"%d\"!\n", i);
			shutdown_all(0);
			exit (1);
		}
	}

	const char** ports;
	if (jack_activate (client)) {
		fprintf (stderr, "cannot activate client\n");		
		shutdown_all(0);
		exit(1);
	}

	ports = jack_get_ports(client, NULL, NULL, JackPortIsPhysical|JackPortIsInput);
	if(NULL == ports) { 
		fprintf (stderr, "no physical playback ports\n");		
		shutdown_all(0);
		exit(1);
	}

	int i = 0;
	while(i < CHANNELS && NULL != ports[i]) {
		if (jack_connect(client, jack_port_name(outputports[i]), ports[i]))
			fprintf (stderr, "cannot connect output ports\n");
		i++;
	}

	free(ports);
}
Esempio n. 28
0
int JackOutput::init( unsigned /*nBufferSize*/ )
{
	Preferences* pref = Preferences::get_instance();
	output_port_name_1 = pref->m_sJackPortName1;
	output_port_name_2 = pref->m_sJackPortName2;

	QString sClientName = "Hydrogen";

#ifdef H2CORE_HAVE_NSMSESSION
	QString nsmClientId = pref->getNsmClientId();

	if(!nsmClientId.isEmpty()){
		sClientName = nsmClientId;
	}
#endif


	jack_status_t status;
	int tries = 2;  // Sometimes jackd doesn't stop and start fast enough.
	while ( tries > 0 ) {
		--tries;

#ifdef H2CORE_HAVE_JACKSESSION
		if (pref->getJackSessionUUID().isEmpty()){
			client = jack_client_open(
						 sClientName.toLocal8Bit(),
						 JackNullOption,
						 &status);
		} else {
			const QByteArray uuid = pref->getJackSessionUUID().toLocal8Bit();
			client = jack_client_open(
						 sClientName.toLocal8Bit(),
						 JackSessionID,
						 &status,
						 uuid.constData());
		}
#else
		client = jack_client_open(
					 sClientName.toLocal8Bit(),
					 JackNullOption,
					 &status);
#endif
		switch(status) {
			case JackFailure:
				CLIENT_FAILURE("unknown error");
				break;
			case JackInvalidOption:
				CLIENT_FAILURE("invalid option");
				break;
			case JackNameNotUnique:
				if (client) {
					sClientName = jack_get_client_name(client);
					CLIENT_SUCCESS(QString("Jack assigned the client name '%1'").arg(sClientName));
				} else {
					CLIENT_FAILURE("name not unique");
				}
				break;
			case JackServerStarted:
				CLIENT_SUCCESS("JACK Server started for Hydrogen.");
				break;
			case JackServerFailed:
				CLIENT_FAILURE("unable to connect");
				break;
			case JackServerError:
				CLIENT_FAILURE("communication error");
				break;
			case JackNoSuchClient:
				CLIENT_FAILURE("unknown client type");
				break;
			case JackLoadFailure:
				CLIENT_FAILURE("can't load internal client");
				break;
			case JackInitFailure:
				CLIENT_FAILURE("can't initialize client");
				break;
			case JackShmFailure:
				CLIENT_FAILURE("unable to access shared memory");
				break;
			case JackVersionError:
				CLIENT_FAILURE("client/server protocol version mismatch");
			default:
				if (status) {
					ERRORLOG("Unknown status with JACK server.");
					if (client) {
						CLIENT_SUCCESS("Client pointer is *not* null..."
									   " assuming we're OK");
					}
				} else {
					CLIENT_SUCCESS("Connected to JACK server");
				}
		}
	}

	if (client == 0) return -1;

	// Here, client should either be valid, or NULL.
	jack_server_sampleRate = jack_get_sample_rate ( client );
	jack_server_bufferSize = jack_get_buffer_size ( client );

	pref->m_nSampleRate = jack_server_sampleRate;
	pref->m_nBufferSize = jack_server_bufferSize;

	/* tell the JACK server to call `process()' whenever
	   there is work to be done.
	*/
	jack_set_process_callback ( client, this->processCallback, 0 );

	/* tell the JACK server to call `srate()' whenever
	   the sample rate of the system changes.
	*/
	jack_set_sample_rate_callback ( client, jackDriverSampleRate, this );

	/* tell JACK server to update us if the buffer size
	   (frames per process cycle) changes.
	*/
	jack_set_buffer_size_callback ( client, jackDriverBufferSize, 0 );

	/* tell the JACK server to call `jack_shutdown()' if
	   it ever shuts down, either entirely, or if it
	   just decides to stop calling us.
	*/
	jack_on_shutdown ( client, jackDriverShutdown, 0 );

	/* create two ports */
	output_port_1 = jack_port_register ( client, "out_L", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
	output_port_2 = jack_port_register ( client, "out_R", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );

	Hydrogen *H = Hydrogen::get_instance();
	if ( ( output_port_1 == NULL ) || ( output_port_2 == NULL ) ) {
		H->raiseError( Hydrogen::JACK_ERROR_IN_PORT_REGISTER );
		return 4;
	}

	// clear buffers
	//	jack_default_audio_sample_t *out_L = (jack_default_audio_sample_t *) jack_port_get_buffer (output_port_1, jack_server_bufferSize);
	//	jack_default_audio_sample_t *out_R = (jack_default_audio_sample_t *) jack_port_get_buffer (output_port_2, jack_server_bufferSize);
	//	memset( out_L, 0, nBufferSize * sizeof( float ) );
	//	memset( out_R, 0, nBufferSize * sizeof( float ) );

#ifdef H2CORE_HAVE_LASH
	if ( pref->useLash() ){
		LashClient* lashClient = LashClient::get_instance();
		if (lashClient->isConnected()) {
			lashClient->setJackClientName(sClientName.toLocal8Bit().constData());
		}
	}
#endif

#ifdef H2CORE_HAVE_JACKSESSION
	jack_set_session_callback (client, jack_session_callback, (void*)this);
#endif

	if ( pref->m_bJackMasterMode == Preferences::USE_JACK_TIME_MASTER )
		initTimeMaster();

	return 0;
}
Esempio n. 29
0
int
main (int argc, char *argv[])
{
	const char *client_name;
	const char *server_name = NULL;
	jack_options_t options = JackNullOption;
	jack_status_t status;
  pcap_t* pcap;
  int   offline=0;
  char* iface=NULL;
  char* fname=NULL;
  int   slen=SNAPLEN;
  int   rs=RINGSIZE;
  char  errbuf[PCAP_ERRBUF_SIZE];
  int   promisc=PROMISC;
  double  rate=1.0;

  client_name = strrchr(argv[0], '/');
  if(!client_name)
    client_name=argv[0];
  else
    client_name++;

  int opt;
  while ((opt = getopt(argc, argv, "c:n:s:pi:r:t:b:")) != -1) {
    switch (opt) {
    case 'c':
        client_name=optarg;
        break;
    case 'n':
        server_name=optarg;
        options |= JackServerName;
        break;
    case 's':
        slen=atoi(optarg);
        break;
    case 'p':
        promisc=0;
        break;
    case 'i':
        iface=optarg;
        break;
    case 'r':
        fname=optarg;
        break;
    case 't':
        rate=atof(optarg);
        break;
    case 'b':
        rs=atoi(optarg);
        break;
    case '?':
        usage(argv[0],0);
        break;
    default: /* '?' */
        printf("Invalid option %c\n",opt);
        usage(argv[0],EXIT_FAILURE);
    }
  }

  /* open the pcap source */
  if ((iface && fname) || (!iface && !fname)) {
    printf("Please specify either a interface or a dump file as packet source\n");
    usage(argv[0],EXIT_FAILURE);
  }

  if (iface) {
    pcap = pcap_open_live(iface, slen, promisc, 0, errbuf);
    if (!pcap) {
      printf("Failed to open pcap source %s: %s\n", iface, errbuf);
      exit(EXIT_FAILURE);
    }
  }

  if (fname) {
    pcap = pcap_open_offline(fname, errbuf);
    if (!pcap) {
      printf("Failed to open dump file %s: %s\n", iface, errbuf);
      exit(EXIT_FAILURE);
    }
    offline=1;
  }

  /* set bpf filter */
  if (optind < argc) {
    int   i,s;
    char* bpf_str;
    struct bpf_program bpf_prog;

    for (s=0, i=optind; i<argc; i++) {
      s += strlen(argv[i]) + 1;
    }

    bpf_str = malloc(s);
    if (!bpf_str) {
      printf("Failed to malloc space for bpf filter\n");
      exit(EXIT_FAILURE);
    }

    bpf_str[0]=0;
    for (i=optind; i<argc; i++) {
      strcat(bpf_str,argv[i]);
      strcat(bpf_str," ");
    }

    printf("Setting bpf filter to %s\n", bpf_str);

    if (0>pcap_compile(pcap, &bpf_prog, bpf_str, 1, 0)) {
      printf("Failed to compile bpf filter\n");
      exit(EXIT_FAILURE);
    }

    if (0>pcap_setfilter(pcap, &bpf_prog)) {
      printf("Failed to set bpf filter\n");
      exit(EXIT_FAILURE);
    }

    pcap_freecode(&bpf_prog);
    free(bpf_str);
  }

  /* allocate ringbuffer */
  rb=jack_ringbuffer_create (rs*sizeof(jack_default_audio_sample_t));
  if (!rb) {
    printf("Failed to allocate ringbuffer\n");
    exit(EXIT_FAILURE);
  }

	/* open a client connection to the JACK server */
	client = jack_client_open (client_name, options, &status, server_name);
	if (client == NULL) {
		fprintf (stderr, "jack_client_open() failed, "
			 "status = 0x%2.0x\n", status);
		if (status & JackServerFailed) {
			fprintf (stderr, "Unable to connect to JACK server\n");
		}
		exit (1);
	}
	if (status & JackServerStarted) {
		fprintf (stderr, "JACK server started\n");
	}
	if (status & JackNameNotUnique) {
		client_name = jack_get_client_name(client);
		fprintf (stderr, "unique name `%s' assigned\n", client_name);
	}

	/* tell the JACK server to call `process()' whenever
	   there is work to be done.
	*/

	jack_set_process_callback (client, process, 0);

	/* tell the JACK server to call `jack_shutdown()' if
	   it ever shuts down, either entirely, or if it
	   just decides to stop calling us.
	*/

	jack_on_shutdown (client, jack_shutdown, 0);

	/* display the current sample rate. 
	 */

	printf ("engine sample rate: %" PRIu32 "\n",
		jack_get_sample_rate (client));

	/* create two ports */

	output_port = jack_port_register (client, "output",
					  JACK_DEFAULT_AUDIO_TYPE,
					  JackPortIsOutput, 0);

	/* Tell the JACK server that we are ready to roll.  Our
	 * process() callback will start running now. */

	if (jack_activate (client)) {
		fprintf (stderr, "cannot activate client");
		exit (1);
	}

	/* read packets from pcap source and write it into the ringbuffer */
  char    *buf;
  struct  pcap_pkthdr *h;
  u_int   pcnt=0;
  struct  timeval toff, tnow;
  
  /* mark offset for calculation on first packet */
  toff.tv_sec = -1;

  /* main loop: get packets from pcap source */
	while (0 <= pcap_next_ex(pcap, &h, (const u_char**) &buf)) {
    size_t  s;
    
    if (!buf) break;
    pcnt++;

    /* 
     * if we are reading from a file we sleep in the loop until the timestamp
     * of the packet is reached.
     */
    if (offline) for(;;) {
      struct timeval dt;
      
      gettimeofday(&tnow, NULL);
      
      /* initialize toff on first packet */
      if(toff.tv_sec == -1) {
        tvmov(toff,h->ts);
        tvsub(toff,tnow);
        tvnrm(toff);
      }

      tvmov(dt,h->ts);
      tvsub(dt,tnow);
      tvsub(dt,toff);
      tvnrm(dt);

      if (dt.tv_sec < 0 ) {
        break;
      }
      else if (dt.tv_sec > 0) {
        sleep(dt.tv_sec);
      }
      else {
        usleep(dt.tv_usec);
      }
    }

    /* check available buffer space */
    s = jack_ringbuffer_write_space(rb);
    if (!s)
      continue;

    /* truncate packet if there is not enough space in the buffer */
    if (s > h->caplen)
      s = h->caplen;

    /* write into the ringbuffer and get the next packet */
    jack_ringbuffer_write(rb,buf,s);
	}

	jack_client_close (client);
  
  struct  pcap_stat  ps;
  if(!pcap_stats(pcap, &ps)) {
    printf(
      "%d packets captured\n"
      "%d received by filter\n"
      "%d packets dropped by kernel\n",
      ps.ps_recv, pcnt, ps.ps_drop
    );
  }
  else {
    pcap_perror(pcap,"Failed to optain packet statistics");
  }
	exit (0);
}
Esempio n. 30
0
int main( int argc, char **argv ) {
	const char **ports;
	const char *client_name;
	const char *server_name = NULL;
	jack_options_t options = JackNullOption;
	jack_status_t status;
	int i;
 char projectM_data[1024];


std::string config_file;
 config_file = read_config();

 ConfigFile config(config_file);

 wvw = config.read<int>( "Window Width", 512 );
 wvh = config.read<int>( "Window Height", 512 );
 int fullscreen = 0;
 if (config.read("Fullscreen", true)) fullscreen = 1;
      else fullscreen = 0;
 

#ifdef DEBUG
	int value;
	int rgb_size[3];
#endif

  const SDL_VideoInfo* info = NULL;
  int bpp = 0;
  /* Flags we will pass into SDL_SetVideoMode. */
  int flags = 0;

  //JACK INIT
  //----------------------------------------------
	if (argc >= 2) {		/* client name specified? */
		client_name = argv[1];
		if (argc >= 3) {	/* server name specified? */
			server_name = argv[2];
			//			options |= JackServerName;
		}
	} else {			/* use basename of argv[0] */
		client_name = strrchr(argv[0], '/');
		if (client_name == 0) {
			client_name = argv[0];
		} else {
			client_name++;
		}
	}

	/* open a client connection to the JACK server */

	client = jack_client_open (client_name, options, &status, server_name);
	if (client == NULL) {
		fprintf (stderr, "jack_client_open() failed, "
			 "status = 0x%2.0x\n", status);
		if (status & JackServerFailed) {
			fprintf (stderr, "Unable to connect to JACK server\n");
		}
		exit (1);
	}
	if (status & JackServerStarted) {
		fprintf (stderr, "JACK server started\n");
	}
	if (status & JackNameNotUnique) {
		client_name = jack_get_client_name(client);
		fprintf (stderr, "unique name `%s' assigned\n", client_name);
	}

	/* tell the JACK server to call `process()' whenever
	   there is work to be done.
	*/

	jack_set_process_callback (client, process, 0);

	/* tell the JACK server to call `jack_shutdown()' if
	   it ever shuts down, either entirely, or if it
	   just decides to stop calling us.
	*/

	jack_on_shutdown (client, jack_shutdown, 0);

	/* display the current sample rate. 
	 */

	printf ("engine sample rate: %d\n",
		jack_get_sample_rate (client));

	/* create two ports */

	input_port = jack_port_register (client, "input",
					 JACK_DEFAULT_AUDIO_TYPE,
					 JackPortIsInput, 0);

	if (input_port == NULL) {
		fprintf(stderr, "no more JACK ports available\n");
		exit (1);
	}

	/* Tell the JACK server that we are ready to roll.  Our
	 * process() callback will start running now. */



	//END JACK INIT ----------------------------------
  init_display(wvw,wvh,&fvw,&fvh,fullscreen);   
    /** Setup some window stuff */
    SDL_WM_SetCaption( PROJECTM_TITLE, NULL );
  globalPM = new projectM(config_file);
    /** Initialise projectM */
 



    //JACK BEGIN-----------------------------

	if (jack_activate (client)) {
		fprintf (stderr, "cannot activate client");
		exit (1);
	}

	/* Connect the ports.  You can't do this before the client is
	 * activated, because we can't make connections to clients
	 * that aren't running.  Note the confusing (but necessary)
	 * orientation of the driver backend ports: playback ports are
	 * "input" to the backend, and capture ports are "output" from
	 * it.
	 */

	ports = jack_get_ports (client, NULL, NULL, JackPortIsOutput);
	if (ports == NULL) {
		fprintf(stderr, "no physical capture ports\n");
		exit (1);
	}
      
	
        i=0;
        while (ports[i]!=NULL) 
	 { 
            printf("Connecting to Jack port %s\n",ports[i]);
	    if (jack_connect (client, ports[i], jack_port_name (input_port))) {
	      fprintf (stderr, "cannot connect input ports\n");
	    }
	      i++;
	     }
	     
	free (ports);

	//----------------------------------END


    /** Initialise the thread */
    renderLoop();

    return 1;
}