JackFFADODriver.cpp 36.9 KB
Newer Older
sletz's avatar
sletz committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
Copyright (C) 2001 Paul Davis
Copyright (C) 2004 Grame
Copyright (C) 2007 Pieter Palmers

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.

*/

22
23
24
25
#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif

sletz's avatar
sletz committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#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"
#include "JackEngineControl.h"
#include "JackClientControl.h"
#include "JackPort.h"
#include "JackGraphManager.h"
sletz's avatar
sletz committed
47
#include "JackExports.h"
sletz's avatar
sletz committed
48
49
50
51

namespace Jack
{

sletz's avatar
sletz committed
52
#define FIREWIRE_REQUIRED_FFADO_API_VERSION 8
sletz's avatar
sletz committed
53
54
55
56
57
58
59
60
61

#define jack_get_microseconds GetMicroSeconds

#define SAMPLE_MAX_24BIT  8388608.0f
#define SAMPLE_MAX_16BIT  32768.0f

int
JackFFADODriver::ffado_driver_read (ffado_driver_t * driver, jack_nframes_t nframes)
{
62
    channel_t chn;
sletz's avatar
sletz committed
63
64
65
    jack_default_audio_sample_t* buf = NULL;

    printEnter();
sletz's avatar
sletz committed
66
67
    for (chn = 0; chn < driver->capture_nchannels; chn++) {
        // if nothing connected, don't process
sletz's avatar
sletz committed
68
69
        if (fGraphManager->GetConnectionsNum(fCapturePortList[chn]) == 0) {
            buf = (jack_default_audio_sample_t*)driver->scratchbuffer;
sletz's avatar
sletz committed
70
71
72
73
74
75
            // 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
76
            if (driver->capture_channels[chn].stream_type == ffado_stream_type_audio) {
sletz's avatar
sletz committed
77
78
79
                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
80
81
                if (!buf) buf = (jack_default_audio_sample_t*)driver->scratchbuffer;

sletz's avatar
sletz committed
82
83
84
                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
85
86
                ffado_streaming_set_capture_stream_buffer(driver->dev, chn,
                        (char *)(driver->capture_channels[chn].midi_buffer));
sletz's avatar
sletz committed
87
88
89
90
91
92
                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
93
94
95
        }
    }

sletz's avatar
sletz committed
96
97
    /* now transfer the buffers */
    ffado_streaming_transfer_capture_buffers(driver->dev);
sletz's avatar
sletz committed
98

sletz's avatar
sletz committed
99
100
101
    /* process the midi data */
    for (chn = 0; chn < driver->capture_nchannels; chn++) {
        if (driver->capture_channels[chn].stream_type == ffado_stream_type_midi) {
102
            jack_nframes_t i;
sletz's avatar
sletz committed
103
104
105
106
107
108
109
            int done;
            uint32_t *midi_buffer = driver->capture_channels[chn].midi_buffer;
            midi_unpack_t *midi_unpack = &driver->capture_channels[chn].midi_unpack;
            buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fCapturePortList[chn],  nframes);
            jack_midi_clear_buffer(buf);

            /* if the returned buffer is invalid, discard the midi data */
sletz's avatar
sletz committed
110
            if (!buf) continue;
sletz's avatar
sletz committed
111
112
113
            /* else unpack
               note that libffado guarantees that midi bytes are on 8-byte aligned indexes
             */
sletz's avatar
sletz committed
114
115
116
            for (i = 0; i < nframes; i += 8) {
                if (midi_buffer[i] & 0xFF000000) {
                    done = midi_unpack_buf(midi_unpack, (unsigned char *)(midi_buffer + i), 1, buf, i);
sletz's avatar
sletz committed
117
118
119
120
                    if (done != 1) {
                        printError("buffer overflow in channel %d\n", chn);
                        break;
                    }
sletz's avatar
sletz committed
121

sletz's avatar
sletz committed
122
                    printMessage("MIDI IN: %08X (i=%d)", midi_buffer[i], i);
sletz's avatar
sletz committed
123
124
125
126
127
128
129
130
131
132
133
134
                }
            }
        }
    }

    printExit();
    return 0;
}

int
JackFFADODriver::ffado_driver_write (ffado_driver_t * driver, jack_nframes_t nframes)
{
135
    channel_t chn;
sletz's avatar
sletz committed
136
    jack_default_audio_sample_t* buf;
sletz's avatar
sletz committed
137
138
139
140
    printEnter();

    driver->process_count++;

sletz's avatar
sletz committed
141
    for (chn = 0; chn < driver->playback_nchannels; chn++) {
sletz's avatar
sletz committed
142
143
        if (fGraphManager->GetConnectionsNum(fPlaybackPortList[chn]) == 0) {
            buf = (jack_default_audio_sample_t*)driver->nullbuffer;
sletz's avatar
sletz committed
144
145
146
147
148
149
            // 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
150
            if (driver->playback_channels[chn].stream_type == ffado_stream_type_audio) {
sletz's avatar
sletz committed
151
152
                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
153
                if (!buf) buf = (jack_default_audio_sample_t*)driver->nullbuffer;
sletz's avatar
sletz committed
154
155
156
                ffado_streaming_set_playback_stream_buffer(driver->dev, chn, (char *)(buf));

            } else if (driver->playback_channels[chn].stream_type == ffado_stream_type_midi) {
157
158
                jack_nframes_t nevents;
                jack_nframes_t i;
sletz's avatar
sletz committed
159
160
161
                midi_pack_t *midi_pack = &driver->playback_channels[chn].midi_pack;
                uint32_t *midi_buffer = driver->playback_channels[chn].midi_buffer;
                buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fPlaybackPortList[chn], nframes);
162
                jack_nframes_t min_next_pos = 0;
sletz's avatar
sletz committed
163
164
165
166
167

                memset(midi_buffer, 0, nframes * sizeof(uint32_t));
                ffado_streaming_set_playback_stream_buffer(driver->dev, chn, (char *)(midi_buffer));

                /* if the returned buffer is invalid, continue */
sletz's avatar
sletz committed
168
                if (!buf) {
sletz's avatar
sletz committed
169
170
171
172
                    ffado_streaming_playback_stream_onoff(driver->dev, chn, 0);
                    continue;
                }
                ffado_streaming_playback_stream_onoff(driver->dev, chn, 1);
sletz's avatar
sletz committed
173

sletz's avatar
sletz committed
174
                // check if we still have to process bytes from the previous period
sletz's avatar
sletz committed
175
                if (driver->playback_channels[chn].nb_overflow_bytes) {
sletz's avatar
sletz committed
176
177
                    printMessage("have to process %d bytes from previous period", driver->playback_channels[chn].nb_overflow_bytes);
                }
sletz's avatar
sletz committed
178
                for (i = 0; i < driver->playback_channels[chn].nb_overflow_bytes; ++i) {
sletz's avatar
sletz committed
179
180
181
                    midi_buffer[min_next_pos] = 0x01000000 | (driver->playback_channels[chn].overflow_buffer[i] & 0xFF);
                    min_next_pos += 8;
                }
sletz's avatar
sletz committed
182
                driver->playback_channels[chn].nb_overflow_bytes = 0;
sletz's avatar
sletz committed
183
184
185
186
187

                // process the events in this period
                nevents = jack_midi_get_event_count(buf);
                //if (nevents)
                //  printMessage("MIDI: %d events in ch %d", nevents, chn);
sletz's avatar
sletz committed
188
189

                for (i = 0; i < nevents; ++i) {
190
                    size_t j;
sletz's avatar
sletz committed
191
192
                    jack_midi_event_t event;
                    jack_midi_event_get(&event, buf, i);
sletz's avatar
sletz committed
193

sletz's avatar
sletz committed
194
                    midi_pack_event(midi_pack, &event);
sletz's avatar
sletz committed
195

sletz's avatar
sletz committed
196
                    // floor the initial position to be a multiple of 8
197
                    jack_nframes_t pos = event.time & 0xFFFFFFF8;
sletz's avatar
sletz committed
198
                    for (j = 0; j < event.size; j++) {
sletz's avatar
sletz committed
199
                        // make sure we don't overwrite a previous byte
sletz's avatar
sletz committed
200
                        while (pos < min_next_pos && pos < nframes) {
sletz's avatar
sletz committed
201
202
203
204
                            pos += 8;
                            printMessage("have to correct pos to %d", pos);
                        }

sletz's avatar
sletz committed
205
                        if (pos >= nframes) {
206
                            unsigned int f;
sletz's avatar
sletz committed
207
208
                            printMessage("midi message crosses period boundary");
                            driver->playback_channels[chn].nb_overflow_bytes = event.size - j;
sletz's avatar
sletz committed
209
                            if (driver->playback_channels[chn].nb_overflow_bytes > MIDI_OVERFLOW_BUFFER_SIZE) {
sletz's avatar
sletz committed
210
211
212
213
                                printError("too much midi bytes cross period boundary");
                                driver->playback_channels[chn].nb_overflow_bytes = MIDI_OVERFLOW_BUFFER_SIZE;
                            }
                            // save the bytes that still have to be transmitted in the next period
sletz's avatar
sletz committed
214
                            for (f = 0; f < driver->playback_channels[chn].nb_overflow_bytes; f++) {
sletz's avatar
sletz committed
215
216
217
218
                                driver->playback_channels[chn].overflow_buffer[f] = event.buffer[j+f];
                            }
                            // exit since we can't transmit anything anymore.
                            // the rate should be controlled
sletz's avatar
sletz committed
219
220
                            if (i < nevents - 1) {
                                printError("%d midi events lost due to period crossing", nevents - i - 1);
sletz's avatar
sletz committed
221
222
223
224
225
226
227
228
229
                            }
                            break;
                        } else {
                            midi_buffer[pos] = 0x01000000 | (event.buffer[j] & 0xFF);
                            pos += 8;
                            min_next_pos = pos;
                        }
                    }
                    //printMessage("MIDI: sent %d-byte event at %ld", (int)event.size, (long)event.time);
sletz's avatar
sletz committed
230
231
                }

sletz's avatar
sletz committed
232
233
234
            } 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
235
236
237
238
239
            }
        }
    }

    ffado_streaming_transfer_playback_buffers(driver->dev);
sletz's avatar
sletz committed
240

sletz's avatar
sletz committed
241
242
243
244
245
246
    printExit();
    return 0;
}

jack_nframes_t
JackFFADODriver::ffado_driver_wait (ffado_driver_t *driver, int extra_fd, int *status,
sletz's avatar
sletz committed
247
                                    float *delayed_usecs)
sletz's avatar
sletz committed
248
249
250
{
    jack_time_t wait_enter;
    jack_time_t wait_ret;
sletz's avatar
sletz committed
251
    ffado_wait_response response;
sletz's avatar
sletz committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268

    printEnter();

    wait_enter = jack_get_microseconds ();
    if (wait_enter > driver->wait_next) {
        /*
        	* This processing cycle was delayed past the
        	* next due interrupt!  Do not account this as
        	* a wakeup delay:
        	*/
        driver->wait_next = 0;
        driver->wait_late++;
    }
// *status = -2; interrupt
// *status = -3; timeout
// *status = -4; extra FD

sletz's avatar
sletz committed
269
    response = ffado_streaming_wait(driver->dev);
sletz's avatar
sletz committed
270
271
272
273
274
275
276
277
278
279

    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;
// 	driver->engine->transport_cycle_start (driver->engine, wait_ret);

sletz's avatar
sletz committed
280
281
282
283
    if(response == ffado_wait_ok) {
       // all good
       *status = 0;
    } else if (response == ffado_wait_xrun) {
sletz's avatar
sletz committed
284
        // xrun happened, but it's handled
sletz's avatar
sletz committed
285
        *status = 0;
sletz's avatar
sletz committed
286
287
288
289
        return 0;
    } else if (response == ffado_wait_error) {
        // an error happened (unhandled xrun)
        // this should be fatal
sletz's avatar
sletz committed
290
        *status = -1;
sletz's avatar
sletz committed
291
        return 0;
sletz's avatar
sletz committed
292
293
294
295
296
297
298
299
300
301
    } else if (response == ffado_wait_shutdown) {
        // ffado requested shutdown (e.g. device unplugged)
        // this should be fatal
        *status = -1;
        return 0;
    } else {
        // unknown response code. should be fatal
        // this should be fatal
        *status = -1;
        return 0;
sletz's avatar
sletz committed
302
303
    }

sletz's avatar
sletz committed
304
    fBeginDateUst = wait_ret;
sletz's avatar
sletz committed
305
306

    printExit();
sletz's avatar
sletz committed
307
    return driver->period_size;
sletz's avatar
sletz committed
308
309
310
311
312
313
314
315
316
}

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
317

sletz's avatar
sletz committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
        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();
}

int
JackFFADODriver::SetBufferSize (jack_nframes_t nframes)
{
    printError("Buffer size change requested but not supported!!!");

    /*
sletz's avatar
sletz committed
350
    driver->period_size = nframes; 
sletz's avatar
sletz committed
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    driver->period_usecs =
    	(jack_time_t) floor ((((float) nframes) / driver->sample_rate)
    			     * 1000000.0f);
    */

    /* 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 *
365
JackFFADODriver::ffado_driver_new (const char *name,
sletz's avatar
sletz committed
366
                                   ffado_jack_settings_t *params)
sletz's avatar
sletz committed
367
368
369
370
371
{
    ffado_driver_t *driver;

    assert(params);

sletz's avatar
sletz committed
372
    if (ffado_get_api_version() != FIREWIRE_REQUIRED_FFADO_API_VERSION) {
sletz's avatar
sletz committed
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
        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);

    /*	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;
    	*/

    /* 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
401
    fBeginDateUst = 0;
sletz's avatar
sletz committed
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429

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

// 	driver->client = client;
    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;

    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
430
    free (driver);
sletz's avatar
sletz committed
431
432
433
434
435
436
437
438
439
440
441
442
443
}

int JackFFADODriver::Attach()
{
    JackPort* port;
    int port_index;
    unsigned long port_flags;

    char buf[JACK_PORT_NAME_SIZE];
    char portname[JACK_PORT_NAME_SIZE];

    ffado_driver_t* driver = (ffado_driver_t*)fDriver;

sletz's avatar
sletz committed
444
    jack_log("JackFFADODriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
sletz's avatar
sletz committed
445
446
447

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

sletz's avatar
sletz committed
448
449
450
451
452
    /* 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
453
    if (driver->nullbuffer == NULL) {
sletz's avatar
sletz committed
454
455
456
457
458
        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
459

sletz's avatar
sletz committed
460
461
    /* 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
462
    if (driver->scratchbuffer == NULL) {
sletz's avatar
sletz committed
463
464
465
466
        printError("could not allocate memory for scratch buffer");
        return -1;
    }

sletz's avatar
sletz committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
    /* packetizer thread options */
    driver->device_options.realtime = (fEngineControl->fRealTime ? 1 : 0);

    driver->device_options.packetizer_priority = fEngineControl->fPriority +
            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
491
492
    ffado_streaming_set_audio_datatype(driver->dev, ffado_audio_datatype_float);

sletz's avatar
sletz committed
493
494
495
496
497
498
    /* ports */

    // capture
    port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;

    driver->capture_nchannels = ffado_streaming_get_nb_capture_streams(driver->dev);
sletz's avatar
sletz committed
499
500
    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
501
502
503
        printError("could not allocate memory for capture channel list");
        return -1;
    }
sletz's avatar
sletz committed
504

sletz's avatar
sletz committed
505
    fCaptureChannels = 0;
506
    for (channel_t chn = 0; chn < driver->capture_nchannels; chn++) {
sletz's avatar
sletz committed
507
        ffado_streaming_get_capture_stream_name(driver->dev, chn, portname, sizeof(portname) - 1);
sletz's avatar
sletz committed
508

sletz's avatar
sletz committed
509
510
        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) {
511
            snprintf(buf, sizeof(buf) - 1, "%s:AC%d_%s", fClientControl.fName, (int)chn, portname);
sletz's avatar
sletz committed
512
            printMessage ("Registering audio capture port %s", buf);
513
            if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, buf,
sletz's avatar
sletz committed
514
515
516
                              JACK_DEFAULT_AUDIO_TYPE,
                              (JackPortFlags)port_flags,
                              fEngineControl->fBufferSize)) == NO_PORT) {
sletz's avatar
sletz committed
517
518
519
520
521
522
523
524
525
526
527
528
529
                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);
            port->SetLatency(driver->period_size + driver->capture_frame_latency);
            fCapturePortList[chn] = port_index;
sletz's avatar
sletz committed
530
            jack_log("JackFFADODriver::Attach fCapturePortList[i] %ld ", port_index);
sletz's avatar
sletz committed
531
532
            fCaptureChannels++;

sletz's avatar
sletz committed
533
        } else if (driver->capture_channels[chn].stream_type == ffado_stream_type_midi) {
534
            snprintf(buf, sizeof(buf) - 1, "%s:MC%d_%s", fClientControl.fName, (int)chn, portname);
sletz's avatar
sletz committed
535
            printMessage ("Registering midi capture port %s", buf);
536
            if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, buf,
sletz's avatar
sletz committed
537
538
539
                              JACK_DEFAULT_MIDI_TYPE,
                              (JackPortFlags)port_flags,
                              fEngineControl->fBufferSize)) == NO_PORT) {
sletz's avatar
sletz committed
540
541
542
543
                jack_error("driver: cannot register port for %s", buf);
                return -1;
            }

sletz's avatar
sletz committed
544
545
546
547
            // 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
548
            if (ffado_streaming_capture_stream_onoff(driver->dev, chn, 0)) {
sletz's avatar
sletz committed
549
550
                printError(" cannot enable port %s", buf);
            }
sletz's avatar
sletz committed
551

sletz's avatar
sletz committed
552
553
554
555
556
            // setup midi unpacker
            midi_unpack_init(&driver->capture_channels[chn].midi_unpack);
            midi_unpack_reset(&driver->capture_channels[chn].midi_unpack);
            // setup the midi buffer
            driver->capture_channels[chn].midi_buffer = (uint32_t *)calloc(driver->period_size, sizeof(uint32_t));
sletz's avatar
sletz committed
557
558
559

            port = fGraphManager->GetPort(port_index);
            port->SetLatency(driver->period_size + driver->capture_frame_latency);
sletz's avatar
sletz committed
560
            fCapturePortList[chn] = port_index;
sletz's avatar
sletz committed
561
            jack_log("JackFFADODriver::Attach fCapturePortList[i] %ld ", port_index);
sletz's avatar
sletz committed
562
563
564
            fCaptureChannels++;
        } else {
            printMessage ("Don't register capture port %s", portname);
sletz's avatar
sletz committed
565
566
567
568
569
570
571
        }
    }

    // playback
    port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;

    driver->playback_nchannels = ffado_streaming_get_nb_playback_streams(driver->dev);
sletz's avatar
sletz committed
572
573
    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
574
575
576
        printError("could not allocate memory for playback channel list");
        return -1;
    }
sletz's avatar
sletz committed
577

sletz's avatar
sletz committed
578
    fPlaybackChannels = 0;
579
    for (channel_t chn = 0; chn < driver->playback_nchannels; chn++) {
sletz's avatar
sletz committed
580
        ffado_streaming_get_playback_stream_name(driver->dev, chn, portname, sizeof(portname) - 1);
sletz's avatar
sletz committed
581

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

sletz's avatar
sletz committed
584
        if (driver->playback_channels[chn].stream_type == ffado_stream_type_audio) {
585
            snprintf(buf, sizeof(buf) - 1, "%s:AP%d_%s", fClientControl.fName, (int)chn, portname);
sletz's avatar
sletz committed
586
            printMessage ("Registering audio playback port %s", buf);
587
            if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, buf,
sletz's avatar
sletz committed
588
589
590
                              JACK_DEFAULT_AUDIO_TYPE,
                              (JackPortFlags)port_flags,
                              fEngineControl->fBufferSize)) == NO_PORT) {
sletz's avatar
sletz committed
591
592
593
594
                jack_error("driver: cannot register port for %s", buf);
                return -1;
            }

sletz's avatar
sletz committed
595
596
597
598
            // 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
599
            if (ffado_streaming_playback_stream_onoff(driver->dev, chn, 0)) {
sletz's avatar
sletz committed
600
601
                printError(" cannot enable port %s", buf);
            }
sletz's avatar
sletz committed
602
603

            port = fGraphManager->GetPort(port_index);
604
605
            // Add one buffer more latency if "async" mode is used...
            port->SetLatency((driver->period_size * (driver->device_options.nb_buffers - 1)) + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize) + driver->playback_frame_latency);
sletz's avatar
sletz committed
606
            fPlaybackPortList[chn] = port_index;
sletz's avatar
sletz committed
607
            jack_log("JackFFADODriver::Attach fPlaybackPortList[i] %ld ", port_index);
sletz's avatar
sletz committed
608
            fPlaybackChannels++;
sletz's avatar
sletz committed
609
        } else if (driver->playback_channels[chn].stream_type == ffado_stream_type_midi) {
610
            snprintf(buf, sizeof(buf) - 1, "%s:MP%d_%s", fClientControl.fName, (int)chn, portname);
sletz's avatar
sletz committed
611
            printMessage ("Registering midi playback port %s", buf);
612
            if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, buf,
sletz's avatar
sletz committed
613
614
615
                              JACK_DEFAULT_MIDI_TYPE,
                              (JackPortFlags)port_flags,
                              fEngineControl->fBufferSize)) == NO_PORT) {
sletz's avatar
sletz committed
616
617
618
619
620
621
622
623
                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
624
            if (ffado_streaming_playback_stream_onoff(driver->dev, chn, 0)) {
sletz's avatar
sletz committed
625
626
627
628
629
630
631
632
633
634
                printError(" cannot enable port %s", buf);
            }
            // setup midi packer
            midi_pack_reset(&driver->playback_channels[chn].midi_pack);
            // setup the midi buffer
            driver->playback_channels[chn].midi_buffer = (uint32_t *)calloc(driver->period_size, sizeof(uint32_t));

            port = fGraphManager->GetPort(port_index);
            port->SetLatency((driver->period_size * (driver->device_options.nb_buffers - 1)) + driver->playback_frame_latency);
            fPlaybackPortList[chn] = port_index;
sletz's avatar
sletz committed
635
            jack_log("JackFFADODriver::Attach fPlaybackPortList[i] %ld ", port_index);
sletz's avatar
sletz committed
636
637
638
            fPlaybackChannels++;
        } else {
            printMessage ("Don't register playback port %s", portname);
sletz's avatar
sletz committed
639
640
641
642
643
644
        }
    }

    assert(fCaptureChannels < PORT_NUM);
    assert(fPlaybackChannels < PORT_NUM);

sletz's avatar
sletz committed
645
    if (ffado_streaming_prepare(driver->dev)) {
sletz's avatar
sletz committed
646
647
648
649
650
651
652
653
654
655
656
        printError("Could not prepare streaming device!");
        return -1;
    }

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

int JackFFADODriver::Detach()
{
657
    channel_t chn;
sletz's avatar
sletz committed
658
    ffado_driver_t* driver = (ffado_driver_t*)fDriver;
sletz's avatar
sletz committed
659
    jack_log("JackFFADODriver::Detach");
sletz's avatar
sletz committed
660
661
662
663
664

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

sletz's avatar
sletz committed
665
666
    // free all internal buffers
    for (chn = 0; chn < driver->capture_nchannels; chn++) {
sletz's avatar
sletz committed
667
        if (driver->capture_channels[chn].midi_buffer)
sletz's avatar
sletz committed
668
            free(driver->capture_channels[chn].midi_buffer);
sletz's avatar
sletz committed
669
    }
sletz's avatar
sletz committed
670
    free(driver->capture_channels);
sletz's avatar
sletz committed
671

sletz's avatar
sletz committed
672
    for (chn = 0; chn < driver->playback_nchannels; chn++) {
sletz's avatar
sletz committed
673
        if (driver->playback_channels[chn].midi_buffer)
sletz's avatar
sletz committed
674
675
676
677
678
679
            free(driver->playback_channels[chn].midi_buffer);
    }
    free(driver->playback_channels);

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

sletz's avatar
sletz committed
681
    return JackAudioDriver::Detach();  // Generic JackAudioDriver Detach
sletz's avatar
sletz committed
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
}

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
699
700
        //fCaptureChannels = ((ffado_driver_t *)fDriver)->capture_nchannels_audio;
        //fPlaybackChannels = ((ffado_driver_t *)fDriver)->playback_nchannels_audio;
sletz's avatar
sletz committed
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
        return 0;
    } else {
        return -1;
    }
}

int JackFFADODriver::Close()
{
    JackAudioDriver::Close();
    ffado_driver_delete((ffado_driver_t*)fDriver);
    return 0;
}

int JackFFADODriver::Start()
{
    return ffado_driver_start((ffado_driver_t *)fDriver);
}

int JackFFADODriver::Stop()
{
    return ffado_driver_stop((ffado_driver_t *)fDriver);
}

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
731
    fDelayedUsecs = 0.f;
sletz's avatar
sletz committed
732

sletz's avatar
sletz committed
733
    jack_nframes_t nframes = ffado_driver_wait(driver, -1, &wait_status,
sletz's avatar
sletz committed
734
                             &fDelayedUsecs);
sletz's avatar
sletz committed
735
736
737
738
739
740
741
742
743
744

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

    if (nframes == 0) {
        /* we detected an xrun and restarted: notify
         * clients about the delay. 
         */
sletz's avatar
sletz committed
745
        jack_log("FFADO XRun");
sletz's avatar
sletz committed
746
        NotifyXRun(fBeginDateUst, fDelayedUsecs);
sletz's avatar
sletz committed
747
748
749
750
        return -1;
    }

    if (nframes != fEngineControl->fBufferSize)
sletz's avatar
sletz committed
751
        jack_log("JackFFADODriver::Read nframes = %ld", nframes);
752
753
        
    // Has to be done before read
754
    JackDriver::CycleIncTime();
sletz's avatar
sletz committed
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
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

    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

sletz's avatar
sletz committed
812
    EXPORT const jack_driver_desc_t *
sletz's avatar
sletz committed
813
814
815
816
817
818
819
820
    driver_get_descriptor () {
        jack_driver_desc_t * desc;
        jack_driver_param_desc_t * params;
        unsigned int i;

        desc = (jack_driver_desc_t *)calloc (1, sizeof (jack_driver_desc_t));

        strcpy (desc->name, "firewire");
821
        desc->nparams = 11;
sletz's avatar
sletz committed
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916

        params = (jack_driver_param_desc_t *)calloc (desc->nparams, sizeof (jack_driver_param_desc_t));
        desc->params = params;

        i = 0;
        strcpy (params[i].name, "period");
        params[i].character  = 'p';
        params[i].type       = JackDriverParamUInt;
        params[i].value.ui   = 1024;
        strcpy (params[i].short_desc, "Frames per period");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "nperiods");
        params[i].character  = 'n';
        params[i].type       = JackDriverParamUInt;
        params[i].value.ui   = 3;
        strcpy (params[i].short_desc, "Number of periods of playback latency");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "rate");
        params[i].character  = 'r';
        params[i].type       = JackDriverParamUInt;
        params[i].value.ui   = 48000U;
        strcpy (params[i].short_desc, "Sample rate");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "capture");
        params[i].character  = 'C';
        params[i].type       = JackDriverParamBool;
        params[i].value.i    = 0;
        strcpy (params[i].short_desc, "Provide capture ports.");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "playback");
        params[i].character  = 'P';
        params[i].type       = JackDriverParamBool;
        params[i].value.i    = 0;
        strcpy (params[i].short_desc, "Provide playback ports.");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "duplex");
        params[i].character  = 'D';
        params[i].type       = JackDriverParamBool;
        params[i].value.i    = 1;
        strcpy (params[i].short_desc, "Provide both capture and playback ports.");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "input-latency");
        params[i].character  = 'I';
        params[i].type       = JackDriverParamUInt;
        params[i].value.ui    = 0;
        strcpy (params[i].short_desc, "Extra input latency (frames)");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "output-latency");
        params[i].character  = 'O';
        params[i].type       = JackDriverParamUInt;
        params[i].value.ui    = 0;
        strcpy (params[i].short_desc, "Extra output latency (frames)");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "inchannels");
        params[i].character  = 'i';
        params[i].type       = JackDriverParamUInt;
        params[i].value.ui    = 0;
        strcpy (params[i].short_desc, "Number of input channels to provide (note: currently ignored)");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "outchannels");
        params[i].character  = 'o';
        params[i].type       = JackDriverParamUInt;
        params[i].value.ui    = 0;
        strcpy (params[i].short_desc, "Number of output channels to provide (note: currently ignored)");
        strcpy (params[i].long_desc, params[i].short_desc);

        i++;
        strcpy (params[i].name, "verbose");
        params[i].character  = 'v';
        params[i].type       = JackDriverParamUInt;
        params[i].value.ui    = 3;
        strcpy (params[i].short_desc, "libffado verbose level");
        strcpy (params[i].long_desc, params[i].short_desc);

        return desc;
    }

sletz's avatar
sletz committed
917
    EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params) {
sletz's avatar
sletz committed
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
        const JSList * node;
        const jack_driver_param_t * param;

        ffado_jack_settings_t cmlparams;

        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
936
937
938
939
940
941
        cmlparams.verbose_level = 0;

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

sletz's avatar
sletz committed
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
        for (node = params; node; node = jack_slist_next (node)) {
            param = (jack_driver_param_t *) node->data;

            switch (param->character) {
                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;
                case 'C':
                    cmlparams.capture_ports = 1;
                    break;
                case 'P':
                    cmlparams.playback_ports = 1;
                    break;
                case 'D':
                    cmlparams.capture_ports = 1;
                    cmlparams.playback_ports = 1;
                    break;
                case 'I':
                    cmlparams.capture_frame_latency = param->value.ui;
                    break;
                case 'O':
                    cmlparams.playback_frame_latency = param->value.ui;
                    break;
                    // ignore these for now
                case 'i':
                    break;
                case 'o':
                    break;
                case 'v':
                    cmlparams.verbose_level = param->value.ui;
            }
        }

        /* duplex is the default */
        if (!cmlparams.playback_ports && !cmlparams.capture_ports) {
            cmlparams.playback_ports = TRUE;
            cmlparams.capture_ports = TRUE;
        }

990
        Jack::JackFFADODriver* ffado_driver = new Jack::JackFFADODriver("system", "firewire_pcm", engine, table);
sletz's avatar
sletz committed
991
992
993
994
995
996
997
998
999
1000
        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;
        }
    }