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

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.

*/

21
22
#define __STDC_FORMAT_MACROS   // For inttypes.h to work in C++

sletz's avatar
sletz committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#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 <string.h>

#include "JackAlsaDriver.h"
#include "JackEngineControl.h"
#include "JackClientControl.h"
#include "JackPort.h"
#include "JackGraphManager.h"
sletz's avatar
sletz committed
41
#include "JackLockedEngine.h"
42
43
#include "JackPosixThread.h"
#include "JackCompilerDeps.h"
44
#include "JackServerGlobals.h"
sletz's avatar
sletz committed
45
46
47
48

namespace Jack
{

sletz's avatar
sletz committed
49
int JackAlsaDriver::SetBufferSize(jack_nframes_t buffer_size)
sletz's avatar
sletz committed
50
{
sletz's avatar
sletz committed
51
    jack_log("JackAlsaDriver::SetBufferSize %ld", buffer_size);
52
    int res = alsa_driver_reset_parameters((alsa_driver_t *)fDriver, buffer_size,
sletz's avatar
sletz committed
53
54
                                           ((alsa_driver_t *)fDriver)->user_nperiods,
                                           ((alsa_driver_t *)fDriver)->frame_rate);
sletz's avatar
sletz committed
55

sletz's avatar
sletz committed
56
    if (res == 0) { // update fEngineControl and fGraphManager
57
58
59
        JackAudioDriver::SetBufferSize(buffer_size);  // Generic change, never fails
        // ALSA specific
        UpdateLatencies();
sletz's avatar
sletz committed
60
    } else {
61
        // Restore old values
sletz's avatar
sletz committed
62
        alsa_driver_reset_parameters((alsa_driver_t *)fDriver, fEngineControl->fBufferSize,
sletz's avatar
sletz committed
63
64
65
66
                                     ((alsa_driver_t *)fDriver)->user_nperiods,
                                     ((alsa_driver_t *)fDriver)->frame_rate);
    }

sletz's avatar
sletz committed
67
    return res;
sletz's avatar
sletz committed
68
69
}

70
71
72
void JackAlsaDriver::UpdateLatencies()
{
    jack_latency_range_t range;
73
    alsa_driver_t* alsa_driver = (alsa_driver_t*)fDriver;
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

    for (int i = 0; i < fCaptureChannels; i++) {
        range.min = range.max = alsa_driver->frames_per_cycle + alsa_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 = (alsa_driver->frames_per_cycle * (alsa_driver->user_nperiods - 1)) +
                         ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize) + alsa_driver->playback_frame_latency;
        fGraphManager->GetPort(fPlaybackPortList[i])->SetLatencyRange(JackPlaybackLatency, &range);
        // Monitor port
        if (fWithMonitorPorts) {
            range.min = range.max = alsa_driver->frames_per_cycle;
            fGraphManager->GetPort(fMonitorPortList[i])->SetLatencyRange(JackCaptureLatency, &range);
        }
    }
}

sletz's avatar
sletz committed
93
94
95
int JackAlsaDriver::Attach()
{
    JackPort* port;
Stephane Letz's avatar
Stephane Letz committed
96
    jack_port_id_t port_index;
sletz's avatar
sletz committed
97
    unsigned long port_flags = (unsigned long)CaptureDriverFlags;
sletz's avatar
sletz committed
98
99
    char name[REAL_JACK_PORT_NAME_SIZE];
    char alias[REAL_JACK_PORT_NAME_SIZE];
sletz's avatar
sletz committed
100

sletz's avatar
sletz committed
101
102
    assert(fCaptureChannels < DRIVER_PORT_NUM);
    assert(fPlaybackChannels < DRIVER_PORT_NUM);
sletz's avatar
sletz committed
103

sletz's avatar
sletz committed
104
    alsa_driver_t* alsa_driver = (alsa_driver_t*)fDriver;
sletz's avatar
sletz committed
105
106
107
108
109
110
111

    if (alsa_driver->has_hw_monitoring)
        port_flags |= JackPortCanMonitor;

    // ALSA driver may have changed the values
    JackAudioDriver::SetBufferSize(alsa_driver->frames_per_cycle);
    JackAudioDriver::SetSampleRate(alsa_driver->frame_rate);
sletz's avatar
sletz committed
112

sletz's avatar
sletz committed
113
    jack_log("JackAlsaDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
sletz's avatar
sletz committed
114

sletz's avatar
sletz committed
115
    for (int i = 0; i < fCaptureChannels; i++) {
sletz's avatar
sletz committed
116
117
        snprintf(alias, sizeof(alias), "%s:%s:out%d", fAliasName, fCaptureDriverName, i + 1);
        snprintf(name, sizeof(name), "%s:capture_%d", fClientControl.fName, i + 1);
Stephane Letz's avatar
Stephane Letz committed
118
        if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize, &port_index) < 0) {
119
            jack_error("driver: cannot register port for %s", name);
sletz's avatar
sletz committed
120
            return -1;
sletz's avatar
sletz committed
121
        }
sletz's avatar
sletz committed
122
        port = fGraphManager->GetPort(port_index);
sletz's avatar
sletz committed
123
        port->SetAlias(alias);
sletz's avatar
sletz committed
124
        fCapturePortList[i] = port_index;
sletz's avatar
sletz committed
125
        jack_log("JackAlsaDriver::Attach fCapturePortList[i] %ld ", port_index);
sletz's avatar
sletz committed
126
127
    }

128
    port_flags = (unsigned long)PlaybackDriverFlags;
sletz's avatar
sletz committed
129
130

    for (int i = 0; i < fPlaybackChannels; i++) {
sletz's avatar
sletz committed
131
132
        snprintf(alias, sizeof(alias), "%s:%s:in%d", fAliasName, fPlaybackDriverName, i + 1);
        snprintf(name, sizeof(name), "%s:playback_%d", fClientControl.fName, i + 1);
133
        if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize, &port_index) < 0) {
134
            jack_error("driver: cannot register port for %s", name);
sletz's avatar
sletz committed
135
136
137
            return -1;
        }
        port = fGraphManager->GetPort(port_index);
sletz's avatar
sletz committed
138
        port->SetAlias(alias);
sletz's avatar
sletz committed
139
        fPlaybackPortList[i] = port_index;
sletz's avatar
sletz committed
140
        jack_log("JackAlsaDriver::Attach fPlaybackPortList[i] %ld ", port_index);
sletz's avatar
sletz committed
141
142
143

        // Monitor ports
        if (fWithMonitorPorts) {
sletz's avatar
sletz committed
144
            jack_log("Create monitor port");
sletz's avatar
sletz committed
145
            snprintf(name, sizeof(name), "%s:monitor_%d", fClientControl.fName, i + 1);
146
147
            if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, MonitorDriverFlags, fEngineControl->fBufferSize, &port_index) < 0) {
                jack_error("ALSA: cannot register monitor port for %s", name);
sletz's avatar
sletz committed
148
149
150
151
152
            } else {
                fMonitorPortList[i] = port_index;
            }
        }
    }
sletz's avatar
sletz committed
153

154
155
    UpdateLatencies();

156
157
158
159
160
161
    if (alsa_driver->midi) {
        int err = (alsa_driver->midi->attach)(alsa_driver->midi);
        if (err)
            jack_error ("ALSA: cannot attach MIDI: %d", err);
    }

sletz's avatar
sletz committed
162
163
    return 0;
}
sletz's avatar
sletz committed
164

165
166
167
168
169
170
int JackAlsaDriver::Detach()
{
    alsa_driver_t* alsa_driver = (alsa_driver_t*)fDriver;
    if (alsa_driver->midi)
        (alsa_driver->midi->detach)(alsa_driver->midi);

171
    return JackAudioDriver::Detach();
172
173
}

174
extern "C" char* get_control_device_name(const char * device_name)
sletz's avatar
sletz committed
175
176
{
    char * ctl_name;
177
    const char * comma;
sletz's avatar
sletz committed
178

179
180
181
    /* the user wants a hw or plughw device, the ctl name
     * should be hw:x where x is the card identification.
     * We skip the subdevice suffix that starts with comma */
sletz's avatar
sletz committed
182

183
184
185
    if (strncasecmp(device_name, "plughw:", 7) == 0) {
        /* skip the "plug" prefix" */
        device_name += 4;
sletz's avatar
sletz committed
186
187
    }

188
189
190
191
192
193
194
195
196
197
198
    comma = strchr(device_name, ',');
    if (comma == NULL) {
        ctl_name = strdup(device_name);
        if (ctl_name == NULL) {
            jack_error("strdup(\"%s\") failed.", device_name);
        }
    } else {
        ctl_name = strndup(device_name, comma - device_name);
        if (ctl_name == NULL) {
            jack_error("strndup(\"%s\", %u) failed.", device_name, (unsigned int)(comma - device_name));
        }
sletz's avatar
sletz committed
199
200
201
202
203
    }

    return ctl_name;
}

204
static int card_to_num(const char* device)
205
{
nedko's avatar
nedko committed
206
207
208
209
210
211
212
213
214
215
216
217
218
    int err;
    char* ctl_name;
    snd_ctl_card_info_t *card_info;
    snd_ctl_t* ctl_handle;
    int i = -1;

    snd_ctl_card_info_alloca (&card_info);

    ctl_name = get_control_device_name(device);
    if (ctl_name == NULL) {
        jack_error("get_control_device_name() failed.");
        goto fail;
    }
219

nedko's avatar
nedko committed
220
221
222
223
224
    if ((err = snd_ctl_open (&ctl_handle, ctl_name, 0)) < 0) {
        jack_error ("control open \"%s\" (%s)", ctl_name,
                    snd_strerror(err));
        goto free;
    }
225

nedko's avatar
nedko committed
226
227
228
229
    if ((err = snd_ctl_card_info(ctl_handle, card_info)) < 0) {
        jack_error ("control hardware info \"%s\" (%s)",
                    device, snd_strerror (err));
        goto close;
230
231
    }

nedko's avatar
nedko committed
232
233
234
235
236
237
238
239
240
    i = snd_ctl_card_info_get_card(card_info);

close:
    snd_ctl_close(ctl_handle);

free:
    free(ctl_name);

fail:
241
242
243
    return i;
}

sletz's avatar
sletz committed
244
int JackAlsaDriver::Open(jack_nframes_t nframes,
sletz's avatar
sletz committed
245
                         jack_nframes_t user_nperiods,
sletz's avatar
sletz committed
246
                         jack_nframes_t samplerate,
sletz's avatar
sletz committed
247
248
                         bool hw_monitoring,
                         bool hw_metering,
sletz's avatar
sletz committed
249
250
                         bool capturing,
                         bool playing,
sletz's avatar
sletz committed
251
252
253
                         DitherAlgorithm dither,
                         bool soft_mode,
                         bool monitor,
sletz's avatar
sletz committed
254
255
                         int inchannels,
                         int outchannels,
sletz's avatar
sletz committed
256
                         bool shorts_first,
sletz's avatar
sletz committed
257
                         const char* capture_driver_name,
sletz's avatar
sletz committed
258
259
260
261
                         const char* playback_driver_name,
                         jack_nframes_t capture_latency,
                         jack_nframes_t playback_latency,
                         const char* midi_driver_name)
sletz's avatar
sletz committed
262
263
{
    // Generic JackAudioDriver Open
sletz's avatar
sletz committed
264
265
266
    if (JackAudioDriver::Open(nframes, samplerate, capturing, playing,
                              inchannels, outchannels, monitor, capture_driver_name, playback_driver_name,
                              capture_latency, playback_latency) != 0) {
sletz's avatar
sletz committed
267
268
        return -1;
    }
sletz's avatar
sletz committed
269

270
271
    alsa_midi_t *midi = 0;
    if (strcmp(midi_driver_name, "seq") == 0)
sletz's avatar
sletz committed
272
        midi = alsa_seqmidi_new((jack_client_t*)this, 0);
273
    else if (strcmp(midi_driver_name, "raw") == 0)
sletz's avatar
sletz committed
274
        midi = alsa_rawmidi_new((jack_client_t*)this);
sletz's avatar
sletz committed
275

sletz's avatar
sletz committed
276
    if (JackServerGlobals::on_device_acquire != NULL) {
277
278
279
280
        int capture_card = card_to_num(capture_driver_name);
        int playback_card = card_to_num(playback_driver_name);
        char audio_name[32];

281
282
283
284
285
286
        if (capture_card >= 0) {
            snprintf(audio_name, sizeof(audio_name), "Audio%d", capture_card);
            if (!JackServerGlobals::on_device_acquire(audio_name)) {
                jack_error("Audio device %s cannot be acquired...", capture_driver_name);
                return -1;
            }
287
288
        }

289
        if (playback_card >= 0 && playback_card != capture_card) {
sletz's avatar
sletz committed
290
            snprintf(audio_name, sizeof(audio_name), "Audio%d", playback_card);
291
            if (!JackServerGlobals::on_device_acquire(audio_name)) {
sletz's avatar
Typo.    
sletz committed
292
                jack_error("Audio device %s cannot be acquired...", playback_driver_name);
293
294
295
296
                if (capture_card >= 0) {
                    snprintf(audio_name, sizeof(audio_name), "Audio%d", capture_card);
                    JackServerGlobals::on_device_release(audio_name);
                }
sletz's avatar
sletz committed
297
                return -1;
298
299
            }
        }
300
301
    }

sletz's avatar
sletz committed
302
    fDriver = alsa_driver_new ((char*)"alsa_pcm", (char*)playback_driver_name, (char*)capture_driver_name,
sletz's avatar
sletz committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
                               NULL,
                               nframes,
                               user_nperiods,
                               samplerate,
                               hw_monitoring,
                               hw_metering,
                               capturing,
                               playing,
                               dither,
                               soft_mode,
                               monitor,
                               inchannels,
                               outchannels,
                               shorts_first,
                               capture_latency,
318
                               playback_latency,
sletz's avatar
sletz committed
319
                               midi);
sletz's avatar
sletz committed
320
321
322
323
324
325
    if (fDriver) {
        // ALSA driver may have changed the in/out values
        fCaptureChannels = ((alsa_driver_t *)fDriver)->capture_nchannels;
        fPlaybackChannels = ((alsa_driver_t *)fDriver)->playback_nchannels;
        return 0;
    } else {
326
        JackAudioDriver::Close();
sletz's avatar
sletz committed
327
328
329
        return -1;
    }
}
sletz's avatar
sletz committed
330

sletz's avatar
sletz committed
331
332
int JackAlsaDriver::Close()
{
333
334
335
    // Generic audio driver close
    int res = JackAudioDriver::Close();

sletz's avatar
sletz committed
336
    alsa_driver_delete((alsa_driver_t*)fDriver);
337
338
339
340
341
342

    if (JackServerGlobals::on_device_release != NULL)
    {
        char audio_name[32];
        int capture_card = card_to_num(fCaptureDriverName);
        if (capture_card >= 0) {
sletz's avatar
sletz committed
343
            snprintf(audio_name, sizeof(audio_name), "Audio%d", capture_card);
344
345
346
347
348
            JackServerGlobals::on_device_release(audio_name);
        }

        int playback_card = card_to_num(fPlaybackDriverName);
        if (playback_card >= 0 && playback_card != capture_card) {
sletz's avatar
sletz committed
349
            snprintf(audio_name, sizeof(audio_name), "Audio%d", playback_card);
350
351
352
353
            JackServerGlobals::on_device_release(audio_name);
        }
    }

354
    return res;
sletz's avatar
sletz committed
355
356
}

sletz's avatar
sletz committed
357
int JackAlsaDriver::Start()
sletz's avatar
sletz committed
358
{
359
360
361
362
363
364
365
366
    int res = JackAudioDriver::Start();
    if (res >= 0) {
        res = alsa_driver_start((alsa_driver_t *)fDriver);
        if (res < 0) {
            JackAudioDriver::Stop();
        }
    }
    return res;
sletz's avatar
sletz committed
367
}
sletz's avatar
sletz committed
368

sletz's avatar
sletz committed
369
370
int JackAlsaDriver::Stop()
{
371
372
373
374
375
    int res = alsa_driver_stop((alsa_driver_t *)fDriver);
    if (JackAudioDriver::Stop() < 0) {
        res = -1;
    }
    return res;
sletz's avatar
sletz committed
376
377
}

sletz's avatar
sletz committed
378
int JackAlsaDriver::Read()
sletz's avatar
sletz committed
379
{
sletz's avatar
sletz committed
380
    /* Taken from alsa_driver_run_cycle */
sletz's avatar
sletz committed
381
    int wait_status;
sletz's avatar
sletz committed
382
    jack_nframes_t nframes;
sletz's avatar
sletz committed
383
    fDelayedUsecs = 0.f;
sletz's avatar
sletz committed
384

385
386
retry:

387
    nframes = alsa_driver_wait((alsa_driver_t *)fDriver, -1, &wait_status, &fDelayedUsecs);
388

sletz's avatar
sletz committed
389
390
    if (wait_status < 0)
        return -1;		/* driver failed */
sletz's avatar
sletz committed
391

sletz's avatar
sletz committed
392
393
    if (nframes == 0) {
        /* we detected an xrun and restarted: notify
394
         * clients about the delay.
sletz's avatar
sletz committed
395
         */
396
        jack_log("ALSA XRun wait_status = %d", wait_status);
sletz's avatar
sletz committed
397
        NotifyXRun(fBeginDateUst, fDelayedUsecs);
398
        goto retry; /* recoverable error*/
sletz's avatar
sletz committed
399
400
    }

sletz's avatar
sletz committed
401
    if (nframes != fEngineControl->fBufferSize)
sletz's avatar
sletz committed
402
        jack_log("JackAlsaDriver::Read warning fBufferSize = %ld nframes = %ld", fEngineControl->fBufferSize, nframes);
403

404
    // Has to be done before read
405
    JackDriver::CycleIncTime();
sletz's avatar
sletz committed
406
407
408
409
410
411

    return alsa_driver_read((alsa_driver_t *)fDriver, fEngineControl->fBufferSize);
}

int JackAlsaDriver::Write()
{
412
    return alsa_driver_write((alsa_driver_t *)fDriver, fEngineControl->fBufferSize);
sletz's avatar
sletz committed
413
414
}

sletz's avatar
sletz committed
415
void JackAlsaDriver::ReadInputAux(jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nread)
416
{
sletz's avatar
sletz committed
417
    for (int chn = 0; chn < fCaptureChannels; chn++) {
418
        if (fGraphManager->GetConnectionsNum(fCapturePortList[chn]) > 0) {
sletz's avatar
sletz committed
419
            jack_default_audio_sample_t* buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fCapturePortList[chn], orig_nframes);
420
421
422
423
424
425
426
            alsa_driver_read_from_channel((alsa_driver_t *)fDriver, chn, buf + nread, contiguous);
        }
    }
}

void JackAlsaDriver::MonitorInputAux()
{
sletz's avatar
sletz committed
427
    for (int chn = 0; chn < fCaptureChannels; chn++) {
428
429
        JackPort* port = fGraphManager->GetPort(fCapturePortList[chn]);
        if (port->MonitoringInput()) {
sletz's avatar
sletz committed
430
            ((alsa_driver_t *)fDriver)->input_monitor_mask |= (1 << chn);
431
432
433
434
435
436
        }
    }
}

void JackAlsaDriver::ClearOutputAux()
{
sletz's avatar
sletz committed
437
    for (int chn = 0; chn < fPlaybackChannels; chn++) {
438
439
        jack_default_audio_sample_t* buf =
            (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fPlaybackPortList[chn], fEngineControl->fBufferSize);
sletz's avatar
sletz committed
440
        memset(buf, 0, sizeof (jack_default_audio_sample_t) * fEngineControl->fBufferSize);
441
442
443
444
445
446
447
448
    }
}

void JackAlsaDriver::SetTimetAux(jack_time_t time)
{
    fBeginDateUst = time;
}

sletz's avatar
sletz committed
449
void JackAlsaDriver::WriteOutputAux(jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nwritten)
450
{
sletz's avatar
sletz committed
451
452
453
454
455
456
457
458
459
    for (int chn = 0; chn < fPlaybackChannels; chn++) {
        // Output ports
        if (fGraphManager->GetConnectionsNum(fPlaybackPortList[chn]) > 0) {
            jack_default_audio_sample_t* buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fPlaybackPortList[chn], orig_nframes);
            alsa_driver_write_to_channel(((alsa_driver_t *)fDriver), chn, buf + nwritten, contiguous);
            // Monitor ports
            if (fWithMonitorPorts && fGraphManager->GetConnectionsNum(fMonitorPortList[chn]) > 0) {
                jack_default_audio_sample_t* monbuf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fMonitorPortList[chn], orig_nframes);
                memcpy(monbuf + nwritten, buf + nwritten, contiguous * sizeof(jack_default_audio_sample_t));
460
            }
sletz's avatar
sletz committed
461
        }
462
463
464
    }
}

465
466
int JackAlsaDriver::is_realtime() const
{
sletz's avatar
sletz committed
467
    return fEngineControl->fRealTime;
468
469
470
471
}

int JackAlsaDriver::create_thread(pthread_t *thread, int priority, int realtime, void *(*start_routine)(void*), void *arg)
{
sletz's avatar
sletz committed
472
    return JackPosixThread::StartImp(thread, priority, realtime, start_routine, arg);
473
474
}

475
jack_port_id_t JackAlsaDriver::port_register(const char *port_name, const char *port_type, unsigned long flags, unsigned long buffer_size)
476
{
477
    jack_port_id_t port_index;
478
    int res = fEngine->PortRegister(fClientControl.fRefNum, port_name, port_type, flags, buffer_size, &port_index);
479
    return (res == 0) ? port_index : 0;
480
481
}

482
int JackAlsaDriver::port_unregister(jack_port_id_t port_index)
483
{
484
    return fEngine->PortUnRegister(fClientControl.fRefNum, port_index);
485
486
487
488
}

void* JackAlsaDriver::port_get_buffer(int port, jack_nframes_t nframes)
{
sletz's avatar
sletz committed
489
    return fGraphManager->GetBuffer(port, nframes);
490
491
}

492
493
int  JackAlsaDriver::port_set_alias(int port, const char* name)
{
sletz's avatar
sletz committed
494
    return fGraphManager->GetPort(port)->SetAlias(name);
495
496
}

497
498
jack_nframes_t JackAlsaDriver::get_sample_rate() const
{
sletz's avatar
sletz committed
499
    return fEngineControl->fSampleRate;
500
501
502
503
}

jack_nframes_t JackAlsaDriver::frame_time() const
{
sletz's avatar
sletz committed
504
505
    JackTimer timer;
    fEngineControl->ReadFrameTime(&timer);
sletz's avatar
sletz committed
506
    return timer.Time2Frames(GetMicroSeconds(), fEngineControl->fBufferSize);
507
508
509
510
511
}

jack_nframes_t JackAlsaDriver::last_frame_time() const
{
    JackTimer timer;
sletz's avatar
sletz committed
512
    fEngineControl->ReadFrameTime(&timer);
sletz's avatar
sletz committed
513
    return timer.CurFrame();
514
515
}

sletz's avatar
sletz committed
516
517
518
519
520
521
522
523
} // end of namespace


#ifdef __cplusplus
extern "C"
{
#endif

nedko's avatar
nedko committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
static
void
fill_device(
    jack_driver_param_constraint_desc_t ** constraint_ptr_ptr,
    uint32_t * array_size_ptr,
    const char * device_id,
    const char * device_description)
{
    jack_driver_param_value_enum_t * possible_value_ptr;

    //jack_info("%6s - %s", device_id, device_description);

    if (*constraint_ptr_ptr == NULL)
    {
        *constraint_ptr_ptr = (jack_driver_param_constraint_desc_t *)calloc(1, sizeof(jack_driver_param_value_enum_t));
        *array_size_ptr = 0;
    }

    if ((*constraint_ptr_ptr)->constraint.enumeration.count == *array_size_ptr)
    {
        *array_size_ptr += 10;
        (*constraint_ptr_ptr)->constraint.enumeration.possible_values_array =
            (jack_driver_param_value_enum_t *)realloc(
                (*constraint_ptr_ptr)->constraint.enumeration.possible_values_array,
                sizeof(jack_driver_param_value_enum_t) * *array_size_ptr);
    }

    possible_value_ptr = (*constraint_ptr_ptr)->constraint.enumeration.possible_values_array + (*constraint_ptr_ptr)->constraint.enumeration.count;
    (*constraint_ptr_ptr)->constraint.enumeration.count++;
    strcpy(possible_value_ptr->value.str, device_id);
    strcpy(possible_value_ptr->short_desc, device_description);
}

static
jack_driver_param_constraint_desc_t *
enum_alsa_devices()
{
    snd_ctl_t * handle;
    snd_ctl_card_info_t * info;
    snd_pcm_info_t * pcminfo_capture;
    snd_pcm_info_t * pcminfo_playback;
    int card_no = -1;
    char card_id[JACK_DRIVER_PARAM_STRING_MAX + 1];
    char device_id[JACK_DRIVER_PARAM_STRING_MAX + 1];
    char description[64];
    int device_no;
    bool has_capture;
    bool has_playback;
    jack_driver_param_constraint_desc_t * constraint_ptr;
573
    uint32_t array_size = 0;
nedko's avatar
nedko committed
574
575
576
577
578
579
580
581
582

    snd_ctl_card_info_alloca(&info);
    snd_pcm_info_alloca(&pcminfo_capture);
    snd_pcm_info_alloca(&pcminfo_playback);

    constraint_ptr = NULL;

    while(snd_card_next(&card_no) >= 0 && card_no >= 0)
    {
sletz's avatar
sletz committed
583
        snprintf(card_id, sizeof(card_id), "hw:%d", card_no);
nedko's avatar
nedko committed
584
585
586
587

        if (snd_ctl_open(&handle, card_id, 0) >= 0 &&
            snd_ctl_card_info(handle, info) >= 0)
        {
588
            snprintf(card_id, sizeof(card_id), "hw:%s", snd_ctl_card_info_get_id(info));
nedko's avatar
nedko committed
589
590
591
592
593
594
            fill_device(&constraint_ptr, &array_size, card_id, snd_ctl_card_info_get_name(info));

            device_no = -1;

            while (snd_ctl_pcm_next_device(handle, &device_no) >= 0 && device_no != -1)
            {
sletz's avatar
sletz committed
595
                snprintf(device_id, sizeof(device_id), "%s,%d", card_id, device_no);
nedko's avatar
nedko committed
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633

                snd_pcm_info_set_device(pcminfo_capture, device_no);
                snd_pcm_info_set_subdevice(pcminfo_capture, 0);
                snd_pcm_info_set_stream(pcminfo_capture, SND_PCM_STREAM_CAPTURE);
                has_capture = snd_ctl_pcm_info(handle, pcminfo_capture) >= 0;

                snd_pcm_info_set_device(pcminfo_playback, device_no);
                snd_pcm_info_set_subdevice(pcminfo_playback, 0);
                snd_pcm_info_set_stream(pcminfo_playback, SND_PCM_STREAM_PLAYBACK);
                has_playback = snd_ctl_pcm_info(handle, pcminfo_playback) >= 0;

                if (has_capture && has_playback)
                {
                    snprintf(description, sizeof(description),"%s (duplex)", snd_pcm_info_get_name(pcminfo_capture));
                }
                else if (has_capture)
                {
                    snprintf(description, sizeof(description),"%s (capture)", snd_pcm_info_get_name(pcminfo_capture));
                }
                else if (has_playback)
                {
                    snprintf(description, sizeof(description),"%s (playback)", snd_pcm_info_get_name(pcminfo_playback));
                }
                else
                {
                    continue;
                }

                fill_device(&constraint_ptr, &array_size, device_id, description);
            }

            snd_ctl_close(handle);
        }
    }

    return constraint_ptr;
}

634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
static
jack_driver_param_constraint_desc_t *
get_midi_driver_constraint()
{
    jack_driver_param_constraint_desc_t * constraint_ptr;
    jack_driver_param_value_enum_t * possible_value_ptr;

    //jack_info("%6s - %s", device_id, device_description);

    constraint_ptr = (jack_driver_param_constraint_desc_t *)calloc(1, sizeof(jack_driver_param_value_enum_t));
    constraint_ptr->flags = JACK_CONSTRAINT_FLAG_STRICT | JACK_CONSTRAINT_FLAG_FAKE_VALUE;

    constraint_ptr->constraint.enumeration.possible_values_array = (jack_driver_param_value_enum_t *)malloc(3 * sizeof(jack_driver_param_value_enum_t));
    constraint_ptr->constraint.enumeration.count = 3;

    possible_value_ptr = constraint_ptr->constraint.enumeration.possible_values_array;

    strcpy(possible_value_ptr->value.str, "none");
    strcpy(possible_value_ptr->short_desc, "no MIDI driver");

    possible_value_ptr++;

    strcpy(possible_value_ptr->value.str, "seq");
    strcpy(possible_value_ptr->short_desc, "ALSA Sequencer driver");

    possible_value_ptr++;

    strcpy(possible_value_ptr->value.str, "raw");
    strcpy(possible_value_ptr->short_desc, "ALSA RawMIDI driver");

    return constraint_ptr;
}

static
jack_driver_param_constraint_desc_t *
get_dither_constraint()
{
    jack_driver_param_constraint_desc_t * constraint_ptr;
    jack_driver_param_value_enum_t * possible_value_ptr;

    //jack_info("%6s - %s", device_id, device_description);

    constraint_ptr = (jack_driver_param_constraint_desc_t *)calloc(1, sizeof(jack_driver_param_value_enum_t));
    constraint_ptr->flags = JACK_CONSTRAINT_FLAG_STRICT | JACK_CONSTRAINT_FLAG_FAKE_VALUE;

    constraint_ptr->constraint.enumeration.possible_values_array = (jack_driver_param_value_enum_t *)malloc(4 * sizeof(jack_driver_param_value_enum_t));
    constraint_ptr->constraint.enumeration.count = 4;

    possible_value_ptr = constraint_ptr->constraint.enumeration.possible_values_array;

    possible_value_ptr->value.c = 'n';
    strcpy(possible_value_ptr->short_desc, "none");

    possible_value_ptr++;

    possible_value_ptr->value.c = 'r';
    strcpy(possible_value_ptr->short_desc, "rectangular");

    possible_value_ptr++;

    possible_value_ptr->value.c = 's';
    strcpy(possible_value_ptr->short_desc, "shaped");

    possible_value_ptr++;

    possible_value_ptr->value.c = 't';
    strcpy(possible_value_ptr->short_desc, "triangular");

    return constraint_ptr;
}

705
static int
706
dither_opt (char c, DitherAlgorithm* dither)
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
{
    switch (c) {
        case '-':
        case 'n':
            *dither = None;
            break;

        case 'r':
            *dither = Rectangular;
            break;

        case 's':
            *dither = Shaped;
            break;

        case 't':
            *dither = Triangular;
            break;

        default:
            fprintf (stderr, "ALSA driver: illegal dithering mode %c\n", c);
            return -1;
sletz's avatar
sletz committed
729
    }
730
731
    return 0;
}
sletz's avatar
sletz committed
732

733
SERVER_EXPORT const jack_driver_desc_t* driver_get_descriptor ()
734
735
{
    jack_driver_desc_t * desc;
736
737
738
    jack_driver_desc_filler_t filler;
    jack_driver_param_value_t value;

739
    desc = jack_driver_descriptor_construct("alsa", JackDriverMaster, "Linux ALSA API based audio backend", &filler);
740

741
742
743
    strcpy(value.str, "hw:0");
    jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, enum_alsa_devices(), "ALSA device name", NULL);

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
777
778
779
780
781
782
783
784
785
786
787
    strcpy(value.str, "none");
    jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Provide capture ports.  Optionally set device", NULL);
    jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Provide playback ports.  Optionally set device", NULL);

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

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

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

    value.i = 0;
    jack_driver_descriptor_add_parameter(desc, &filler, "hwmon", 'H', JackDriverParamBool, &value, NULL, "Hardware monitoring, if available", NULL);

    value.i = 0;
    jack_driver_descriptor_add_parameter(desc, &filler, "hwmeter", 'M', JackDriverParamBool, &value, NULL, "Hardware metering, if available", NULL);

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

    value.i = 0;
    jack_driver_descriptor_add_parameter(desc, &filler, "softmode", 's', JackDriverParamBool, &value, NULL, "Soft-mode, no xrun handling", NULL);

    value.i = 0;
    jack_driver_descriptor_add_parameter(desc, &filler, "monitor", 'm', JackDriverParamBool, &value, NULL, "Provide monitor ports for the output", NULL);

    value.c = 'n';
    jack_driver_descriptor_add_parameter(
        desc,
        &filler,
        "dither",
        'z',
        JackDriverParamChar,
        &value,
        get_dither_constraint(),
        "Dithering mode",
        "Dithering mode:\n"
        "  n - none\n"
        "  r - rectangular\n"
        "  s - shaped\n"
        "  t - triangular");

788
789
790
    value.ui = 0;
    jack_driver_descriptor_add_parameter(desc, &filler, "inchannels", 'i', JackDriverParamUInt, &value, NULL, "Number of capture channels (defaults to hardware max)", NULL);
    jack_driver_descriptor_add_parameter(desc, &filler, "outchannels", 'o', JackDriverParamUInt, &value, NULL, "Number of playback channels (defaults to hardware max)", NULL);
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813

    value.i = FALSE;
    jack_driver_descriptor_add_parameter(desc, &filler, "shorts", 'S', JackDriverParamBool, &value, NULL, "Try 16-bit samples before 32-bit", 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);

    strcpy(value.str, "none");
    jack_driver_descriptor_add_parameter(
        desc,
        &filler,
        "midi-driver",
        'X',
        JackDriverParamString,
        &value,
        get_midi_driver_constraint(),
        "ALSA device name",
        "ALSA MIDI driver:\n"
        " none - no MIDI driver\n"
        " seq - ALSA Sequencer driver\n"
        " raw - ALSA RawMIDI driver\n");

814
815
    return desc;
}
sletz's avatar
sletz committed
816

817
818
static Jack::JackAlsaDriver* g_alsa_driver;

819
SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
820
821
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
{
    jack_nframes_t srate = 48000;
    jack_nframes_t frames_per_interrupt = 1024;
    unsigned long user_nperiods = 2;
    const char *playback_pcm_name = "hw:0";
    const char *capture_pcm_name = "hw:0";
    int hw_monitoring = FALSE;
    int hw_metering = FALSE;
    int capture = FALSE;
    int playback = FALSE;
    int soft_mode = FALSE;
    int monitor = FALSE;
    DitherAlgorithm dither = None;
    int user_capture_nchnls = 0;
    int user_playback_nchnls = 0;
    int shorts_first = FALSE;
    jack_nframes_t systemic_input_latency = 0;
    jack_nframes_t systemic_output_latency = 0;
    const JSList * node;
    const jack_driver_param_t * param;
    const char *midi_driver = "none";

    for (node = params; node; node = jack_slist_next (node)) {
        param = (const jack_driver_param_t *) node->data;

        switch (param->character) {

            case 'C':
                capture = TRUE;
                if (strcmp (param->value.str, "none") != 0) {
                    capture_pcm_name = strdup (param->value.str);
                    jack_log("capture device %s", capture_pcm_name);
                }
                break;
sletz's avatar
sletz committed
854

855
856
857
            case 'P':
                playback = TRUE;
                if (strcmp (param->value.str, "none") != 0) {
sletz's avatar
sletz committed
858
                    playback_pcm_name = strdup (param->value.str);
sletz's avatar
sletz committed
859
                    jack_log("playback device %s", playback_pcm_name);
860
861
                }
                break;
sletz's avatar
sletz committed
862

863
864
865
866
            case 'D':
                playback = TRUE;
                capture = TRUE;
                break;
sletz's avatar
sletz committed
867

868
            case 'd':
869
870
871
872
873
874
                if (strcmp (param->value.str, "none") != 0) {
                    playback_pcm_name = strdup (param->value.str);
                    capture_pcm_name = strdup (param->value.str);
                    jack_log("playback device %s", playback_pcm_name);
                    jack_log("capture device %s", capture_pcm_name);
                }
875
                break;
sletz's avatar
sletz committed
876

877
878
879
            case 'H':
                hw_monitoring = param->value.i;
                break;
sletz's avatar
sletz committed
880

881
882
883
            case 'm':
                monitor = param->value.i;
                break;
sletz's avatar
sletz committed
884

885
886
887
            case 'M':
                hw_metering = param->value.i;
                break;
sletz's avatar
sletz committed
888

889
890
891
892
            case 'r':
                srate = param->value.ui;
                jack_log("apparent rate = %d", srate);
                break;
sletz's avatar
sletz committed
893

894
895
896
897
            case 'p':
                frames_per_interrupt = param->value.ui;
                jack_log("frames per period = %d", frames_per_interrupt);
                break;
sletz's avatar
sletz committed
898

899
900
            case 'n':
                user_nperiods = param->value.ui;
901
                if (user_nperiods < 2) {    /* enforce minimum value */
902
                    user_nperiods = 2;
903
                }
904
                break;
sletz's avatar
sletz committed
905

906
907
908
            case 's':
                soft_mode = param->value.i;
                break;
sletz's avatar
sletz committed
909

910
911
912
913
914
            case 'z':
                if (dither_opt (param->value.c, &dither)) {
                    return NULL;
                }
                break;
sletz's avatar
sletz committed
915

916
917
918
            case 'i':
                user_capture_nchnls = param->value.ui;
                break;
sletz's avatar
sletz committed
919

920
921
922
            case 'o':
                user_playback_nchnls = param->value.ui;
                break;
sletz's avatar
sletz committed
923

924
925
926
            case 'S':
                shorts_first = param->value.i;
                break;
sletz's avatar
sletz committed
927

928
929
930
            case 'I':
                systemic_input_latency = param->value.ui;
                break;
sletz's avatar
sletz committed
931

932
933
934
            case 'O':
                systemic_output_latency = param->value.ui;
                break;
sletz's avatar
sletz committed
935

936
937
938
            case 'X':
                midi_driver = strdup(param->value.str);
                break;
sletz's avatar
sletz committed
939
940
941
        }
    }

942
943
944
945
946
947
    /* duplex is the default */
    if (!capture && !playback) {
        capture = TRUE;
        playback = TRUE;
    }

948
949
    g_alsa_driver = new Jack::JackAlsaDriver("system", "alsa_pcm", engine, table);
    Jack::JackDriverClientInterface* threaded_driver = new Jack::JackThreadedDriver(g_alsa_driver);
950
    // Special open for ALSA driver...
sletz's avatar
sletz committed
951
    if (g_alsa_driver->Open(frames_per_interrupt, user_nperiods, srate, hw_monitoring, hw_metering, capture, playback, dither, soft_mode, monitor,
952
953
954
955
956
957
958
959
960
                          user_capture_nchnls, user_playback_nchnls, shorts_first, capture_pcm_name, playback_pcm_name,
                          systemic_input_latency, systemic_output_latency, midi_driver) == 0) {
        return threaded_driver;
    } else {
        delete threaded_driver; // Delete the decorated driver
        return NULL;
    }
}

961
962
// Code to be used in alsa_driver.c

sletz's avatar
sletz committed
963
void ReadInput(jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nread)
964
{
sletz's avatar
sletz committed
965
    g_alsa_driver->ReadInputAux(orig_nframes, contiguous, nread);
966
967
968
969
970
971
972
973
974
}
void MonitorInput()
{
    g_alsa_driver->MonitorInputAux();
}
void ClearOutput()
{
    g_alsa_driver->ClearOutputAux();
}
sletz's avatar
sletz committed
975
void WriteOutput(jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nwritten)
976
{
sletz's avatar
sletz committed
977
    g_alsa_driver->WriteOutputAux(orig_nframes, contiguous, nwritten);
978
}
sletz's avatar
sletz committed
979
void SetTime(jack_time_t time)
980
981
982
983
{
    g_alsa_driver->SetTimetAux(time);
}

984
985
986
int Restart()
{
    int res;
987
    if ((res = g_alsa_driver->Stop()) == 0) {
988
        res = g_alsa_driver->Start();
989
    }
990
991
992
    return res;
}

sletz's avatar
sletz committed
993
994
995
996
997
#ifdef __cplusplus
}
#endif