summaryrefslogtreecommitdiffhomepage
path: root/alsa.cpp
blob: d9d7cf97452163e44458765394f25b71c5e3932c (plain)
1
2
3
4
5
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#include <libreichwein/file.h>

#include <alsa/asoundlib.h>

#include <cstdint>
#include <cmath>
#include <iostream>
#include <limits>
#include <exception>
#include <stdexcept>

#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>

using namespace std::string_literals;

//static const int CLICK_NOTE = 37;
//static const int CLICK_CHANNEL = 4;

static const char *device = "default";    // playback device
const snd_pcm_sframes_t nframes = 1024;   // ~1/44th sec buffer size
int16_t buffer[nframes];
const unsigned int f_sample = 44100;
const double pi = std::acos(-1);

class ClickStream
{
public:
  ClickStream(): m_phase(1000000)
  {
    std::string data_s = Reichwein::File::getFile("media/click.s16le");
    m_data.resize(data_s.size() / 2); // src is in bytes
    memcpy(m_data.data(), data_s.data(), data_s.size());
  }

  void generate()
  {
    int i;
    size_t j = m_phase;

    for (i = 0; i < nframes; i++) {
        if (j >= m_data.size())
        {
          buffer[i] = 0;
        }
        else
        {
          buffer[i] = m_data[j];
        }
        j++;
    }

    m_phase = j;
  }

  void click()
  {
    m_phase = 0;
  }

private:
  std::vector<uint16_t> m_data;
  size_t m_phase;
};

class PCM
{
public:
  PCM()
  {
    // non-blocking
    if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)) < 0) {
        printf("Playback open error: %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = snd_pcm_set_params(handle,
                      SND_PCM_FORMAT_S16_LE,
                      SND_PCM_ACCESS_RW_INTERLEAVED,
                      1,
                      f_sample,
                      1,
                      100000)) < 0) {   // latency in us
        printf("Playback open error: %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
 
    npfd = snd_pcm_poll_descriptors_count(handle);
    if (npfd < 0) {
      throw std::runtime_error("snd_pcm_poll_descriptors_count() failed");
    }
    pfd = (struct pollfd *)malloc(npfd * sizeof(struct pollfd));
    if (pfd == nullptr) {
      throw std::runtime_error("alloca() error for PCM");
    }
    if (0 > snd_pcm_poll_descriptors(handle, pfd, npfd))
    {
      throw std::runtime_error("snd_pcm_poll_descriptors() failure");
    }

    if (0 > snd_pcm_start(handle))
    {
     throw std::runtime_error("PCM could not be started");
    }

    if (npfd != 1) {
      std::cout << "Warning: " << std::to_string(npfd) << " poll fds for pcm" << std::endl;
    }
  }

  ~PCM()
  {
    // pass the remaining samples, otherwise they're dropped in close
    err = snd_pcm_drain(handle);
    if (err < 0)
        printf("snd_pcm_drain failed: %s\n", snd_strerror(err));
    snd_pcm_close(handle);

    free(pfd);
  }

  int fd()
  {
    return pfd->fd;
  }

  // write from buffer to ALSA PCM
  void write()
  {
        snd_pcm_sframes_t written = snd_pcm_writei(handle, &buffer[0], nframes);
        if (written < 0) {
            if (written == -EPIPE) {
              std::cout << "Warning: PCM underrun" << std::endl;
            }
            std::cout << "Recovering." << std::endl;
            written = snd_pcm_recover(handle, written, 0);
        }
        if (written < 0) {
            throw std::runtime_error("snd_pcm_writei failed: "s + snd_strerror(written));
        }

        if (written != nframes) {
          std::cout << "Warning: written " << std::to_string(written) << " frames instead of "<< std::to_string(nframes) << std::endl;
        }
  }

  bool wait_for_event()
  {
    int result = poll(pfd, npfd, 10000);
    if (result > 0)
    {
      // event
      return true;
    }
    else if (result == 0) {
      // timeout
      return false;
    } else {
      throw std::runtime_error("Poll unsuccessful");
    }
  }

  bool write_available()
  {
    snd_pcm_sframes_t result = snd_pcm_avail(handle);
    if (0 > result) {
      std::cerr << "Error: snd_pcm_avail()" << std::endl;
      //throw std::runtime_error("snd_pcm_avail()");
    }

    return result >= nframes;
  }

private:
  int err;
  snd_pcm_t *handle;

  int npfd;
  struct pollfd* pfd;
};

class MIDI
{
public:
  MIDI()
  {
    if (0 > snd_seq_open(&seq_handle, "default", SND_SEQ_OPEN_INPUT, SND_SEQ_NONBLOCK))
    {
      throw std::runtime_error("MIDI sequencer couldn't be opened");
    }

    if (0 > snd_seq_set_client_name(seq_handle, "Midi Listener"))
    {
      throw std::runtime_error("MIDI client name couldn't be set");
    }

    if (0 > ((in_port = snd_seq_create_simple_port(seq_handle, "24:0",
                      SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE | SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ,
                      SND_SEQ_PORT_TYPE_APPLICATION))))
    {
      throw std::runtime_error("MIDI port couldn't be opened");
    }

    std::cout << "in_port: " << std::to_string(in_port) << std::endl;

#if 1
    snd_seq_addr_t sender, dest;
    snd_seq_port_subscribe_t *subs;
    sender.client = 24;
    sender.port = 0;
    dest.client = snd_seq_client_id(seq_handle);
    dest.port = in_port;
    snd_seq_port_subscribe_alloca(&subs);
    snd_seq_port_subscribe_set_sender(subs, &sender);
    snd_seq_port_subscribe_set_dest(subs, &dest);
    snd_seq_port_subscribe_set_queue(subs, 1);
    //snd_seq_port_subscribe_set_time_update(subs, 1);
    snd_seq_port_subscribe_set_time_real(subs, 1);
    // TODO: fix timestamp (currently always 0)
    if (0 > snd_seq_subscribe_port(seq_handle, subs))
#endif
    //if (0 > snd_seq_connect_from(seq_handle, in_port, 24, 0))
    {
      throw std::runtime_error("MIDI port couldn't be connected");
    }

    npfd = snd_seq_poll_descriptors_count(seq_handle, POLLIN);
    if (npfd < 0) {
      throw std::runtime_error("snd_seq_poll_descriptors_count() failed");
    }
    pfd = (struct pollfd *)malloc(npfd * sizeof(struct pollfd));
    if (pfd == nullptr) {
      throw std::runtime_error("alloca() error for MIDI");
    }
    if (0 > snd_seq_poll_descriptors(seq_handle, pfd, npfd, POLLIN))
    {
      throw std::runtime_error("snd_seq_poll_descriptors() failure");
    }

    if (npfd != 1) {
      std::cout << "Warning: " << std::to_string(npfd) << " poll fds for MIDI" << std::endl;
    }
  }

  ~MIDI()
  {
    free(pfd);
  }

  int fd()
  {
    return pfd->fd;
  }

  bool event_ready()
  {
    int result = snd_seq_event_input_pending(seq_handle, 1);
    if (result < 0) {
      throw std::runtime_error("snd_seq_event_input_pending() failed");
    }

    return result > 0;
  }

  snd_seq_event_t *read(void)
  {
    snd_seq_event_t *ev = NULL;
    if (0 > snd_seq_event_input(seq_handle, &ev))
    {
     std::cerr << "snd_seq_event_input(): -EAGAIN" << std::endl;
    }
    return ev;
  }

  // returns if click starts
  bool process(const snd_seq_event_t *ev)
  {
     bool result = false;

     if((ev->type == SND_SEQ_EVENT_NOTEON)
            ||(ev->type == SND_SEQ_EVENT_NOTEOFF)) {
        const char *type = (ev->type == SND_SEQ_EVENT_NOTEON) ? "on " : "off";
        printf("[%d] Note %s: %2x vel(%2x), ch %2x\n", ((ev->flags & SND_SEQ_TIME_STAMP_MASK) == SND_SEQ_TIME_STAMP_REAL) ? ev->time.time.tv_sec : ev->time.tick,
                                               type,
                                               ev->data.note.note,
                                               ev->data.note.velocity,
                                               ev->data.control.channel);
        if (ev->type == SND_SEQ_EVENT_NOTEON) {
//          if (ev->data.note.note == CLICK_NOTE && ev->data.control.channel == CLICK_CHANNEL) {
            result = true;
//          }
        }
     }
     else if(ev->type == SND_SEQ_EVENT_CONTROLLER)
     {
        printf("[%d] Control:  %2x val(%2x)\n", ((ev->flags & SND_SEQ_TIME_STAMP_MASK) == SND_SEQ_TIME_STAMP_REAL) ? ev->time.time.tv_sec : ev->time.tick,
                                                ev->data.control.param,
                                                ev->data.control.value);
     }
     else if(ev->type == SND_SEQ_EVENT_CLOCK)
     {
        printf("[%d] Clock\n", ((ev->flags & SND_SEQ_TIME_STAMP_MASK) == SND_SEQ_TIME_STAMP_REAL) ? ev->time.time.tv_sec : ev->time.tick);
     }
     else
     {
        printf("[%d] Unknown:  Unhandled Event Received\n", ev->time.tick);
     }
     return result;
  }

  void wait_for_event()
  {
    int result = poll(pfd, npfd, 10000);
    if (result > 0)
    {
      // event
    }
    else if (result == 0) {
      // timeout
    } else {
      throw std::runtime_error("Poll unsuccessful");
    }
  }

private:
  snd_seq_t *seq_handle;
  int in_port;
  int npfd;
  struct pollfd* pfd;
};

int main(void)
{
  try {
    MIDI midi;
    ClickStream stream;
    PCM pcm;

    stream.generate();
    pcm.write();
    stream.generate();

    while (true) {
      //midi.wait_for_event();
      //pcm.wait_for_event();
      fd_set read_set;
      FD_ZERO(&read_set);
      FD_SET(midi.fd(), &read_set);

      fd_set write_set;
      FD_ZERO(&write_set);
      FD_SET(pcm.fd(), &write_set);

      struct timeval timeout;
      timeout.tv_sec = 1;
      timeout.tv_usec = 0;

      int result = select(FD_SETSIZE, &read_set, &write_set, NULL, &timeout);
      if (result < 0) {
        throw std::runtime_error("select() failed");
      } else if (result == 0) {
        throw std::runtime_error("select() timeout");
      }

      if (midi.event_ready())
      {
        //std::cout << "read..." << std::endl;
        auto event = midi.read();
        //std::cout << "process..." << std::endl;
        if (midi.process(event)) {
          stream.click();
          //std::cout << "DEBUG: CLICK" << std::endl;
        }
      }

      if (pcm.write_available()) {
        //std::cout << "DEBUG: WRITE" << std::endl;
        pcm.write();
        stream.generate();
      }
    }
  } catch (const std::exception& ex) {
    std::cerr << "Error: " << ex.what() << std::endl;
  }
 
  return 0;
}