JackFFADODriver.cpp 34.6 KB
Newer Older
sletz's avatar
sletz committed
1
2
3
4
/*
Copyright (C) 2001 Paul Davis
Copyright (C) 2004 Grame
Copyright (C) 2007 Pieter Palmers
5
Copyright (C) 2009 Devin Anderson
sletz's avatar
sletz committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include <iostream>
#include <unistd.h>
#include <math.h>
#include <stdio.h>
#include <memory.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdarg.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/time.h>
#include <regex.h>
#include <string.h>

#include "JackFFADODriver.h"
39
40
#include "JackFFADOMidiInputPort.h"
#include "JackFFADOMidiOutputPort.h"
sletz's avatar
sletz committed
41
42
43
44
#include "JackEngineControl.h"
#include "JackClientControl.h"
#include "JackPort.h"
#include "JackGraphManager.h"
45
#include "JackCompilerDeps.h"
46
#include "JackLockedEngine.h"
sletz's avatar
sletz committed
47
48
49
50

namespace Jack
{

sletz's avatar
sletz committed
51
#define FIREWIRE_REQUIRED_FFADO_API_VERSION 8
sletz's avatar
sletz committed
52
53
54
55
56
57

#define jack_get_microseconds GetMicroSeconds

int
JackFFADODriver::ffado_driver_read (ffado_driver_t * driver, jack_nframes_t nframes)
{
58
    channel_t chn;
sletz's avatar
sletz committed
59
60
61
    jack_default_audio_sample_t* buf = NULL;

    printEnter();
sletz's avatar
sletz committed
62
63
    for (chn = 0; chn < driver->capture_nchannels; chn++) {
        // if nothing connected, don't process
sletz's avatar
sletz committed
64
65
        if (fGraphManager->GetConnectionsNum(fCapturePortList[chn]) == 0) {
            buf = (jack_default_audio_sample_t*)driver->scratchbuffer;
sletz's avatar
sletz committed
66
67
68
69
70
71
            // we always have to specify a valid buffer
            ffado_streaming_set_capture_stream_buffer(driver->dev, chn, (char *)(buf));
            // notify the streaming system that it can (but doesn't have to) skip
            // this channel
            ffado_streaming_capture_stream_onoff(driver->dev, chn, 0);
        } else {
sletz's avatar
sletz committed
72
            if (driver->capture_channels[chn].stream_type == ffado_stream_type_audio) {
sletz's avatar
sletz committed
73
74
75
                buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fCapturePortList[chn],  nframes);

                /* if the returned buffer is invalid, use the dummy buffer */
sletz's avatar
sletz committed
76
77
                if (!buf) buf = (jack_default_audio_sample_t*)driver->scratchbuffer;

sletz's avatar
sletz committed
78
79
80
                ffado_streaming_set_capture_stream_buffer(driver->dev, chn, (char *)(buf));
                ffado_streaming_capture_stream_onoff(driver->dev, chn, 1);
            } else if (driver->capture_channels[chn].stream_type == ffado_stream_type_midi) {
sletz's avatar
sletz committed
81
82
                ffado_streaming_set_capture_stream_buffer(driver->dev, chn,
                        (char *)(driver->capture_channels[chn].midi_buffer));
sletz's avatar
sletz committed
83
84
85
86
87
88
                ffado_streaming_capture_stream_onoff(driver->dev, chn, 1);
            } else { // always have a valid buffer
                ffado_streaming_set_capture_stream_buffer(driver->dev, chn, (char *)(driver->scratchbuffer));
                // don't process what we don't use
                ffado_streaming_capture_stream_onoff(driver->dev, chn, 0);
            }
sletz's avatar
sletz committed
89
90
91
        }
    }

sletz's avatar
sletz committed
92
93
    /* now transfer the buffers */
    ffado_streaming_transfer_capture_buffers(driver->dev);
sletz's avatar
sletz committed
94

sletz's avatar
sletz committed
95
96
97
    /* process the midi data */
    for (chn = 0; chn < driver->capture_nchannels; chn++) {
        if (driver->capture_channels[chn].stream_type == ffado_stream_type_midi) {
98
            JackFFADOMidiInputPort *midi_input = (JackFFADOMidiInputPort *) driver->capture_channels[chn].midi_input;
99
            JackMidiBuffer *buffer = (JackMidiBuffer *) fGraphManager->GetBuffer(fCapturePortList[chn], nframes);
100
            midi_input->Process(buffer, driver->capture_channels[chn].midi_buffer, nframes);
sletz's avatar
sletz committed
101
102
103
104
105
106
107
108
109
110
        }
    }

    printExit();
    return 0;
}

int
JackFFADODriver::ffado_driver_write (ffado_driver_t * driver, jack_nframes_t nframes)
{
111
    channel_t chn;
sletz's avatar
sletz committed
112
    jack_default_audio_sample_t* buf;
sletz's avatar
sletz committed
113
114
115
116
    printEnter();

    driver->process_count++;

sletz's avatar
sletz committed
117
    for (chn = 0; chn < driver->playback_nchannels; chn++) {
sletz's avatar
sletz committed
118
119
        if (fGraphManager->GetConnectionsNum(fPlaybackPortList[chn]) == 0) {
            buf = (jack_default_audio_sample_t*)driver->nullbuffer;
sletz's avatar
sletz committed
120
121
122
123
124
125
            // we always have to specify a valid buffer
            ffado_streaming_set_playback_stream_buffer(driver->dev, chn, (char *)(buf));
            // notify the streaming system that it can (but doesn't have to) skip
            // this channel
            ffado_streaming_playback_stream_onoff(driver->dev, chn, 0);
        } else {
sletz's avatar
sletz committed
126
            if (driver->playback_channels[chn].stream_type == ffado_stream_type_audio) {
sletz's avatar
sletz committed
127
128
                buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fPlaybackPortList[chn], nframes);
                /* use the silent buffer if there is no valid jack buffer */
sletz's avatar
sletz committed
129
                if (!buf) buf = (jack_default_audio_sample_t*)driver->nullbuffer;
sletz's avatar
sletz committed
130
                ffado_streaming_set_playback_stream_buffer(driver->dev, chn, (char *)(buf));
pieterpalmers's avatar
pieterpalmers committed
131
                ffado_streaming_playback_stream_onoff(driver->dev, chn, 1);
sletz's avatar
sletz committed
132
133
134
            } else if (driver->playback_channels[chn].stream_type == ffado_stream_type_midi) {
                uint32_t *midi_buffer = driver->playback_channels[chn].midi_buffer;
                memset(midi_buffer, 0, nframes * sizeof(uint32_t));
135
                buf = (jack_default_audio_sample_t *) fGraphManager->GetBuffer(fPlaybackPortList[chn], nframes);
sletz's avatar
sletz committed
136
                ffado_streaming_set_playback_stream_buffer(driver->dev, chn, (char *)(midi_buffer));
137
138
139
                ffado_streaming_playback_stream_onoff(driver->dev, chn, buf ? 1 : 0);
                JackFFADOMidiOutputPort *midi_output = (JackFFADOMidiOutputPort *) driver->playback_channels[chn].midi_output;
                midi_output->Process((JackMidiBuffer *) buf, midi_buffer, nframes);
sletz's avatar
sletz committed
140

sletz's avatar
sletz committed
141
142
143
            } else { // always have a valid buffer
                ffado_streaming_set_playback_stream_buffer(driver->dev, chn, (char *)(driver->nullbuffer));
                ffado_streaming_playback_stream_onoff(driver->dev, chn, 0);
sletz's avatar
sletz committed
144
145
146
147
148
149
150
151
152
153
            }
        }
    }
    ffado_streaming_transfer_playback_buffers(driver->dev);
    printExit();
    return 0;
}

jack_nframes_t
JackFFADODriver::ffado_driver_wait (ffado_driver_t *driver, int extra_fd, int *status,
sletz's avatar
sletz committed
154
                                    float *delayed_usecs)
sletz's avatar
sletz committed
155
156
157
{
    jack_time_t wait_enter;
    jack_time_t wait_ret;
sletz's avatar
sletz committed
158
    ffado_wait_response response;
sletz's avatar
sletz committed
159
160
161
162
163
164

    printEnter();

    wait_enter = jack_get_microseconds ();
    if (wait_enter > driver->wait_next) {
        /*
pieterpalmers's avatar
pieterpalmers committed
165
166
167
168
                * This processing cycle was delayed past the
                * next due interrupt!  Do not account this as
                * a wakeup delay:
                */
sletz's avatar
sletz committed
169
170
171
172
173
174
175
        driver->wait_next = 0;
        driver->wait_late++;
    }
// *status = -2; interrupt
// *status = -3; timeout
// *status = -4; extra FD

sletz's avatar
sletz committed
176
    response = ffado_streaming_wait(driver->dev);
sletz's avatar
sletz committed
177
178
179
180
181
182
183
184

    wait_ret = jack_get_microseconds ();

    if (driver->wait_next && wait_ret > driver->wait_next) {
        *delayed_usecs = wait_ret - driver->wait_next;
    }
    driver->wait_last = wait_ret;
    driver->wait_next = wait_ret + driver->period_usecs;
pieterpalmers's avatar
pieterpalmers committed
185
//         driver->engine->transport_cycle_start (driver->engine, wait_ret);
sletz's avatar
sletz committed
186

sletz's avatar
sletz committed
187
188
189
190
    if(response == ffado_wait_ok) {
       // all good
       *status = 0;
    } else if (response == ffado_wait_xrun) {
sletz's avatar
sletz committed
191
        // xrun happened, but it's handled
sletz's avatar
sletz committed
192
        *status = 0;
sletz's avatar
sletz committed
193
194
195
196
        return 0;
    } else if (response == ffado_wait_error) {
        // an error happened (unhandled xrun)
        // this should be fatal
197
        jack_error("JackFFADODriver::ffado_driver_wait - unhandled xrun");
sletz's avatar
sletz committed
198
        *status = -1;
sletz's avatar
sletz committed
199
        return 0;
sletz's avatar
sletz committed
200
201
202
    } else if (response == ffado_wait_shutdown) {
        // ffado requested shutdown (e.g. device unplugged)
        // this should be fatal
203
204
        jack_error("JackFFADODriver::ffado_driver_wait - shutdown requested "
                   "(device unplugged?)");
sletz's avatar
sletz committed
205
206
207
208
209
        *status = -1;
        return 0;
    } else {
        // unknown response code. should be fatal
        // this should be fatal
210
211
        jack_error("JackFFADODriver::ffado_driver_wait - unexpected error "
                   "code '%d' returned from 'ffado_streaming_wait'", response);
sletz's avatar
sletz committed
212
213
        *status = -1;
        return 0;
sletz's avatar
sletz committed
214
215
    }

sletz's avatar
sletz committed
216
    fBeginDateUst = wait_ret;
sletz's avatar
sletz committed
217
218

    printExit();
sletz's avatar
sletz committed
219
    return driver->period_size;
sletz's avatar
sletz committed
220
221
222
223
224
225
226
227
228
}

int
JackFFADODriver::ffado_driver_start (ffado_driver_t *driver)
{
    int retval = 0;

    if ((retval = ffado_streaming_start(driver->dev))) {
        printError("Could not start streaming threads");
sletz's avatar
sletz committed
229

sletz's avatar
sletz committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
        return retval;
    }
    return 0;
}

int
JackFFADODriver::ffado_driver_stop (ffado_driver_t *driver)
{
    int retval = 0;

    if ((retval = ffado_streaming_stop(driver->dev))) {
        printError("Could not stop streaming threads");
        return retval;
    }

    return 0;
}

int
JackFFADODriver::ffado_driver_restart (ffado_driver_t *driver)
{
    if (Stop())
        return -1;
    return Start();
}

256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
void
JackFFADODriver::UpdateLatencies(void)
{
    jack_latency_range_t range;
    ffado_driver_t* driver = (ffado_driver_t*)fDriver;

    for (int i = 0; i < fCaptureChannels; i++) {
        range.min = range.max = driver->period_size + driver->capture_frame_latency;
        fGraphManager->GetPort(fCapturePortList[i])->SetLatencyRange(JackCaptureLatency, &range);
    }

    for (int i = 0; i < fPlaybackChannels; i++) {
        // Add one buffer more latency if "async" mode is used...
        range.min = range.max = (driver->period_size *
			(driver->device_options.nb_buffers - 1)) +
                         ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize) + driver->playback_frame_latency;
        fGraphManager->GetPort(fPlaybackPortList[i])->SetLatencyRange(JackPlaybackLatency, &range);
        // Monitor port
        if (fWithMonitorPorts) {
            range.min = range.max =driver->period_size;
            fGraphManager->GetPort(fMonitorPortList[i])->SetLatencyRange(JackCaptureLatency, &range);
        }
    }
}

sletz's avatar
sletz committed
281
282
283
284
285
286
int
JackFFADODriver::SetBufferSize (jack_nframes_t nframes)
{
    printError("Buffer size change requested but not supported!!!");

    /*
287
    driver->period_size = nframes;
sletz's avatar
sletz committed
288
    driver->period_usecs =
pieterpalmers's avatar
pieterpalmers committed
289
290
            (jack_time_t) floor ((((float) nframes) / driver->sample_rate)
                                 * 1000000.0f);
sletz's avatar
sletz committed
291
292
293
294
295
296
297
298
299
300
301
    */

    /* tell the engine to change its buffer size */
    //driver->engine->set_buffer_size (driver->engine, nframes);

    return -1; // unsupported
}

typedef void (*JackDriverFinishFunction) (jack_driver_t *);

ffado_driver_t *
302
JackFFADODriver::ffado_driver_new (const char *name,
sletz's avatar
sletz committed
303
                                   ffado_jack_settings_t *params)
sletz's avatar
sletz committed
304
305
306
307
308
{
    ffado_driver_t *driver;

    assert(params);

sletz's avatar
sletz committed
309
    if (ffado_get_api_version() != FIREWIRE_REQUIRED_FFADO_API_VERSION) {
sletz's avatar
sletz committed
310
311
312
313
314
315
316
317
318
319
320
        printError("Incompatible libffado version! (%s)", ffado_get_version());
        return NULL;
    }

    printMessage("Starting FFADO backend (%s)", ffado_get_version());

    driver = (ffado_driver_t*)calloc (1, sizeof (ffado_driver_t));

    /* Setup the jack interfaces */
    jack_driver_nt_init ((jack_driver_nt_t *) driver);

pieterpalmers's avatar
pieterpalmers committed
321
322
323
324
325
326
327
328
329
330
    /*        driver->nt_attach    = (JackDriverNTAttachFunction)   ffado_driver_attach;
            driver->nt_detach    = (JackDriverNTDetachFunction)   ffado_driver_detach;
            driver->nt_start     = (JackDriverNTStartFunction)    ffado_driver_start;
            driver->nt_stop      = (JackDriverNTStopFunction)     ffado_driver_stop;
            driver->nt_run_cycle = (JackDriverNTRunCycleFunction) ffado_driver_run_cycle;
            driver->null_cycle   = (JackDriverNullCycleFunction)  ffado_driver_null_cycle;
            driver->write        = (JackDriverReadFunction)       ffado_driver_write;
            driver->read         = (JackDriverReadFunction)       ffado_driver_read;
            driver->nt_bufsize   = (JackDriverNTBufSizeFunction)  ffado_driver_bufsize;
            */
sletz's avatar
sletz committed
331
332
333
334
335
336
337

    /* copy command line parameter contents to the driver structure */
    memcpy(&driver->settings, params, sizeof(ffado_jack_settings_t));

    /* prepare all parameters */
    driver->sample_rate = params->sample_rate;
    driver->period_size = params->period_size;
sletz's avatar
sletz committed
338
    fBeginDateUst = 0;
sletz's avatar
sletz committed
339
340
341
342

    driver->period_usecs =
        (jack_time_t) floor ((((float) driver->period_size) * 1000000.0f) / driver->sample_rate);

pieterpalmers's avatar
pieterpalmers committed
343
//         driver->client = client;
sletz's avatar
sletz committed
344
345
346
347
348
349
350
351
352
    driver->engine = NULL;

    memset(&driver->device_options, 0, sizeof(driver->device_options));
    driver->device_options.sample_rate = params->sample_rate;
    driver->device_options.period_size = params->period_size;
    driver->device_options.nb_buffers = params->buffer_size;
    driver->device_options.verbose = params->verbose_level;
    driver->capture_frame_latency = params->capture_frame_latency;
    driver->playback_frame_latency = params->playback_frame_latency;
sletz's avatar
sletz committed
353
    driver->device_options.snoop_mode = params->snoop_mode;
sletz's avatar
sletz committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367

    debugPrint(DEBUG_LEVEL_STARTUP, " Driver compiled on %s %s", __DATE__, __TIME__);
    debugPrint(DEBUG_LEVEL_STARTUP, " Created driver %s", name);
    debugPrint(DEBUG_LEVEL_STARTUP, "            period_size:   %d", driver->device_options.period_size);
    debugPrint(DEBUG_LEVEL_STARTUP, "            period_usecs:  %d", driver->period_usecs);
    debugPrint(DEBUG_LEVEL_STARTUP, "            sample rate:   %d", driver->device_options.sample_rate);
    debugPrint(DEBUG_LEVEL_STARTUP, "            verbose level: %d", driver->device_options.verbose);

    return (ffado_driver_t *) driver;
}

void
JackFFADODriver::ffado_driver_delete (ffado_driver_t *driver)
{
sletz's avatar
sletz committed
368
    free (driver);
sletz's avatar
sletz committed
369
370
371
372
373
}

int JackFFADODriver::Attach()
{
    JackPort* port;
Stephane Letz's avatar
Stephane Letz committed
374
    jack_port_id_t port_index;
sletz's avatar
sletz committed
375
376
    char buf[REAL_JACK_PORT_NAME_SIZE];
    char portname[REAL_JACK_PORT_NAME_SIZE];
377
    jack_latency_range_t range;
sletz's avatar
sletz committed
378
379
380

    ffado_driver_t* driver = (ffado_driver_t*)fDriver;

sletz's avatar
sletz committed
381
    jack_log("JackFFADODriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
sletz's avatar
sletz committed
382
383
384

    g_verbose = (fEngineControl->fVerbose ? 1 : 0);

sletz's avatar
sletz committed
385
386
387
388
389
    /* preallocate some buffers such that they don't have to be allocated
       in RT context (or from the stack)
     */
    /* the null buffer is a buffer that contains one period of silence */
    driver->nullbuffer = (ffado_sample_t *)calloc(driver->period_size, sizeof(ffado_sample_t));
sletz's avatar
sletz committed
390
    if (driver->nullbuffer == NULL) {
sletz's avatar
sletz committed
391
392
393
394
395
        printError("could not allocate memory for null buffer");
        return -1;
    }
    /* calloc should do this, but it can't hurt to be sure */
    memset(driver->nullbuffer, 0, driver->period_size*sizeof(ffado_sample_t));
sletz's avatar
sletz committed
396

sletz's avatar
sletz committed
397
398
    /* the scratch buffer is a buffer of one period that can be used as dummy memory */
    driver->scratchbuffer = (ffado_sample_t *)calloc(driver->period_size, sizeof(ffado_sample_t));
sletz's avatar
sletz committed
399
    if (driver->scratchbuffer == NULL) {
sletz's avatar
sletz committed
400
401
402
403
        printError("could not allocate memory for scratch buffer");
        return -1;
    }

sletz's avatar
sletz committed
404
405
406
    /* packetizer thread options */
    driver->device_options.realtime = (fEngineControl->fRealTime ? 1 : 0);

407
    driver->device_options.packetizer_priority = fEngineControl->fServerPriority +
sletz's avatar
sletz committed
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
            FFADO_RT_PRIORITY_PACKETIZER_RELATIVE;
    if (driver->device_options.packetizer_priority > 98) {
        driver->device_options.packetizer_priority = 98;
    }

    // initialize the thread
    driver->dev = ffado_streaming_init(driver->device_info, driver->device_options);

    if (!driver->dev) {
        printError("FFADO: Error creating virtual device");
        return -1;
    }

    if (driver->device_options.realtime) {
        printMessage("Streaming thread running with Realtime scheduling, priority %d",
                     driver->device_options.packetizer_priority);
    } else {
        printMessage("Streaming thread running without Realtime scheduling");
    }

sletz's avatar
sletz committed
428
429
    ffado_streaming_set_audio_datatype(driver->dev, ffado_audio_datatype_float);

sletz's avatar
sletz committed
430
431
432
433
    /* ports */

    // capture
    driver->capture_nchannels = ffado_streaming_get_nb_capture_streams(driver->dev);
sletz's avatar
sletz committed
434
435
    driver->capture_channels = (ffado_capture_channel_t *)calloc(driver->capture_nchannels, sizeof(ffado_capture_channel_t));
    if (driver->capture_channels == NULL) {
sletz's avatar
sletz committed
436
437
438
        printError("could not allocate memory for capture channel list");
        return -1;
    }
sletz's avatar
sletz committed
439

sletz's avatar
sletz committed
440
    fCaptureChannels = 0;
441
    for (channel_t chn = 0; chn < driver->capture_nchannels; chn++) {
sletz's avatar
sletz committed
442
        ffado_streaming_get_capture_stream_name(driver->dev, chn, portname, sizeof(portname));
sletz's avatar
sletz committed
443

sletz's avatar
sletz committed
444
445
        driver->capture_channels[chn].stream_type = ffado_streaming_get_capture_stream_type(driver->dev, chn);
        if (driver->capture_channels[chn].stream_type == ffado_stream_type_audio) {
sletz's avatar
sletz committed
446
            snprintf(buf, sizeof(buf), "firewire_pcm:%s_in", portname);
sletz's avatar
sletz committed
447
            printMessage ("Registering audio capture port %s", buf);
448
            if (fEngine->PortRegister(fClientControl.fRefNum, buf,
sletz's avatar
sletz committed
449
                              JACK_DEFAULT_AUDIO_TYPE,
450
                              CaptureDriverFlags,
451
                              fEngineControl->fBufferSize, &port_index) < 0) {
sletz's avatar
sletz committed
452
453
454
455
456
457
458
459
460
461
462
                jack_error("driver: cannot register port for %s", buf);
                return -1;
            }

            // setup port parameters
            if (ffado_streaming_set_capture_stream_buffer(driver->dev, chn, NULL)) {
                printError(" cannot configure initial port buffer for %s", buf);
            }
            ffado_streaming_capture_stream_onoff(driver->dev, chn, 0);

            port = fGraphManager->GetPort(port_index);
463
464
            range.min = range.max = driver->period_size + driver->capture_frame_latency;
            port->SetLatencyRange(JackCaptureLatency, &range);
465
            // capture port aliases (jackd1 style port names)
sletz's avatar
sletz committed
466
            snprintf(buf, sizeof(buf), "%s:capture_%i", fClientControl.fName, (int) chn + 1);
467
            port->SetAlias(buf);
sletz's avatar
sletz committed
468
            fCapturePortList[chn] = port_index;
sletz's avatar
sletz committed
469
            jack_log("JackFFADODriver::Attach fCapturePortList[i] %ld ", port_index);
sletz's avatar
sletz committed
470
            fCaptureChannels++;
sletz's avatar
sletz committed
471
        } else if (driver->capture_channels[chn].stream_type == ffado_stream_type_midi) {
sletz's avatar
sletz committed
472
            snprintf(buf, sizeof(buf), "firewire_pcm:%s_in", portname);
sletz's avatar
sletz committed
473
            printMessage ("Registering midi capture port %s", buf);
474
            if (fEngine->PortRegister(fClientControl.fRefNum, buf,
sletz's avatar
sletz committed
475
                              JACK_DEFAULT_MIDI_TYPE,
476
                              CaptureDriverFlags,
477
                              fEngineControl->fBufferSize, &port_index) < 0) {
sletz's avatar
sletz committed
478
479
480
481
                jack_error("driver: cannot register port for %s", buf);
                return -1;
            }

sletz's avatar
sletz committed
482
483
484
485
            // setup port parameters
            if (ffado_streaming_set_capture_stream_buffer(driver->dev, chn, NULL)) {
                printError(" cannot configure initial port buffer for %s", buf);
            }
sletz's avatar
sletz committed
486
            if (ffado_streaming_capture_stream_onoff(driver->dev, chn, 0)) {
sletz's avatar
sletz committed
487
488
                printError(" cannot enable port %s", buf);
            }
sletz's avatar
sletz committed
489

490
            driver->capture_channels[chn].midi_input = new JackFFADOMidiInputPort();
sletz's avatar
sletz committed
491
492
            // setup the midi buffer
            driver->capture_channels[chn].midi_buffer = (uint32_t *)calloc(driver->period_size, sizeof(uint32_t));
sletz's avatar
sletz committed
493
494

            port = fGraphManager->GetPort(port_index);
495
496
            range.min = range.max = driver->period_size + driver->capture_frame_latency;
            port->SetLatencyRange(JackCaptureLatency, &range);
sletz's avatar
sletz committed
497
            fCapturePortList[chn] = port_index;
sletz's avatar
sletz committed
498
            jack_log("JackFFADODriver::Attach fCapturePortList[i] %ld ", port_index);
sletz's avatar
sletz committed
499
500
501
            fCaptureChannels++;
        } else {
            printMessage ("Don't register capture port %s", portname);
sletz's avatar
sletz committed
502
503
504
505
506
        }
    }

    // playback
    driver->playback_nchannels = ffado_streaming_get_nb_playback_streams(driver->dev);
sletz's avatar
sletz committed
507
508
    driver->playback_channels = (ffado_playback_channel_t *)calloc(driver->playback_nchannels, sizeof(ffado_playback_channel_t));
    if (driver->playback_channels == NULL) {
sletz's avatar
sletz committed
509
510
511
        printError("could not allocate memory for playback channel list");
        return -1;
    }
sletz's avatar
sletz committed
512

sletz's avatar
sletz committed
513
    fPlaybackChannels = 0;
514
    for (channel_t chn = 0; chn < driver->playback_nchannels; chn++) {
sletz's avatar
sletz committed
515
        ffado_streaming_get_playback_stream_name(driver->dev, chn, portname, sizeof(portname));
sletz's avatar
sletz committed
516

sletz's avatar
sletz committed
517
        driver->playback_channels[chn].stream_type = ffado_streaming_get_playback_stream_type(driver->dev, chn);
sletz's avatar
sletz committed
518

sletz's avatar
sletz committed
519
        if (driver->playback_channels[chn].stream_type == ffado_stream_type_audio) {
sletz's avatar
sletz committed
520
            snprintf(buf, sizeof(buf), "firewire_pcm:%s_out", portname);
sletz's avatar
sletz committed
521
            printMessage ("Registering audio playback port %s", buf);
522
            if (fEngine->PortRegister(fClientControl.fRefNum, buf,
sletz's avatar
sletz committed
523
                              JACK_DEFAULT_AUDIO_TYPE,
524
                              PlaybackDriverFlags,
525
                              fEngineControl->fBufferSize, &port_index) < 0) {
sletz's avatar
sletz committed
526
527
528
529
                jack_error("driver: cannot register port for %s", buf);
                return -1;
            }

sletz's avatar
sletz committed
530
531
532
533
            // setup port parameters
            if (ffado_streaming_set_playback_stream_buffer(driver->dev, chn, NULL)) {
                printError(" cannot configure initial port buffer for %s", buf);
            }
sletz's avatar
sletz committed
534
            if (ffado_streaming_playback_stream_onoff(driver->dev, chn, 0)) {
sletz's avatar
sletz committed
535
536
                printError(" cannot enable port %s", buf);
            }
sletz's avatar
sletz committed
537
538

            port = fGraphManager->GetPort(port_index);
539
            // Add one buffer more latency if "async" mode is used...
Devin Anderson's avatar
Devin Anderson committed
540
            range.min = range.max = (driver->period_size * (driver->device_options.nb_buffers - 1)) + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize) + driver->playback_frame_latency;
541
            port->SetLatencyRange(JackPlaybackLatency, &range);
542
            // playback port aliases (jackd1 style port names)
sletz's avatar
sletz committed
543
            snprintf(buf, sizeof(buf), "%s:playback_%i", fClientControl.fName, (int) chn + 1);
544
            port->SetAlias(buf);
sletz's avatar
sletz committed
545
            fPlaybackPortList[chn] = port_index;
sletz's avatar
sletz committed
546
            jack_log("JackFFADODriver::Attach fPlaybackPortList[i] %ld ", port_index);
sletz's avatar
sletz committed
547
            fPlaybackChannels++;
sletz's avatar
sletz committed
548
        } else if (driver->playback_channels[chn].stream_type == ffado_stream_type_midi) {
sletz's avatar
sletz committed
549
            snprintf(buf, sizeof(buf), "firewire_pcm:%s_out", portname);
sletz's avatar
sletz committed
550
            printMessage ("Registering midi playback port %s", buf);
551
552

            if (fEngine->PortRegister(fClientControl.fRefNum, buf,
sletz's avatar
sletz committed
553
                              JACK_DEFAULT_MIDI_TYPE,
554
                              PlaybackDriverFlags,
555
                              fEngineControl->fBufferSize, &port_index) < 0) {
sletz's avatar
sletz committed
556
557
558
559
560
561
562
563
                jack_error("driver: cannot register port for %s", buf);
                return -1;
            }

            // setup port parameters
            if (ffado_streaming_set_playback_stream_buffer(driver->dev, chn, NULL)) {
                printError(" cannot configure initial port buffer for %s", buf);
            }
sletz's avatar
sletz committed
564
            if (ffado_streaming_playback_stream_onoff(driver->dev, chn, 0)) {
sletz's avatar
sletz committed
565
566
567
                printError(" cannot enable port %s", buf);
            }
            // setup the midi buffer
568

569
570
571
            // This constructor optionally accepts arguments for the
            // non-realtime buffer size and the realtime buffer size.  Ideally,
            // these would become command-line options for the FFADO driver.
572
            driver->playback_channels[chn].midi_output = new JackFFADOMidiOutputPort();
573

sletz's avatar
sletz committed
574
575
576
            driver->playback_channels[chn].midi_buffer = (uint32_t *)calloc(driver->period_size, sizeof(uint32_t));

            port = fGraphManager->GetPort(port_index);
577
            range.min = range.max = (driver->period_size * (driver->device_options.nb_buffers - 1)) + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize) + driver->playback_frame_latency;
578
            port->SetLatencyRange(JackPlaybackLatency, &range);
sletz's avatar
sletz committed
579
            fPlaybackPortList[chn] = port_index;
sletz's avatar
sletz committed
580
            jack_log("JackFFADODriver::Attach fPlaybackPortList[i] %ld ", port_index);
sletz's avatar
sletz committed
581
582
583
            fPlaybackChannels++;
        } else {
            printMessage ("Don't register playback port %s", portname);
sletz's avatar
sletz committed
584
585
586
        }
    }

sletz's avatar
sletz committed
587
588
    assert(fCaptureChannels < DRIVER_PORT_NUM);
    assert(fPlaybackChannels < DRIVER_PORT_NUM);
sletz's avatar
sletz committed
589

sletz's avatar
sletz committed
590
    if (ffado_streaming_prepare(driver->dev)) {
sletz's avatar
sletz committed
591
592
593
594
595
596
597
598
599
600
601
        printError("Could not prepare streaming device!");
        return -1;
    }

    // this makes no sense...
    assert(fCaptureChannels + fPlaybackChannels > 0);
    return 0;
}

int JackFFADODriver::Detach()
{
602
    channel_t chn;
sletz's avatar
sletz committed
603
    ffado_driver_t* driver = (ffado_driver_t*)fDriver;
sletz's avatar
sletz committed
604
    jack_log("JackFFADODriver::Detach");
sletz's avatar
sletz committed
605
606
607
608
609

    // finish the libfreebob streaming
    ffado_streaming_finish(driver->dev);
    driver->dev = NULL;

sletz's avatar
sletz committed
610
611
    // free all internal buffers
    for (chn = 0; chn < driver->capture_nchannels; chn++) {
sletz's avatar
sletz committed
612
        if (driver->capture_channels[chn].midi_buffer)
sletz's avatar
sletz committed
613
            free(driver->capture_channels[chn].midi_buffer);
614
        if (driver->capture_channels[chn].midi_input)
615
            delete ((JackFFADOMidiInputPort *) (driver->capture_channels[chn].midi_input));
sletz's avatar
sletz committed
616
    }
sletz's avatar
sletz committed
617
    free(driver->capture_channels);
sletz's avatar
sletz committed
618

sletz's avatar
sletz committed
619
    for (chn = 0; chn < driver->playback_nchannels; chn++) {
sletz's avatar
sletz committed
620
        if (driver->playback_channels[chn].midi_buffer)
sletz's avatar
sletz committed
621
            free(driver->playback_channels[chn].midi_buffer);
622
        if (driver->playback_channels[chn].midi_output)
623
            delete ((JackFFADOMidiOutputPort *) (driver->playback_channels[chn].midi_output));
sletz's avatar
sletz committed
624
625
626
627
628
    }
    free(driver->playback_channels);

    free(driver->nullbuffer);
    free(driver->scratchbuffer);
sletz's avatar
sletz committed
629

sletz's avatar
sletz committed
630
    return JackAudioDriver::Detach();  // Generic JackAudioDriver Detach
sletz's avatar
sletz committed
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
}

int JackFFADODriver::Open(ffado_jack_settings_t *params)
{
    // Generic JackAudioDriver Open
    if (JackAudioDriver::Open(
                params->period_size, params->sample_rate,
                params->playback_ports, params->playback_ports,
                0, 0, 0, "", "",
                params->capture_frame_latency, params->playback_frame_latency) != 0) {
        return -1;
    }

    fDriver = (jack_driver_t *)ffado_driver_new ("ffado_pcm", params);

    if (fDriver) {
        // FFADO driver may have changed the in/out values
sletz's avatar
sletz committed
648
649
        //fCaptureChannels = ((ffado_driver_t *)fDriver)->capture_nchannels_audio;
        //fPlaybackChannels = ((ffado_driver_t *)fDriver)->playback_nchannels_audio;
sletz's avatar
sletz committed
650
651
        return 0;
    } else {
652
        JackAudioDriver::Close();
sletz's avatar
sletz committed
653
654
655
656
657
658
        return -1;
    }
}

int JackFFADODriver::Close()
{
659
660
661
    // Generic audio driver close
    int res = JackAudioDriver::Close();

sletz's avatar
sletz committed
662
    ffado_driver_delete((ffado_driver_t*)fDriver);
663
    return res;
sletz's avatar
sletz committed
664
665
666
667
}

int JackFFADODriver::Start()
{
668
669
670
671
672
673
674
675
    int res = JackAudioDriver::Start();
    if (res >= 0) {
        res = ffado_driver_start((ffado_driver_t *)fDriver);
        if (res < 0) {
            JackAudioDriver::Stop();
        }
    }
    return res;
sletz's avatar
sletz committed
676
677
678
679
}

int JackFFADODriver::Stop()
{
680
681
682
683
684
    int res = ffado_driver_stop((ffado_driver_t *)fDriver);
    if (JackAudioDriver::Stop() < 0) {
        res = -1;
    }
    return res;
sletz's avatar
sletz committed
685
686
687
688
689
690
691
692
693
}

int JackFFADODriver::Read()
{
    printEnter();

    /* Taken from ffado_driver_run_cycle */
    ffado_driver_t* driver = (ffado_driver_t*)fDriver;
    int wait_status = 0;
sletz's avatar
sletz committed
694
    fDelayedUsecs = 0.f;
sletz's avatar
sletz committed
695

696
697
retry:

sletz's avatar
sletz committed
698
    jack_nframes_t nframes = ffado_driver_wait(driver, -1, &wait_status,
sletz's avatar
sletz committed
699
                             &fDelayedUsecs);
sletz's avatar
sletz committed
700
701
702
703
704
705
706
707

    if ((wait_status < 0)) {
        printError( "wait status < 0! (= %d)", wait_status);
        return -1;
    }

    if (nframes == 0) {
        /* we detected an xrun and restarted: notify
708
         * clients about the delay.
sletz's avatar
sletz committed
709
         */
sletz's avatar
sletz committed
710
        jack_log("FFADO XRun");
sletz's avatar
sletz committed
711
        NotifyXRun(fBeginDateUst, fDelayedUsecs);
712
        goto retry; /* recoverable error*/
sletz's avatar
sletz committed
713
714
715
    }

    if (nframes != fEngineControl->fBufferSize)
716
        jack_log("JackFFADODriver::Read warning nframes = %ld", nframes);
717

718
    // Has to be done before read
719
    JackDriver::CycleIncTime();
sletz's avatar
sletz committed
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776

    printExit();
    return ffado_driver_read((ffado_driver_t *)fDriver, fEngineControl->fBufferSize);
}

int JackFFADODriver::Write()
{
    printEnter();
    int res = ffado_driver_write((ffado_driver_t *)fDriver, fEngineControl->fBufferSize);
    printExit();
    return res;
}

void
JackFFADODriver::jack_driver_init (jack_driver_t *driver)
{
    memset (driver, 0, sizeof (*driver));

    driver->attach = 0;
    driver->detach = 0;
    driver->write = 0;
    driver->read = 0;
    driver->null_cycle = 0;
    driver->bufsize = 0;
    driver->start = 0;
    driver->stop = 0;
}

void
JackFFADODriver::jack_driver_nt_init (jack_driver_nt_t * driver)
{
    memset (driver, 0, sizeof (*driver));

    jack_driver_init ((jack_driver_t *) driver);

    driver->attach = 0;
    driver->detach = 0;
    driver->bufsize = 0;
    driver->stop = 0;
    driver->start = 0;

    driver->nt_bufsize = 0;
    driver->nt_start = 0;
    driver->nt_stop = 0;
    driver->nt_attach = 0;
    driver->nt_detach = 0;
    driver->nt_run_cycle = 0;
}

} // end of namespace


#ifdef __cplusplus
extern "C"
{
#endif

777
    SERVER_EXPORT const jack_driver_desc_t *
sletz's avatar
sletz committed
778
779
    driver_get_descriptor () {
        jack_driver_desc_t * desc;
780
781
782
        jack_driver_desc_filler_t filler;
        jack_driver_param_value_t value;

783
        desc = jack_driver_descriptor_construct("firewire", JackDriverMaster, "Linux FFADO API based audio backend", &filler);
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825

        strcpy(value.str, "hw:0");
        jack_driver_descriptor_add_parameter(
            desc,
            &filler,
            "device",
            'd',
            JackDriverParamString,
            &value,
            NULL,
            "The FireWire device to use.",
            "The FireWire device to use. Please consult the FFADO documentation for more info.");

        value.ui = 1024;
        jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", NULL);

        value.ui = 3;
        jack_driver_descriptor_add_parameter(desc, &filler, "nperiods", 'n', JackDriverParamUInt, &value, NULL, "Number of periods of playback latency", NULL);

        value.ui = 48000U;
        jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);

        value.i = 0;
        jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamBool, &value, NULL, "Provide capture ports.", NULL);
        jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamBool, &value, NULL, "Provide playback ports.", NULL);

        value.i = 1;
        jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports.", NULL);

        value.ui = 0;
        jack_driver_descriptor_add_parameter(desc, &filler, "input-latency", 'I', JackDriverParamUInt, &value, NULL, "Extra input latency (frames)", NULL);
        jack_driver_descriptor_add_parameter(desc, &filler, "output-latency", 'O', JackDriverParamUInt, &value, NULL, "Extra output latency (frames)", NULL);

        value.ui = 0;
        jack_driver_descriptor_add_parameter(desc, &filler, "inchannels", 'i', JackDriverParamUInt, &value, NULL, "Number of input channels to provide (note: currently ignored)", NULL);
        jack_driver_descriptor_add_parameter(desc, &filler, "outchannels", 'o', JackDriverParamUInt, &value, NULL, "Number of output channels to provide (note: currently ignored)", NULL);

        value.ui = 3;
        jack_driver_descriptor_add_parameter(desc, &filler, "verbose", 'v', JackDriverParamUInt, &value, NULL, "libffado verbose level", NULL);

        value.i = 0;
        jack_driver_descriptor_add_parameter(desc, &filler, "snoop", 'X', JackDriverParamBool, &value, NULL, "Snoop firewire traffic", NULL);
sletz's avatar
sletz committed
826

sletz's avatar
sletz committed
827
828
829
        return desc;
    }

830
    SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params) {
sletz's avatar
sletz committed
831
832
833
834
835
        const JSList * node;
        const jack_driver_param_t * param;

        ffado_jack_settings_t cmlparams;

sletz's avatar
sletz committed
836
        char *device_name=(char*)"hw:0";
pieterpalmers's avatar
pieterpalmers committed
837

sletz's avatar
sletz committed
838
839
840
841
842
843
844
845
846
847
848
849
850
        cmlparams.period_size_set = 0;
        cmlparams.sample_rate_set = 0;
        cmlparams.buffer_size_set = 0;

        /* default values */
        cmlparams.period_size = 1024;
        cmlparams.sample_rate = 48000;
        cmlparams.buffer_size = 3;
        cmlparams.playback_ports = 0;
        cmlparams.capture_ports = 0;
        cmlparams.playback_frame_latency = 0;
        cmlparams.capture_frame_latency = 0;

sletz's avatar
sletz committed
851
852
853
854
855
856
        cmlparams.verbose_level = 0;

        cmlparams.slave_mode = 0;
        cmlparams.snoop_mode = 0;
        cmlparams.device_info = NULL;

sletz's avatar
sletz committed
857
858
859
860
        for (node = params; node; node = jack_slist_next (node)) {
            param = (jack_driver_param_t *) node->data;

            switch (param->character) {
pieterpalmers's avatar
pieterpalmers committed
861
                case 'd':
sletz's avatar
sletz committed
862
                    device_name = const_cast<char*>(param->value.str);
pieterpalmers's avatar
pieterpalmers committed
863
                    break;
sletz's avatar
sletz committed
864
865
866
867
868
869
870
871
872
873
874
875
                case 'p':
                    cmlparams.period_size = param->value.ui;
                    cmlparams.period_size_set = 1;
                    break;
                case 'n':
                    cmlparams.buffer_size = param->value.ui;
                    cmlparams.buffer_size_set = 1;
                    break;
                case 'r':
                    cmlparams.sample_rate = param->value.ui;
                    cmlparams.sample_rate_set = 1;
                    break;
pieterpalmers's avatar
pieterpalmers committed
876
877
                case 'i':
                    cmlparams.capture_ports = param->value.ui;
sletz's avatar
sletz committed
878
                    break;
pieterpalmers's avatar
pieterpalmers committed
879
880
                case 'o':
                    cmlparams.playback_ports = param->value.ui;
sletz's avatar
sletz committed
881
882
883
884
885
886
887
                    break;
                case 'I':
                    cmlparams.capture_frame_latency = param->value.ui;
                    break;
                case 'O':
                    cmlparams.playback_frame_latency = param->value.ui;
                    break;
pieterpalmers's avatar
pieterpalmers committed
888
889
                case 'x':
                    cmlparams.slave_mode = param->value.ui;
sletz's avatar
sletz committed
890
                    break;
pieterpalmers's avatar
pieterpalmers committed
891
                case 'X':
sletz's avatar
sletz committed
892
                    cmlparams.snoop_mode = param->value.i;
sletz's avatar
sletz committed
893
894
895
896
897
898
899
900
                    break;
                case 'v':
                    cmlparams.verbose_level = param->value.ui;
            }
        }

        /* duplex is the default */
        if (!cmlparams.playback_ports && !cmlparams.capture_ports) {
pieterpalmers's avatar
pieterpalmers committed
901
902
            cmlparams.playback_ports = 1;
            cmlparams.capture_ports = 1;
sletz's avatar
sletz committed
903
904
        }

pieterpalmers's avatar
pieterpalmers committed
905
906
907
        // temporary
        cmlparams.device_info = device_name;

908
        Jack::JackFFADODriver* ffado_driver = new Jack::JackFFADODriver("system", "firewire_pcm", engine, table);
sletz's avatar
sletz committed
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
        Jack::JackDriverClientInterface* threaded_driver = new Jack::JackThreadedDriver(ffado_driver);
        // Special open for FFADO driver...
        if (ffado_driver->Open(&cmlparams) == 0) {
            return threaded_driver;
        } else {
            delete threaded_driver; // Delete the decorated driver
            return NULL;
        }
    }

#ifdef __cplusplus
}
#endif