Esempio n. 1
0
    JackAudioProvider(Synth *synth, const std::string &name)
      : synth_(synth)
    {
      SampleBufferAllocator::reset();
      client_ = jack_client_open(name.c_str(), JackNoStartServer, 0);
      if (client_ == NULL) {
	throw JackClientOpenError();
      }
      std::cout << "connected to jackd as client `" << name << "`\n";
      sl::sampleRate(jack_get_sample_rate(client_));
      jack_set_sample_rate_callback(client_, jackSampleRateCallback, 0);
      sl::bufferSize(jack_get_buffer_size(client_));
      jack_set_buffer_size_callback(client_, jackBufferSizeCallback, 0);
      jack_set_process_callback(client_, jackProcessCallback, this);
      midiInPort_ = jack_port_register(client_, "midi_in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
      std::cout << "registered midi port: midi_in\n";
      char portName[64];
      for (int i=0; i<Synth::InputBuffer::nChannels; i++) {
	snprintf(portName, sizeof(portName), "in_%u", i+1);
	inputPorts_[i] = jack_port_register(client_, portName, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
        std::cout << "registered audio port: " << portName << "\n";
      }
      for (int i=0; i<Synth::OutputBuffer::nChannels; i++) {
	snprintf(portName, sizeof(portName), "out_%u", i+1);
	outputPorts_[i] = jack_port_register(client_, portName, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
        std::cout << "registered audio port: " << portName << "\n";
      }
      for (int i=0; i<128; i++) {
        midiCtrlMap_[i] = i;
      }
      for (int i=11; i<=19; i++) {
        midiCtrlMap_[i] = i-10;
      }
      midiCtrlMap_[1] = 129; // modwheel
    }
Esempio n. 2
0
// Attempt to connect to the Jack server
static PyObject* attach(PyObject* self, PyObject* args)
{
    char* cname;
    if (! PyArg_ParseTuple(args, "s", &cname))
        return NULL;

    pyjack_client_t * client = self_or_global_client(self);
    if(client->pjc != NULL) {
        PyErr_SetString(JackUsageError, "A connection is already established.");
        return NULL;
    }

    jack_status_t status;
    client->pjc = jack_client_open(cname, JackNoStartServer, &status);
    if(client->pjc == NULL) {
        //TODO check status
        PyErr_SetString(JackNotConnectedError, "Failed to connect to Jack audio server.");
        return NULL;
    }

    jack_on_shutdown(client->pjc, pyjack_shutdown, client);
    signal(SIGHUP, pyjack_hangup); // TODO: This just works with global clients

    if(jack_set_process_callback(client->pjc, pyjack_process, client) != 0) {
        PyErr_SetString(JackError, "Failed to set jack process callback.");
        return NULL;
    }

    if(jack_set_buffer_size_callback(client->pjc, pyjack_buffer_size_changed, client) != 0) {
        PyErr_SetString(JackError, "Failed to set jack buffer size callback.");
        return NULL;
    }

    if(jack_set_sample_rate_callback(client->pjc, pyjack_sample_rate_changed, client) != 0) {
        PyErr_SetString(JackError, "Failed to set jack sample rate callback.");
        return NULL;
    }

    if(jack_set_port_registration_callback(client->pjc, pyjack_port_registration, client) != 0) {
        PyErr_SetString(JackError, "Failed to set jack port registration callback.");
        return NULL;
    }

    if(jack_set_graph_order_callback(client->pjc, pyjack_graph_order, client) != 0) {
        PyErr_SetString(JackError, "Failed to set jack graph order callback.");
        return NULL;
    }

    if(jack_set_xrun_callback(client->pjc, pyjack_xrun, client) != 0) {
        PyErr_SetString(JackError, "Failed to set jack xrun callback.");
        return NULL;
    }

    // Get buffer size
    client->buffer_size = jack_get_buffer_size(client->pjc);

    // Success!
    Py_INCREF(Py_None);
    return Py_None;
}
Esempio n. 3
0
int main (int argc, char *argv[])
{
	jack_client_t *client;
	char jack_client_name[] = "scope";
	jack_status_t jack_status;
	jack_options_t  jack_options = JackNullOption;		

	if ((client = jack_client_open(jack_client_name, jack_options, &jack_status)) == 0) {
		fprintf (stderr, "jack server not running?\n");
		return 1;
	}

	jack_set_process_callback (client, process, 0);
	jack_set_buffer_size_callback (client, bufsize, 0);
	jack_set_sample_rate_callback (client, srate, 0);
	jack_on_shutdown (client, jack_shutdown, 0);

	in_l = jack_port_register (client, "in_l", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
	in_r = jack_port_register (client, "in_r", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
	out_x = jack_port_register (client, "out_x", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
	out_y = jack_port_register (client, "out_y", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
	out_w = jack_port_register (client, "out_w", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);

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

	while (1)
		sleep(1);
	jack_client_close (client);
	exit (0);
}
    int JackAudioSystem::set_segment_size_callback(segment_size_callback_t cb, void* arg, QString* err_msg)
    {
	assert(_client);

	int rv = jack_set_buffer_size_callback( _client,
						cb,
						arg );
	if(rv && err_msg) {
	    *err_msg = "Could not set up jack callback.";
	}
	return rv;
    }
Esempio n. 5
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. 6
0
void gojack_generic_callback_sync_destroy(struct gojack_generic_callback_sync *sync) {
    jack_set_freewheel_callback(sync->client, NULL, NULL);
    jack_set_buffer_size_callback(sync->client, NULL, NULL);
    jack_set_sample_rate_callback(sync->client, NULL, NULL);
    jack_set_client_registration_callback(sync->client, NULL, NULL);
    jack_set_port_registration_callback(sync->client, NULL, NULL);
    jack_set_port_connect_callback(sync->client, NULL, NULL);
    jack_set_port_rename_callback(sync->client, NULL, NULL);
    jack_set_graph_order_callback(sync->client, NULL, NULL);
    jack_set_xrun_callback(sync->client, NULL, NULL);
    jack_set_latency_callback(sync->client, NULL, NULL);
    cgo_callback_sync_destroy(sync->base);
    pthread_mutex_destroy(&sync->lock);
    free(sync);
}
Esempio n. 7
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. 8
0
//--------------------------------------------------------------
void
ofxJackClient::setup(std::string _name)
{
	jack_status_t jack_status;

  if (!_name.empty())
      name = _name;
  
	if ((clientImpl = jack_client_open(name.c_str(), JackNullOption, &jack_status)) != NULL)
  {
    jack_set_process_callback(clientImpl, _onJackProcess, this);
    jack_set_buffer_size_callback(clientImpl, _onJackBufferSizeChanged, this);
    jack_set_sample_rate_callback(clientImpl, _onJackSampleRateChanged, this);
    jack_on_shutdown(clientImpl, _onJackShutdown, this);
  }
  else
    std::cerr << name << ":: jack server not running?" << std::endl;
}
Esempio n. 9
0
int main (int argc, char *argv[])
{
    static const char jack_client_name[] = "simulator";
    jack_status_t jack_status;


    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);
    glutInitWindowSize(640, 640);
    glutInitWindowPosition(0, 0);

    window = glutCreateWindow("OpenLase Simulator");

    glutDisplayFunc(&draw_gl);
    glutIdleFunc(&draw_gl);
    glutReshapeFunc(&resize_gl);
    glutKeyboardFunc(&key_gl);
    init_gl(640, 640);

    if ((client = jack_client_open(jack_client_name, JackNullOption, &jack_status)) == 0) {
        fprintf (stderr, "jack server not running?\n");
        return 1;
    }

    jack_set_process_callback (client, process, 0);
    jack_set_buffer_size_callback (client, bufsize, 0);
    jack_set_sample_rate_callback (client, srate, 0);
    jack_on_shutdown (client, jack_shutdown, 0);

    in_x = jack_port_register (client, "in_x", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
    in_y = jack_port_register (client, "in_y", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
    in_r = jack_port_register (client, "in_r", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
    in_g = jack_port_register (client, "in_g", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
    in_b = jack_port_register (client, "in_b", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);

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

    glutMainLoop();
    return 0;
}
Esempio n. 10
0
struct gojack_generic_callback_sync * gojack_generic_callback_sync_create(jack_client_t *client) {
    struct gojack_generic_callback_sync *sync = (struct gojack_generic_callback_sync *) malloc(sizeof(struct gojack_generic_callback_sync));
    void *arg = (void *) sync;
    sync->base = cgo_callback_sync_create();
    cgo_callback_sync_set_log_callback(sync->base, &handle_log, NULL);
    pthread_mutex_init(&sync->lock, NULL);
    sync->client = client;
    jack_set_freewheel_callback(client, &handle_freewheel, arg);
    jack_set_buffer_size_callback(client, &handle_buffer_size, arg);
    //jack_set_sample_rate_callback(client, &handle_sample_rate, arg);
    jack_set_client_registration_callback(client, &handle_client_registration, arg);
    jack_set_port_registration_callback(client, &handle_port_registration, arg);
    jack_set_port_connect_callback(client, &handle_port_connect, arg);
    jack_set_port_rename_callback(client, &handle_port_rename, arg);
    jack_set_graph_order_callback(client, &handle_graph_order, arg);
    jack_set_xrun_callback(client, &handle_xrun, arg);
    //jack_set_latency_callback(client, &handle_latency, arg);
    return sync;
}
Esempio n. 11
0
int main (int argc, char *argv[])
{
	int retval;
	jack_client_t *client;

	QApplication app(argc, argv);
	OutputSettings settings;
	
	cfg = &settings.cfg;

	if ((client = jack_client_new ("output")) == 0) {
		fprintf (stderr, "jack server not running?\n");
		return 1;
	}

	jack_set_process_callback (client, process, 0);
	jack_set_buffer_size_callback (client, bufsize, 0);
	jack_set_sample_rate_callback (client, srate, 0);
	jack_on_shutdown (client, jack_shutdown, 0);

	in_x = jack_port_register (client, "in_x", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
	in_y = jack_port_register (client, "in_y", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
	in_g = jack_port_register (client, "in_g", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
	out_x = jack_port_register (client, "out_x", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
	out_y = jack_port_register (client, "out_y", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
	out_g = jack_port_register (client, "out_g", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
	out_e = jack_port_register (client, "out_e", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);

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

	settings.show();

	retval = app.exec();

	jack_client_close (client);
	return retval;
}
Esempio n. 12
0
static void openJackStreams(RtJackGlobals *p)
{
    char    buf[256];
    int     i, j, k;
    CSOUND *csound = p->csound;

    /* connect to JACK server */
    p->client = jack_client_open(&(p->clientName[0]), JackNoStartServer, NULL);
    if (UNLIKELY(p->client == NULL))
      rtJack_Error(csound, -1, Str("could not connect to JACK server"));

    csound->system_sr(csound, jack_get_sample_rate(p->client));
    csound->Message(csound, "system sr: %f\n", csound->system_sr(csound,0));

    /* check consistency of parameters */
    if (UNLIKELY(p->nChannels < 1 || p->nChannels > 255))
      rtJack_Error(csound, -1, Str("invalid number of channels"));
    if (UNLIKELY(p->sampleRate < 1000 || p->sampleRate > 768000))
      rtJack_Error(csound, -1, Str("invalid sample rate"));
    if (UNLIKELY(p->sampleRate != (int) jack_get_sample_rate(p->client))) {
      snprintf(&(buf[0]), 256, Str("sample rate %d does not match "
                             "JACK sample rate %d"),
              p->sampleRate, (int) jack_get_sample_rate(p->client));
      rtJack_Error(p->csound, -1, &(buf[0]));
    }
    if (UNLIKELY(p->bufSize < 8 || p->bufSize > 32768))
      rtJack_Error(csound, -1, Str("invalid period size (-b)"));
    if (p->nBuffers < 2)
      p->nBuffers = 2;
    if (UNLIKELY((unsigned int) (p->nBuffers * p->bufSize) > (unsigned int) 65536))
      rtJack_Error(csound, -1, Str("invalid buffer size (-B)"));
    if (UNLIKELY(((p->nBuffers - 1) * p->bufSize)
                 < (int) jack_get_buffer_size(p->client)))
      rtJack_Error(csound, -1, Str("buffer size (-B) is too small"));

    /* register ports */
    rtJack_RegisterPorts(p);

    /* allocate ring buffers if not done yet */
    if (p->bufs == NULL)
      rtJack_AllocateBuffers(p);

    /* initialise ring buffers */
    p->csndBufCnt = 0;
    p->csndBufPos = 0;
    p->jackBufCnt = 0;
    p->jackBufPos = 0;
    for (i = 0; i < p->nBuffers; i++) {
      rtJack_TryLock(p->csound, &(p->bufs[i]->csndLock));
      rtJack_Unlock(p->csound, &(p->bufs[i]->jackLock));
      for (j = 0; j < p->nChannels; j++) {
        if (p->inputEnabled) {
          for (k = 0; k < p->bufSize; k++)
            p->bufs[i]->inBufs[j][k] = (jack_default_audio_sample_t) 0;
        }
        if (p->outputEnabled) {
          for (k = 0; k < p->bufSize; k++)
            p->bufs[i]->outBufs[j][k] = (jack_default_audio_sample_t) 0;
        }
      }
    }

    /* output port buffer pointer cache is invalid initially */
    if (p->outputEnabled)
      p->outPortBufs[0] = (jack_default_audio_sample_t*) NULL;

    /* register callback functions */
    if (UNLIKELY(jack_set_sample_rate_callback(p->client,
                                               sampleRateCallback, (void*) p)
                 != 0))
      rtJack_Error(csound, -1, Str("error setting sample rate callback"));
    if (UNLIKELY(jack_set_buffer_size_callback(p->client,
                                               bufferSizeCallback, (void*) p)
                 != 0))
      rtJack_Error(csound, -1, Str("error setting buffer size callback"));
#ifdef LINUX
    if (UNLIKELY(jack_set_freewheel_callback(p->client,
                                             freeWheelCallback, (void*) p)
                 != 0))
      rtJack_Error(csound, -1, Str("error setting freewheel callback"));
#endif
    if (UNLIKELY(jack_set_xrun_callback(p->client, xrunCallback, (void*) p) != 0))
      rtJack_Error(csound, -1, Str("error setting xrun callback"));
    jack_on_shutdown(p->client, shutDownCallback, (void*) p);
    if (UNLIKELY(jack_set_process_callback(p->client,
                                           processCallback, (void*) p) != 0))
      rtJack_Error(csound, -1, Str("error setting process callback"));

    /* activate client */
    if (UNLIKELY(jack_activate(p->client) != 0))
      rtJack_Error(csound, -1, Str("error activating JACK client"));

    /* connect ports if requested */
    if (p->inputEnabled) {
      char dev[128], *dev_final, *sp;
      {
        int i,n = listDevices(csound,NULL,0);
        CS_AUDIODEVICE *devs = (CS_AUDIODEVICE *)
                malloc(n*sizeof(CS_AUDIODEVICE));
        listDevices(csound,devs,0);
        for(i=0; i < n; i++)
          csound->Message(csound, " %d: %s (%s)\n",
                          i, devs[i].device_id, devs[i].device_name);
        strncpy(dev, devs[0].device_name, 128);
        free(devs);
      }
      if(p->inDevName != NULL) {
        strncpy(dev, p->inDevName, 128); dev[127]='\0';
      }
      //if (dev) {
      dev_final = dev;
      sp = strchr(dev_final, '\0');
      if (!isalpha(dev_final[0])) dev_final++;
      for (i = 0; i < p->nChannels; i++) {
        snprintf(sp, 128-(dev-sp), "%d", i + 1);
        if (UNLIKELY(jack_connect(p->client, dev_final,
                                  jack_port_name(p->inPorts[i])) != 0)) {
          //rtJack_Error(csound, -1, Str("error connecting input ports"));
          csound->Warning(csound,
                          Str("not autoconnecting input channel %d \n"
                              "(needs manual connection)"), i+1);
        }
      }
      *sp = (char) 0;
      //}

    }
    if (p->outputEnabled) {
      char dev[128], *dev_final, *sp;
      {
          int i,n = listDevices(csound,NULL,1);
          CS_AUDIODEVICE *devs = (CS_AUDIODEVICE *)
                  malloc(n*sizeof(CS_AUDIODEVICE));
          listDevices(csound,devs,1);
          for(i=0; i < n; i++)
            csound->Message(csound, " %d: %s (%s)\n",
                            i, devs[i].device_id, devs[i].device_name);
          strncpy(dev, devs[0].device_name, 128);
          free(devs);
      }
      if (p->outDevName != NULL) {
        strncpy(dev, p->outDevName, 128); dev[127]='\0';
      }
      //if (dev) { this test is rubbish
      dev_final = dev;
      sp = strchr(dev_final, '\0');
      if(!isalpha(dev_final[0])) dev_final++;
      for (i = 0; i < p->nChannels; i++) {
        snprintf(sp, 128-(dev-sp), "%d", i + 1);
        if (jack_connect(p->client, jack_port_name(p->outPorts[i]),
                         dev_final) != 0) {
          //rtJack_Error(csound, -1, Str("error connecting output ports"));
          csound->Warning(csound, Str("not autoconnecting input channel %d \n"
                                      "(needs manual connection)"), i+1);

        }
      }
      *sp = (char) 0;
    }
    /* stream is now active */
    p->jackState = 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;
}
bool JackAudioInterface::go()
{
    // start JACK
    if (jack_server_is_running())
    {
        qDebug() << "JackAudioInterface::start Warning: JACK was already running" << endl;
    }
    else
    {
        qDebug() << "JackAudioInterface::start Starting JACK:" << endl;
        pid_t jackPID = start_jack(m_sampleRate, m_bufferSamples);
        qDebug() << "JackAudioInterface::start Finished starting JACK" << endl;
        if (jackPID >= 0)
        {
            qDebug() << "JackAudioInterface::start: Successfully started the JACK server with PID " << QString::number(jackPID) << endl;
        }
        else
        {
            qWarning() << "JackAudioInterface::start: Couldn't start JACK server" << endl;
            return false;
        }
    }
    
    // create a jack client
    if (!open_jack_client())
    {
        qWarning() << "JackAudioInterface::start Couldn't open JACK client" << endl;
        return false;
    }

    qDebug() << "JackAudioInterface::start opened JACK client" << endl;

    // check that buffer size and sample rate are correct
    if (jack_get_buffer_size(m_client) != m_bufferSamples || jack_get_sample_rate(m_client) != m_sampleRate)
    {
        qWarning() << "JackAudioInterface::start ERROR: JACK is running with incorrect parameters: sample rate = " << jack_get_sample_rate(m_client) << ", buffer size = " << jack_get_buffer_size(m_client) << endl;
        // TODO: how to communicate this error back to the app?
        return false;
    }
    
    qDebug() << "JackAudioInterface::start checked JACK parameters" << endl;

    // register jack callbacks
    jack_set_buffer_size_callback(m_client, JackAudioInterface::jack_buffer_size_changed, this);
    jack_set_process_callback(m_client, JackAudioInterface::jack_process, this);
    jack_set_sample_rate_callback(m_client, JackAudioInterface::jack_sample_rate_changed, this);
    jack_on_shutdown(m_client, JackAudioInterface::jack_shutdown, this);
    jack_set_xrun_callback(m_client, JackAudioInterface::jack_xrun, this);

    qDebug() << "JackAudioInterface::start registered JACK callbacks" << endl;

     // activate client (starts processing)
    if (jack_activate(m_client) != 0)
    {
        qDebug() << "JackAudioInterface::start Couldn't activate JACK client" << endl;
        return false;
    }

    qDebug() << "JackAudioInterface::start activated JACK client" << endl;
    return true;
}
Esempio n. 15
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. 16
0
static int instream_open_jack(struct SoundIoPrivate *si, struct SoundIoInStreamPrivate *is) {
    SoundIoInStream *instream = &is->pub;
    SoundIoInStreamJack *isj = &is->backend_data.jack;
    SoundIoJack *sij = &si->backend_data.jack;
    SoundIoDevice *device = instream->device;
    SoundIoDevicePrivate *dev = (SoundIoDevicePrivate *)device;
    SoundIoDeviceJack *dj = &dev->backend_data.jack;

    if (sij->is_shutdown)
        return SoundIoErrorBackendDisconnected;

    if (!instream->name)
        instream->name = "SoundIoInStream";

    instream->software_latency = device->software_latency_current;
    isj->period_size = sij->period_size;

    jack_status_t status;
    isj->client = jack_client_open(instream->name, JackNoStartServer, &status);
    if (!isj->client) {
        instream_destroy_jack(si, is);
        assert(!(status & JackInvalidOption));
        if (status & JackShmFailure)
            return SoundIoErrorSystemResources;
        if (status & JackNoSuchClient)
            return SoundIoErrorNoSuchClient;
        return SoundIoErrorOpeningDevice;
    }

    int err;
    if ((err = jack_set_process_callback(isj->client, instream_process_callback, is))) {
        instream_destroy_jack(si, is);
        return SoundIoErrorOpeningDevice;
    }
    if ((err = jack_set_buffer_size_callback(isj->client, instream_buffer_size_callback, is))) {
        instream_destroy_jack(si, is);
        return SoundIoErrorOpeningDevice;
    }
    if ((err = jack_set_sample_rate_callback(isj->client, instream_sample_rate_callback, is))) {
        instream_destroy_jack(si, is);
        return SoundIoErrorOpeningDevice;
    }
    if ((err = jack_set_xrun_callback(isj->client, instream_xrun_callback, is))) {
        instream_destroy_jack(si, is);
        return SoundIoErrorOpeningDevice;
    }
    jack_on_shutdown(isj->client, instream_shutdown_callback, is);

    jack_nframes_t max_port_latency = 0;

    // register ports and map channels
    int connected_count = 0;
    for (int ch = 0; ch < instream->layout.channel_count; ch += 1) {
        SoundIoChannelId my_channel_id = instream->layout.channels[ch];
        const char *channel_name = soundio_get_channel_name(my_channel_id);
        unsigned long flags = JackPortIsInput;
        if (!instream->non_terminal_hint)
            flags |= JackPortIsTerminal;
        jack_port_t *jport = jack_port_register(isj->client, channel_name, JACK_DEFAULT_AUDIO_TYPE, flags, 0);
        if (!jport) {
            instream_destroy_jack(si, is);
            return SoundIoErrorOpeningDevice;
        }
        SoundIoInStreamJackPort *isjp = &isj->ports[ch];
        isjp->dest_port = jport;
        // figure out which source port this connects to
        SoundIoDeviceJackPort *djp = find_port_matching_channel(device, my_channel_id);
        if (djp) {
            isjp->source_port_name = djp->full_name;
            isjp->source_port_name_len = djp->full_name_len;
            connected_count += 1;
            max_port_latency = max(max_port_latency, djp->latency_range.max);
        }
    }
    // If nothing got connected, channel layouts aren't working. Just send the
    // data in the order of the ports.
    if (connected_count == 0) {
        max_port_latency = 0;
        instream->layout_error = SoundIoErrorIncompatibleDevice;

        int ch_count = min(instream->layout.channel_count, dj->port_count);
        for (int ch = 0; ch < ch_count; ch += 1) {
            SoundIoInStreamJackPort *isjp = &isj->ports[ch];
            SoundIoDeviceJackPort *djp = &dj->ports[ch];
            isjp->source_port_name = djp->full_name;
            isjp->source_port_name_len = djp->full_name_len;
            max_port_latency = max(max_port_latency, djp->latency_range.max);
        }
    }

    isj->hardware_latency = max_port_latency / (double)instream->sample_rate;

    return 0;
}
Esempio n. 17
0
int soundio_jack_init(struct SoundIoPrivate *si) {
    SoundIoJack *sij = &si->backend_data.jack;
    SoundIo *soundio = &si->pub;

    if (!global_msg_callback_flag.test_and_set()) {
        if (soundio->jack_error_callback)
            jack_set_error_function(soundio->jack_error_callback);
        if (soundio->jack_info_callback)
            jack_set_info_function(soundio->jack_info_callback);
        global_msg_callback_flag.clear();
    }

    sij->mutex = soundio_os_mutex_create();
    if (!sij->mutex) {
        destroy_jack(si);
        return SoundIoErrorNoMem;
    }

    sij->cond = soundio_os_cond_create();
    if (!sij->cond) {
        destroy_jack(si);
        return SoundIoErrorNoMem;
    }

    // We pass JackNoStartServer due to
    // https://github.com/jackaudio/jack2/issues/138
    jack_status_t status;
    sij->client = jack_client_open(soundio->app_name, JackNoStartServer, &status);
    if (!sij->client) {
        destroy_jack(si);
        assert(!(status & JackInvalidOption));
        if (status & JackShmFailure)
            return SoundIoErrorSystemResources;
        if (status & JackNoSuchClient)
            return SoundIoErrorNoSuchClient;

        return SoundIoErrorInitAudioBackend;
    }

    int err;
    if ((err = jack_set_buffer_size_callback(sij->client, buffer_size_callback, si))) {
        destroy_jack(si);
        return SoundIoErrorInitAudioBackend;
    }
    if ((err = jack_set_sample_rate_callback(sij->client, sample_rate_callback, si))) {
        destroy_jack(si);
        return SoundIoErrorInitAudioBackend;
    }
    if ((err = jack_set_port_registration_callback(sij->client, port_registration_callback, si))) {
        destroy_jack(si);
        return SoundIoErrorInitAudioBackend;
    }
    if ((err = jack_set_port_rename_callback(sij->client, port_rename_calllback, si))) {
        destroy_jack(si);
        return SoundIoErrorInitAudioBackend;
    }
    jack_on_shutdown(sij->client, shutdown_callback, si);

    sij->refresh_devices_flag.clear();
    sij->period_size = jack_get_buffer_size(sij->client);
    sij->sample_rate = jack_get_sample_rate(sij->client);

    if ((err = jack_activate(sij->client))) {
        destroy_jack(si);
        return SoundIoErrorInitAudioBackend;
    }

    if ((err = refresh_devices(si))) {
        destroy_jack(si);
        return err;
    }

    si->destroy = destroy_jack;
    si->flush_events = flush_events_jack;
    si->wait_events = wait_events_jack;
    si->wakeup = wakeup_jack;
    si->force_device_scan = force_device_scan_jack;

    si->outstream_open = outstream_open_jack;
    si->outstream_destroy = outstream_destroy_jack;
    si->outstream_start = outstream_start_jack;
    si->outstream_begin_write = outstream_begin_write_jack;
    si->outstream_end_write = outstream_end_write_jack;
    si->outstream_clear_buffer = outstream_clear_buffer_jack;
    si->outstream_pause = outstream_pause_jack;
    si->outstream_get_latency = outstream_get_latency_jack;

    si->instream_open = instream_open_jack;
    si->instream_destroy = instream_destroy_jack;
    si->instream_start = instream_start_jack;
    si->instream_begin_read = instream_begin_read_jack;
    si->instream_end_read = instream_end_read_jack;
    si->instream_pause = instream_pause_jack;
    si->instream_get_latency = instream_get_latency_jack;

    return 0;
}
Esempio n. 18
0
/*****************************************************************************
 *
 * JACK_INIT()
 *
 * Setup the jack client.
 *
 *****************************************************************************/
int
jack_init(void) {
    const char		*server_name = NULL;
    static char		client_name[32];
    jack_options_t	options = JackNoStartServer | JackUseExactName;
    jack_status_t	status = 0;

    if (debug) {
	fprintf (stderr, "Initializing JACK client from thread 0x%lx\n", pthread_self());
    }

    if (client != NULL) {
	if (debug) {
	    fprintf (stderr, "Warning: closing stale JACK client...\n");
	}
	jack_client_close (client);
	client = NULL;
    }

    /* open a client connection to the JACK server */
    for( phasex_instance = 0; phasex_instance != 16; phasex_instance++)
    {
    if(!phasex_instance) {
        snprintf (client_name, 32, "%s", phasex_title);
    }
    else {
        snprintf (client_name, 32, "%s-%02d", phasex_title, phasex_instance);
    }
    printf("Using client name %s\n", client_name);
    if (client = jack_client_open ((const char *)client_name, options, &status, server_name))
        break;
    }
    
    /* deal with non-unique client name */
    if (status & JackNameNotUnique) {
	fprintf (stderr, "Unable to start JACK client '%s'!\n", client_name);
	return 1;
    }

    /* deal with jack server problems */
    if (status & (JackServerFailed | JackServerError)) {
	if (debug) {
	    fprintf (stderr, "Unable to connect to JACK server.  Status = 0x%2.0x\n", status);
	}
	return 1;
    }

    /* deal with missing client */
    if (client == NULL) {
	if (debug) {
	    fprintf (stderr, "Unable to open JACK client.  Status = 0x%2.0x\n", status);
	}
	return 1;
    }

    /* callback for when jack shuts down (needs to be set as early as possible) */
    jack_on_shutdown (client, jack_shutdown_handler, 0);

    if (debug) {
	fprintf (stderr, "Unique JACK client name '%s' assigned.\n", client_name);
    }

    /* notify if we started jack server */
    if (status & JackServerStarted) {
	fprintf (stderr, "JACK server started.\n");
    }

    /* report realtime scheduling in JACK */
    if (debug) {
	if (jack_is_realtime (client)) {
	    fprintf (stderr, "JACK is running with realtime scheduling.\n");
	}
	else {
	    fprintf (stderr, "JACK is running without realtime scheduling.\n");
	}
    }

    /* get sample rate early and notify other threads */
    sample_rate = jack_get_sample_rate (client);

    if (debug) {
	fprintf (stderr, "JACK sample rate:  %d\n", sample_rate);
    }

    /* scale sample rate depending on mode */
    switch (sample_rate_mode) {
    case SAMPLE_RATE_UNDERSAMPLE:
	sample_rate /= 2;
	break;
    case SAMPLE_RATE_OVERSAMPLE:
	sample_rate *= 2;
	break;
    }

    /* set samplerate related vars */
    f_sample_rate = (sample_t)sample_rate;
    nyquist_freq  = (sample_t)(sample_rate / 2);
    wave_period   = (sample_t)(F_WAVEFORM_SIZE / (double)sample_rate);

    if (debug) {
	fprintf (stderr, "Internal sample rate:  %d\n", sample_rate);
    }

    /* callback for setting our sample rate when jack tells us to */
    jack_set_sample_rate_callback (client, jack_samplerate_handler, 0);

    /* now that we have the sample rate, signal anyone else who needs to know */
    pthread_mutex_lock (&sample_rate_mutex);
    pthread_cond_broadcast (&sample_rate_cond);
    pthread_mutex_unlock (&sample_rate_mutex);

    /* get buffer size */
    buffer_size = jack_get_buffer_size (client) * 2;
    if (buffer_size > (PHASEX_MAX_BUFSIZE / 2)) {
    	fprintf (stderr, "JACK requested buffer size:  %d.  Max is:  %d.\n",
		 buffer_size, (PHASEX_MAX_BUFSIZE / 2));
    	fprintf (stderr, "JACK buffer size exceeded.  Closing client...\n");
	jack_client_close (client);
	client = NULL;
	jack_running = 0;
	return 1;
    }
    buffer_full = buffer_size;
    if (debug) {
	fprintf (stderr, "JACK output buffer size:  %d.\n", buffer_size);
    }

    /* callback for setting our buffer size when jack tells us to */
    jack_set_buffer_size_callback (client, jack_bufsize_handler, 0);

    /* callback for dealing with xruns */
    jack_set_xrun_callback (client, jack_xrun_handler, 0);

    /* create ports */
    input_port1 = jack_port_register (client, "in_1",
				      JACK_DEFAULT_AUDIO_TYPE,
				      JackPortIsInput, 0);
    input_port2 = jack_port_register (client, "in_2",
				      JACK_DEFAULT_AUDIO_TYPE,
				      JackPortIsInput, 0);

    output_port1 = jack_port_register (client, "out_1",
				       JACK_DEFAULT_AUDIO_TYPE,
				       JackPortIsOutput, 0);
    output_port2 = jack_port_register (client, "out_2",
				       JACK_DEFAULT_AUDIO_TYPE,
				       JackPortIsOutput, 0);

    if ( (output_port1 == NULL) || (output_port2 == NULL) ||
	 (input_port1 == NULL) || (input_port2 == NULL) )
    {
	fprintf (stderr, "JACK has no output ports available.\n");
	jack_client_close (client);
	client = NULL;
	jack_running = 0;
	return 0;
    }

    /* set callback for jack to grab audio data */
    jack_set_process_callback (client, process_buffer, 0);

    return 0;
}
Esempio n. 19
0
// Initialise Jack related stuff
static jack_client_t* init_jack( MastSendTool* tool ) 
{
	const char* client_name = tool->get_tool_name();
	jack_client_t* client = NULL;
	jack_status_t status;
	size_t ringbuffer_size = 0;
	int port_count = tool->get_input_channels();
	int i = 0;


    pthread_mutex_init(&g_ringbuffer_cond_mutex, NULL);
    pthread_cond_init(&g_ringbuffer_cond, NULL);

	// Register with Jack
	if ((client = jack_client_open(client_name, g_client_opt, &status)) == 0) {
		MAST_ERROR("Failed to start jack client: 0x%x", status);
		return NULL;
	} else {
		MAST_INFO( "JACK client registered as '%s'", jack_get_client_name( client ) );
	}

	// Create our input port(s)
	if (port_count==1) {
		if (!(g_jackport[0] = jack_port_register(client, "mono", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0))) {
			MAST_ERROR("Cannot register mono input port");
			return NULL;
		}
	} else {
		if (!(g_jackport[0] = jack_port_register(client, "left", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0))) {
			MAST_ERROR("Cannot register left input port");
			return NULL;
		}
		
		if (!(g_jackport[1] = jack_port_register(client, "right", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0))) {
			MAST_ERROR( "Cannot register left input port");
			return NULL;
		}
	}
	
	// Create ring buffer
	ringbuffer_size = jack_get_sample_rate( client ) * g_rb_duration * port_count * sizeof(int16_t) / 1000;
	MAST_INFO("Duration of the ring buffer is %d ms (%d bytes)", g_rb_duration, (int)ringbuffer_size );
	if (!(g_ringbuffer = jack_ringbuffer_create( ringbuffer_size ))) {
		MAST_ERROR("Cannot create ringbuffer %d", i);
		return NULL;
	}

	// Register callbacks
	jack_on_shutdown(client, shutdown_callback, tool );
	jack_set_buffer_size_callback( client, buffersize_callback, tool);
	jack_set_process_callback(client, process_callback, tool);
	
	// Create conversion buffer
	buffersize_callback( jack_get_buffer_size(client), tool );

	// Activate JACK
	if (jack_activate(client)) MAST_FATAL("Cannot activate JACK client");
	
	/* Auto connect ports ? */
	if (g_do_autoconnect) autoconnect_jack_ports( client, tool->get_input_channels() );
	
	return client;
}
Esempio n. 20
0
int jack_initialize (jack_client_t *client, const char *string){
  struct Data *data;
  AEffect *effect;
  snd_seq_t *seq;

  int lokke;

  char pluginname[500];
  char *seqname;

  bool dontconnectjackports=false;

  sprintf(pluginname,"%s",string);
  seqname=&pluginname[0];

  if(strstr(string,":")){
    seqname=strstr(pluginname,":")+1;
    strstr(pluginname,":")[0]=0;
    if(strstr(seqname,":")){
      strstr(seqname,":")[0]=0;
      dontconnectjackports=true;
    }
  }
  
  printf("plugname: %s, seqname: %s, dontconnect: %s\n",pluginname,seqname,dontconnectjackports==true?"true":"false");
     
  //printf("rate: %f, blocksize: %d\n",(float)jack_get_sample_rate(client),jack_get_buffer_size(client));
  
  /*****************************
       VST Init
  *****************************/

  effect=VSTLIB_new(pluginname);
  if(effect==NULL) return 1;

  effect->dispatcher (effect,
		      effOpen,
		      0, 0, NULL, 0);

  effect->dispatcher(
		     effect,
		     effSetSampleRate,
		     0,0,NULL,(float)jack_get_sample_rate(client));

  effect->dispatcher(effect,
		     effSetBlockSize,
		     0, jack_get_buffer_size(client), NULL, 0);

  effect->dispatcher(effect,
		     effMainsChanged,
		     0, 1, NULL, 0);

  effect->dispatcher (effect,
		      effEditOpen,
		      0, 0, NULL, 0);
  

  /*****************************
       MIDI init
  *****************************/

  seq=create_alsa_seq(seqname,true);
  if(seq==NULL){
    VSTLIB_delete(effect);
    return 2;
  }

  data=calloc(1,sizeof(struct Data));
  data->seq=seq;
  data->client=client;
  data->effect=effect;
  data->toquit=false;

  pthread_create(&data->midithread,NULL,midireceiver,data);
  {
    struct sched_param rt_param={0};
    int err;
    rt_param.sched_priority = 1; // This is not an important thread.
    err=pthread_setschedparam(data->midithread,SCHED_FIFO, &rt_param);
    if(err){
      fprintf(stderr,"Could not set realtime priority for midi thread.\n");
    }
  }


  /*****************************
       Jack init
  *****************************/

  jack_set_process_callback(client,process,data);
  jack_set_buffer_size_callback(client,buffersizecallback,data);

  data->num_inputs=data->effect->numInputs;
  data->num_outputs=data->effect->numOutputs;

  data->input_ports=calloc(sizeof(jack_port_t*),data->num_inputs);
  data->output_ports=calloc(sizeof(jack_port_t*),data->num_outputs);

  for(lokke=0;lokke<data->num_inputs;lokke++){
    char temp[500];
    sprintf(temp,"in%d",lokke);
    data->input_ports[lokke]=jack_port_register(client,temp, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
  }
  for(lokke=0;lokke<data->num_outputs;lokke++){
    char temp[500];
    sprintf(temp,"out%d",lokke);
    data->output_ports[lokke]=jack_port_register(client,temp, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
  }

  
  jack_activate (client);


  if(dontconnectjackports==false){
    for(lokke=0;lokke<data->num_inputs;lokke++){
      char temp[500];
      sprintf(temp,"alsa_pcm:capture_%d",lokke+1);
      jack_connect(client,temp,jack_port_name(data->input_ports[lokke]));
    }
    for(lokke=0;lokke<data->num_outputs;lokke++){
      char temp[500];
      sprintf(temp,"alsa_pcm:playback_%d",lokke+1);
      jack_connect(client,jack_port_name(data->output_ports[lokke]),temp);
    }
  }


  return 0;
}
    PluginJack(jack_client_t* const client)
        : fPlugin(),
          fUI(this, 0, nullptr, setParameterValueCallback, setStateCallback, nullptr, setSizeCallback, fPlugin.getInstancePointer()),
          fClient(client)
    {
        char strBuf[0xff+1];
        strBuf[0xff] = '\0';

#if DISTRHO_PLUGIN_NUM_INPUTS > 0
        for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i)
        {
            std::snprintf(strBuf, 0xff, "in%i", i+1);
            fPortAudioIns[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
        }
#endif

#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0
        for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i)
        {
            std::snprintf(strBuf, 0xff, "out%i", i+1);
            fPortAudioOuts[i] = jack_port_register(fClient, strBuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
        }
#endif

#if DISTRHO_PLUGIN_IS_SYNTH
        fPortMidiIn = jack_port_register(fClient, "midi-in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
#endif

#if DISTRHO_PLUGIN_WANT_PROGRAMS
        if (fPlugin.getProgramCount() > 0)
        {
            fPlugin.setProgram(0);
            fUI.programChanged(0);
        }
#endif

        if (const uint32_t count = fPlugin.getParameterCount())
        {
            fLastOutputValues = new float[count];

            for (uint32_t i=0; i < count; ++i)
            {
                if (fPlugin.isParameterOutput(i))
                {
                    fLastOutputValues[i] = fPlugin.getParameterValue(i);
                }
                else
                {
                    fLastOutputValues[i] = 0.0f;
                    fUI.parameterChanged(i, fPlugin.getParameterValue(i));
                }
            }
        }
        else
        {
            fLastOutputValues = nullptr;
        }

        jack_set_buffer_size_callback(fClient, jackBufferSizeCallback, this);
        jack_set_sample_rate_callback(fClient, jackSampleRateCallback, this);
        jack_set_process_callback(fClient, jackProcessCallback, this);
        jack_on_shutdown(fClient, jackShutdownCallback, this);

        jack_activate(fClient);

        if (const char* const name = jack_get_client_name(fClient))
            fUI.setWindowTitle(name);
        else
            fUI.setWindowTitle(fPlugin.getName());
    }
Esempio n. 22
0
int
Server_jack_init(Server *self) {
    char client_name[32];
    char name[16];
    const char *server_name = "server";
    jack_options_t options = JackNullOption;
    jack_status_t status;
    int sampleRate = 0;
    int bufferSize = 0;
    int nchnls = 0;
    int total_nchnls = 0;
    int index = 0;
    int ret = 0;
    assert(self->audio_be_data == NULL);
    PyoJackBackendData *be_data = (PyoJackBackendData *) malloc(sizeof(PyoJackBackendData *));
    self->audio_be_data = (void *) be_data;
    be_data->jack_in_ports = (jack_port_t **) calloc(self->ichnls + self->input_offset, sizeof(jack_port_t *));
    be_data->jack_out_ports = (jack_port_t **) calloc(self->nchnls + self->output_offset, sizeof(jack_port_t *));
    strncpy(client_name,self->serverName, 32);
    be_data->jack_client = jack_client_open(client_name, options, &status, server_name);
    if (be_data->jack_client == NULL) {
        Server_error(self, "Jack error: Unable to create JACK client\n");
        if (status & JackServerFailed) {
            Server_debug(self, "Jack error: jack_client_open() failed, "
            "status = 0x%2.0x\n", status);
        }
        return -1;
    }
    if (status & JackServerStarted) {
        Server_warning(self, "JACK server started.\n");
    }
    if (strcmp(self->serverName, jack_get_client_name(be_data->jack_client)) ) {
        strcpy(self->serverName, jack_get_client_name(be_data->jack_client));
        Server_warning(self, "Jack name `%s' assigned\n", self->serverName);
    }

    sampleRate = jack_get_sample_rate (be_data->jack_client);
    if (sampleRate != self->samplingRate) {
        self->samplingRate = (double)sampleRate;
        Server_warning(self, "Sample rate set to Jack engine sample rate: %" PRIu32 "\n", sampleRate);
    }
    else {
        Server_debug(self, "Jack engine sample rate: %" PRIu32 "\n", sampleRate);
    }
    if (sampleRate <= 0) {
        Server_error(self, "Invalid Jack engine sample rate.");
        jack_client_close(be_data->jack_client);
        return -1;
    }
    bufferSize = jack_get_buffer_size(be_data->jack_client);
    if (bufferSize != self->bufferSize) {
        self->bufferSize = bufferSize;
        Server_warning(self, "Buffer size set to Jack engine buffer size: %" PRIu32 "\n", bufferSize);
    }
    else {
        Server_debug(self, "Jack engine buffer size: %" PRIu32 "\n", bufferSize);
    }

    nchnls = total_nchnls = self->ichnls + self->input_offset;
    while (nchnls-- > 0) {
        index = total_nchnls - nchnls - 1;
        ret = sprintf(name, "input_%i", index + 1);
        if (ret > 0) {
            be_data->jack_in_ports[index]
            = jack_port_register(be_data->jack_client, name,
                                 JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
        }

        if ((be_data->jack_in_ports[index] == NULL)) {
            Server_error(self, "Jack: no more JACK input ports available\n");
            return -1;
        }
    }

    nchnls = total_nchnls = self->nchnls + self->output_offset;
    while (nchnls-- > 0) {
        index = total_nchnls - nchnls - 1;
        ret = sprintf(name, "output_%i", index + 1);
        if (ret > 0) {
            be_data->jack_out_ports[index]
            = jack_port_register(be_data->jack_client, name,
                                 JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
        }
        if ((be_data->jack_out_ports[index] == NULL)) {
            Server_error(self, "Jack: no more JACK output ports available\n");
            return -1;
        }
    }
    jack_set_error_function(jack_error_cb);
    jack_set_sample_rate_callback(be_data->jack_client, jack_srate_cb, (void *) self);
    jack_on_shutdown(be_data->jack_client, jack_shutdown_cb, (void *) self);
    jack_set_buffer_size_callback(be_data->jack_client, jack_bufsize_cb, (void *) self);
    return 0;
}
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;
}
Esempio n. 24
0
void samplv1_jack::open ( const char *client_id )
{
    // init param ports
    for (uint32_t i = 0; i < samplv1::NUM_PARAMS; ++i) {
        const samplv1::ParamIndex index = samplv1::ParamIndex(i);
        m_params[i] = samplv1_param::paramDefaultValue(index);
        samplv1::setParamPort(index, &m_params[i]);
    }

    // open client
    m_client = ::jack_client_open(client_id, JackNullOption, NULL);
    if (m_client == NULL)
        return;

    // set sample rate
    samplv1::setSampleRate(float(jack_get_sample_rate(m_client)));
//	samplv1::reset();

    // register audio ports & buffers
    uint16_t nchannels = samplv1::channels();

    m_audio_ins  = new jack_port_t * [nchannels];
    m_audio_outs = new jack_port_t * [nchannels];

    m_ins  = new float * [nchannels];
    m_outs = new float * [nchannels];

    char port_name[32];
    for (uint16_t k = 0; k < nchannels; ++k) {
        ::snprintf(port_name, sizeof(port_name), "in_%d", k + 1);
        m_audio_ins[k] = ::jack_port_register(m_client,
                                              port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
        m_ins[k] = NULL;
        ::snprintf(port_name, sizeof(port_name), "out_%d", k + 1);
        m_audio_outs[k] = ::jack_port_register(m_client,
                                               port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
        m_outs[k] = NULL;
    }

    // register midi port
#ifdef CONFIG_JACK_MIDI
    m_midi_in = ::jack_port_register(m_client,
                                     "in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0);
#endif
#ifdef CONFIG_ALSA_MIDI
    m_alsa_seq     = NULL;
//	m_alsa_client  = -1;
    m_alsa_port    = -1;
    m_alsa_decoder = NULL;
    m_alsa_buffer  = NULL;
    m_alsa_thread  = NULL;
    // open alsa sequencer client...
    if (snd_seq_open(&m_alsa_seq, "hw", SND_SEQ_OPEN_INPUT, 0) >= 0) {
        snd_seq_set_client_name(m_alsa_seq, client_id);
        //	m_alsa_client = snd_seq_client_id(m_alsa_seq);
        m_alsa_port = snd_seq_create_simple_port(m_alsa_seq, "in",
                      SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE,
                      SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);
        snd_midi_event_new(1024, &m_alsa_decoder);
        m_alsa_buffer = ::jack_ringbuffer_create(
                            1024 * (sizeof(jack_midi_event_t) + 4));
        m_alsa_thread = new samplv1_alsa_thread(this);
        m_alsa_thread->start(QThread::TimeCriticalPriority);
    }
#endif	// CONFIG_ALSA_MIDI

    // setup any local, initial buffers...
    samplv1::setBufferSize(::jack_get_buffer_size(m_client));

    jack_set_buffer_size_callback(m_client,
                                  samplv1_jack_buffer_size, this);

    // set process callbacks...
    ::jack_set_process_callback(m_client,
                                samplv1_jack_process, this);

#ifdef CONFIG_JACK_SESSION
    // JACK session event callback...
    if (::jack_set_session_callback) {
        ::jack_set_session_callback(m_client,
                                    samplv1_jack_session_event, this);
    }
#endif
}
Esempio n. 25
0
File: jack.c Progetto: BG2BKK/cmus
static int op_jack_init(void)
{
#ifdef HAVE_SAMPLERATE
	for (int i = 0; i < CHANNELS; i++) {
		src_state[i] = src_new(src_quality, 1, NULL);
		if (src_state[i] == NULL) {
			d_print("src_new failed");
			for (i = i - 1; i >= 0; i--) {
				src_delete(src_state[i]);
			}
			return -OP_ERROR_INTERNAL;
		}
	}
#endif
	jack_set_error_function(op_jack_error_cb);

	jack_options_t options = JackNullOption;
	if (fail) {
		/* since jackd failed, it will not be autostarted. Either jackd
		 * was killed intentionaly or it died by heartattack.
		 * Until it is restarted, init will happily fail again
		 * and again and again..
		 */
		options |= JackNoStartServer;
	}

	jack_status_t status;
	client = jack_client_open("cmus", options, &status, server_name);
	if (client == NULL) {
		d_print("jack_client_new failed\n");
		return -OP_ERROR_INTERNAL;
	}

	if (status & JackServerStarted) {
		d_print("jackd started\n");
	}

	jack_nframes_t jack_buffer_size = jack_get_buffer_size(client);
	jack_sample_rate = jack_get_sample_rate(client);
	op_jack_buffer_init(jack_buffer_size, NULL);

	jack_set_process_callback(client, op_jack_cb, NULL);
	jack_set_sample_rate_callback(client, op_jack_sample_rate_cb, NULL);
	jack_set_buffer_size_callback(client, op_jack_buffer_init, NULL);
	jack_on_shutdown(client, op_jack_shutdown_cb, NULL);

	for (int i = 0; i < CHANNELS; i++) {
		char port_name[20];
		snprintf(port_name, sizeof(port_name)-1, "output %d", i);

		output_ports[i] = jack_port_register(
			client,
			port_name,
			JACK_DEFAULT_AUDIO_TYPE,
			JackPortIsOutput,
			0
		);
		if (output_ports[i] == NULL) {
			d_print("no jack ports available\n");
			return -OP_ERROR_INTERNAL;
		}
	}

	if (jack_activate(client)) {
		d_print("jack_client_activate failed\n");
		return -OP_ERROR_INTERNAL;
	}

	const char **ports = jack_get_ports(client, NULL, NULL, JackPortIsPhysical | JackPortIsInput);
	if (ports == NULL) {
		d_print("cannot get playback ports\n");
		return -OP_ERROR_INTERNAL;
	}

	for (int i = 0; i < CHANNELS; i++) {
		if (ports[i] == NULL) {
			d_print("could not connect output %d. too few ports.\n", i);
			break;
		}
		if (jack_connect(client, jack_port_name(output_ports[i]), ports[i])) {
			d_print("connot connect port %s\n", ports[i]);
			jack_free(ports);
			return -OP_ERROR_INTERNAL;
		}
	}

	jack_free(ports);
	fail = 0;

	return OP_ERROR_SUCCESS;
}
Esempio n. 26
0
bool DevJack::start(QString *err)
{
#ifdef JACK
  jack_options_t jackopts=JackNullOption;
  jack_status_t jackstat=JackFailure;
  int srcerr;

  //
  // Connect to JACK Instance
  //
  if(jack_server_name.isEmpty()) {
    jack_jack_client=
      jack_client_open(jack_client_name.toAscii(),jackopts,&jackstat);
  }
  else {
    jack_jack_client=
      jack_client_open(jack_client_name.toAscii(),jackopts,&jackstat,
		       (const char *)jack_server_name.toAscii());
  }
  if(jack_jack_client==NULL) {
    if((jackstat&JackInvalidOption)!=0) {
      *err=tr("invalid or unsupported JACK option");
    }
    if((jackstat&JackServerError)!=0) {
      *err=tr("communication error with the JACK server");
    }
    if((jackstat&JackNoSuchClient)!=0) {
      *err=tr("requested JACK client does not exist");
    }
    if((jackstat&JackLoadFailure)!=0) {
      *err=tr("unable to load internal JACK client");
    }
    if((jackstat&JackInitFailure)!=0) {
      *err=tr("unable to initialize JACK client");
    }
    if((jackstat&JackShmFailure)!=0) {
      *err=tr("unable to access JACK shared memory");
    }
    if((jackstat&JackVersionError)!=0) {
      *err=tr("JACK protocol version mismatch");
    }
    if((jackstat&JackServerStarted)!=0) {
      *err=tr("JACK server started");
    }
    if((jackstat&JackServerFailed)!=0) {
      fprintf (stderr, "unable to communication with JACK server\n");
      *err=tr("unable to communicate with JACK server");
    }
    if((jackstat&JackNameNotUnique)!=0) {
      *err=tr("JACK client name not unique");
    }
    if((jackstat&JackFailure)!=0) {
      *err=tr("JACK general failure");
    }
    *err=tr("no connection to JACK server");
  printf("~DevJack::start() Ends FALSE 1\n");
    return false;
  }
  jack_set_buffer_size_callback(jack_jack_client,JackBufferSizeChanged,this);
  jack_set_process_callback(jack_jack_client,JackProcess,this);

  //
  // Join the Graph
  //
  if(jack_activate(jack_jack_client)) {
    *err=tr("unable to join JACK graph");
  printf("~DevJack::start() Ends FALSE 2\n");
    return false;
  }
  jack_jack_sample_rate=jack_get_sample_rate(jack_jack_client);

  //
  // Register Ports
  //
  for(unsigned i=0;i<codec()->channels();i++) {
    QString name=QString().sprintf("output_%d",i+1);
    jack_jack_ports[i]=
      jack_port_register(jack_jack_client,name.toAscii(),JACK_DEFAULT_AUDIO_TYPE,
			 JackPortIsOutput|JackPortIsTerminal,0);
  }
  Log(LOG_INFO,QString().sprintf("connected to JACK graph at %u samples/sec.",
				 jack_jack_sample_rate));

  //  jack_meter_timer->start(AUDIO_METER_INTERVAL);

  //
  // Initialize SRC
  //
  jack_pll_setpoint_ratio=
    (double)jack_jack_sample_rate/(double)codec()->samplerate();
  memset(&jack_data,0,sizeof(jack_data));
  jack_data.src_ratio=jack_pll_setpoint_ratio;
  if((jack_src=src_new(SRC_LINEAR,codec()->channels(),&srcerr))==NULL) {
    fprintf(stderr,"SRC initialization error [%s]\n",src_strerror(srcerr));
    exit(GLASS_EXIT_SRC_ERROR);
  }
  jack_play_position=0;
  jack_pll_setpoint_frames=0;
  jack_pll_offset=0.0;

  jack_play_position_timer->start(50);
  jack_meter_timer->start(AUDIO_METER_INTERVAL);

  return true;

#endif  // JACK
  return false;
}
/* make a connection with @id and @server. Returns NULL on failure with the
 * status set. */
static GstJackAudioConnection *
gst_jack_audio_make_connection (const gchar * id, const gchar * server,
    jack_client_t * jclient, jack_status_t * status)
{
  GstJackAudioConnection *conn;
  jack_options_t options;
  gint res;

  *status = 0;

  GST_DEBUG ("new client %s, connecting to server %s", id,
      GST_STR_NULL (server));

  /* never start a server */
  options = JackNoStartServer;
  /* if we have a servername, use it */
  if (server != NULL)
    options |= JackServerName;
  /* open the client */
  if (jclient == NULL)
    jclient = jack_client_open (id, options, status, server);
  if (jclient == NULL)
    goto could_not_open;

  /* now create object */
  conn = g_new (GstJackAudioConnection, 1);
  conn->refcount = 1;
  g_mutex_init (&conn->lock);
  g_cond_init (&conn->flush_cond);
  conn->id = g_strdup (id);
  conn->server = g_strdup (server);
  conn->client = jclient;
  conn->n_clients = 0;
  conn->src_clients = NULL;
  conn->sink_clients = NULL;
  conn->cur_ts = -1;
  conn->transport_state = GST_STATE_VOID_PENDING;

  /* set our callbacks  */
  jack_set_process_callback (jclient, jack_process_cb, conn);
  /* these callbacks cause us to error */
  jack_set_buffer_size_callback (jclient, jack_buffer_size_cb, conn);
  jack_set_sample_rate_callback (jclient, jack_sample_rate_cb, conn);
  jack_on_shutdown (jclient, jack_shutdown_cb, conn);

  /* all callbacks are set, activate the client */
  GST_INFO ("activate jack_client %p", jclient);
  if ((res = jack_activate (jclient)))
    goto could_not_activate;

  GST_DEBUG ("opened connection %p", conn);

  return conn;

  /* ERRORS */
could_not_open:
  {
    GST_DEBUG ("failed to open jack client, %d", *status);
    return NULL;
  }
could_not_activate:
  {
    GST_ERROR ("Could not activate client (%d)", res);
    *status = JackFailure;
    g_mutex_clear (&conn->lock);
    g_free (conn->id);
    g_free (conn->server);
    g_free (conn);
    return NULL;
  }
}
Esempio n. 28
0
    /*
        JackProxyDriver is wrapped in a JackWaitCallbackDriver decorator that behaves
        as a "dummy driver, until Initialize method returns.
    */
    bool JackProxyDriver::Initialize()
    {
        jack_log("JackProxyDriver::Initialize");

        // save existing local connections if needed
        if (fAutoSave) {
            SaveConnections(0);
        }

        // new loading, but existing client, restart the driver
        if (fClient) {
            jack_info("JackProxyDriver restarting...");
            jack_client_close(fClient);
        }
        FreePorts();

        // display some additional infos
        jack_info("JackProxyDriver started in %s mode.",
                    (fEngineControl->fSyncMode) ? "sync" : "async");

        do {
            jack_status_t status;
            char *old = NULL;

            if (fPromiscuous) {
                // as we are fiddling with the environment variable content, save it
                const char* tmp = getenv("JACK_PROMISCUOUS_SERVER");
                if (tmp) {
                    old = strdup(tmp);
                }
                // temporary enable promiscuous mode
                if (setenv("JACK_PROMISCUOUS_SERVER", fPromiscuous, 1) < 0) {
                    free(old);
                    jack_error("Error allocating memory.");
                    return false;
                }
            }

            jack_info("JackProxyDriver connecting to %s", fUpstream);
            fClient = jack_client_open(fClientName, static_cast<jack_options_t>(JackNoStartServer|JackServerName), &status, fUpstream);

            if (fPromiscuous) {
                // restore previous environment variable content
                if (old) {
                    if (setenv("JACK_PROMISCUOUS_SERVER", old, 1) < 0) {
                        free(old);
                        jack_error("Error allocating memory.");
                        return false;
                    }
                    free(old);
                } else {
                    unsetenv("JACK_PROMISCUOUS_SERVER");
                }
            }

            // the connection failed, try again later
            if (!fClient) {
                JackSleep(1000000);
            }

        } while (!fClient);
        jack_info("JackProxyDriver connected to %s", fUpstream);

        // we are connected, let's register some callbacks

        jack_on_shutdown(fClient, shutdown_callback, this);

        if (jack_set_process_callback(fClient, process_callback, this) != 0) {
            jack_error("Cannot set process callback.");
            return false;
        }

        if (jack_set_buffer_size_callback(fClient, bufsize_callback, this) != 0) {
            jack_error("Cannot set buffer size callback.");
            return false;
        }

        if (jack_set_sample_rate_callback(fClient, srate_callback, this) != 0) {
            jack_error("Cannot set sample rate callback.");
            return false;
        }

        if (jack_set_port_connect_callback(fClient, connect_callback, this) != 0) {
            jack_error("Cannot set port connect callback.");
            return false;
        }

        // detect upstream physical playback ports if needed
        if (fDetectPlaybackChannels) {
            fPlaybackChannels = CountIO(JACK_DEFAULT_AUDIO_TYPE, JackPortIsPhysical | JackPortIsOutput);
        }

        // detect upstream physical capture ports if needed
        if (fDetectCaptureChannels) {
            fCaptureChannels = CountIO(JACK_DEFAULT_AUDIO_TYPE, JackPortIsPhysical | JackPortIsInput);
        }

        if (AllocPorts() != 0) {
            jack_error("Can't allocate ports.");
            return false;
        }

        bufsize_callback(jack_get_buffer_size(fClient));
        srate_callback(jack_get_sample_rate(fClient));

        // restore local connections if needed
        if (fAutoSave) {
            LoadConnections(0);
        }

        // everything is ready, start upstream processing
        if (jack_activate(fClient) != 0) {
            jack_error("Cannot activate jack client.");
            return false;
        }

        // connect upstream ports if needed
        if (fAutoConnect) {
            ConnectPorts();
        }

        return true;
    }
Esempio n. 29
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. 30
0
int main (int argc, char **argv) {
	jack_client_t *client;
	jack_thread_info_t thread_info;
	jack_status_t jstat;
	int c;

	memset(&thread_info, 0, sizeof(thread_info));
	thread_info.channels = 2;
	thread_info.delay = 100000;
	thread_info.format = 0;
	thread_info.iecmult = 2.0;
	thread_info.outfd = NULL;
	thread_info.address = "127.0.0.1";
	thread_info.port = 7770;
	thread_info.message = "/1/fader1";

	const char *optstring = "hqpjiomx:d:f:V";
	struct option long_options[] = {
		{ "help",     no_argument,       0, 'h' },
		{ "json",     no_argument,       0, 'j' },
		{ "iec268",   required_argument, 0, 'i' },
		{ "file",     required_argument, 0, 'f' },
		{ "delay",    required_argument, 0, 'd' },
		{ "peakhold", required_argument, 0, 'p' },
		{ "osc",      required_argument, 0, 'o' },
		{ "port",     required_argument, 0, 'x' },
		{ "message",  required_argument, 0, 'm' },
		{ "quiet",    no_argument,       0, 'q' },
		{ "version",  no_argument,       0, 'V' },
		{ 0, 0, 0, 0 }
	};

	int option_index;

	while ((c = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1) {
		switch (c) {
			case 'h':
				usage(argv[0], 0);
				break;
			case 'q':
				want_quiet = 1;
				break;
			case 'i':
				thread_info.format|=2;
				thread_info.iecmult = atof(optarg)/100.0;
				break;
			case 'j':
				thread_info.format|=4;
				break;
			case 'p':
				thread_info.format|=8;
				break;
			case 'f':
				if (thread_info.outfd) fclose(thread_info.outfd);
				thread_info.outfd = fopen(optarg, "w");
				break;
			case 'd':
				if (atol(optarg) < 0 || atol(optarg) > 60000)
					fprintf(stderr, "delay: time out of bounds.\n");
				else
					thread_info.delay = 1000*atol(optarg);
				break;
			case 'm':
				thread_info.message = optarg;
				break;
			case 'o':
				thread_info.address = optarg;
				break;
			case 'x':
				thread_info.port = atoi(optarg); 
				break;
			case 'V':
				printf ("%s %s\n\n",argv[0], VERSION);
				printf(
"Copyright (C) 2012 Robin Gareus <*****@*****.**>\n"
"This is free software; see the source for copying conditions.  There is NO\n"
"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"
);
				break;
			default:
				fprintf(stderr, "invalid argument.\n");
				usage(argv[0], 0);
				break;
		}
	}


	if (!thread_info.outfd) {
		thread_info.outfd=stdout;
		thread_info.format|=1;
	}

	if (argc <= optind) {
		fprintf(stderr, "At least one port/audio-channel must be given.\n");
		usage(argv[0], 1);
	}

	/* set up JACK client */
	if ((client = jack_client_open("jackpeak", JackNoStartServer, &jstat)) == 0) {
		fprintf(stderr, "Can not connect to JACK.\n");
		exit(1);
	}

	thread_info.client = client;
	thread_info.can_process = 0;
	thread_info.channels = argc - optind;

	jack_set_process_callback(client, process, &thread_info);
	jack_on_shutdown(client, jack_shutdown, &thread_info);
	jack_set_buffer_size_callback(client, jack_bufsiz_cb, &thread_info);

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

	setup_ports(thread_info.channels, &argv[optind], &thread_info);

	/* set up i/o thread */
	pthread_create(&thread_info.thread_id, NULL, io_thread, &thread_info);
#ifndef _WIN32
	signal (SIGHUP, catchsig);
#endif
	thread_info.samplerate = jack_get_sample_rate(thread_info.client);

	if (!want_quiet) {
		fprintf(stderr, "%i channel%s, @%iSPS.\naddress: %s:%i\nmessage: %s\n",
			thread_info.channels,
			(thread_info.channels>1)?"s":"",
			thread_info.samplerate,
			thread_info.address,
			thread_info.port,
			thread_info.message
		);
	}

	/* all systems go - run the i/o thread */
	thread_info.can_capture = 1;
	pthread_join(thread_info.thread_id, NULL);

	if (thread_info.outfd != stdout)
		fclose(thread_info.outfd);

	jack_client_close(client);

	cleanup(&thread_info);

	return(0);
}