Separate tizenaudio-sink2 and module-tizenaudio-sink2
[platform/core/multimedia/pulseaudio-modules-tizen.git] / src / tizenaudio-source2.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright (c) 2022 Samsung Electronics Co., Ltd. All rights reserved.
5
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2.1 of the License,
9   or (at your option) any later version.
10
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with PulseAudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #include <unistd.h>
30
31 #include <pulse/rtclock.h>
32 #include <pulse/timeval.h>
33 #include <pulse/xmalloc.h>
34 #include <pulse/util.h>
35
36 #include <pulsecore/i18n.h>
37 #include <pulsecore/macro.h>
38 #include <pulsecore/source.h>
39 #include <pulsecore/module.h>
40 #include <pulsecore/core-util.h>
41 #include <pulsecore/modargs.h>
42 #include <pulsecore/log.h>
43 #include <pulsecore/thread.h>
44 #include <pulsecore/thread-mq.h>
45 #include <pulsecore/rtpoll.h>
46 #include <pulsecore/poll.h>
47
48 #include "hal-interface.h"
49 #include "echo-cancel/echo-cancel-def.h"
50
51 #define DEFAULT_SOURCE_NAME "tizenaudio-source2"
52
53 #define DEVICE_NAME_MAX                     30
54 #define DEFAULT_FRAGMENT_MSEC               20
55 #define DEFAULT_FRAGMENTS                    4
56
57 struct userdata {
58     pa_core *core;
59     pa_module *module;
60     pa_source *source;
61
62     pa_thread *thread;
63     pa_thread_mq thread_mq;
64     pa_rtpoll *rtpoll;
65
66     void *pcm_handle;
67     uint32_t nfrags;
68     uint32_t frag_size;
69
70     pa_usec_t timestamp;
71
72     char* card;
73     char* device;
74     bool first;
75     bool echo_on;
76
77     pa_rtpoll_item *rtpoll_item;
78
79     uint64_t read_count;
80     pa_usec_t latency_time;
81     pa_hal_interface *hal_interface;
82
83     /* for echo-cancel */
84     pa_msgobject *ec_object;
85     pa_asyncmsgq *ec_asyncmsgq;
86     pa_rtpoll_item *ec_poll_item;
87 };
88
89 static void userdata_free(struct userdata *u);
90
91 static int build_pollfd(struct userdata *u) {
92     int32_t ret;
93     struct pollfd *pollfd;
94     int fd = -1;
95
96     pa_assert(u);
97     pa_assert(u->pcm_handle);
98     pa_assert(u->rtpoll);
99
100     if (u->rtpoll_item)
101         pa_rtpoll_item_free(u->rtpoll_item);
102
103     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
104     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
105     ret = pa_hal_interface_pcm_get_fd(u->hal_interface, u->pcm_handle, &fd);
106     if (ret < 0 || fd < 0) {
107         pa_log_error("Failed to get fd(%d) of PCM device %d", fd, ret);
108         return -1;
109     }
110     pollfd->fd = fd;
111     pollfd->events = POLLIN | POLLERR | POLLNVAL;
112
113     return 0;
114 }
115
116 /* Called from IO context */
117 static int suspend(struct userdata *u) {
118     int32_t ret;
119     pa_assert(u);
120     pa_assert(u->pcm_handle);
121
122     ret = pa_hal_interface_pcm_close(u->hal_interface, u->pcm_handle);
123     if (ret) {
124         pa_log_error("Error closing PCM device %x", ret);
125     }
126     u->pcm_handle = NULL;
127
128     if (u->rtpoll_item) {
129         pa_rtpoll_item_free(u->rtpoll_item);
130         u->rtpoll_item = NULL;
131     }
132
133     pa_log_info("Device suspended...");
134
135     return 0;
136 }
137
138 /* Called from IO context */
139 static int unsuspend(struct userdata *u) {
140     pa_sample_spec sample_spec;
141     int32_t ret;
142     size_t frame_size;
143
144     pa_assert(u);
145     pa_assert(!u->pcm_handle);
146
147     pa_log_info("Trying resume...");
148
149     sample_spec = u->source->sample_spec;
150     frame_size = pa_frame_size(&sample_spec);
151     if (frame_size == 0) {
152         pa_log_error("Unexpected frame size zero!");
153         goto fail;
154     }
155
156     ret = pa_hal_interface_pcm_open(u->hal_interface,
157               u->card,
158               u->device,
159               DIRECTION_IN,
160               &sample_spec,
161               u->frag_size / frame_size,
162               u->nfrags,
163               (void **)&u->pcm_handle);
164     if (ret) {
165         pa_log_error("Error opening PCM device %x", ret);
166         goto fail;
167     }
168
169     if (build_pollfd(u) < 0)
170         goto fail;
171
172     u->read_count = 0;
173     u->first = true;
174     u->timestamp = pa_rtclock_now();
175
176     pa_log_info("Resumed successfully...");
177
178     return 0;
179
180 fail:
181     if (u->pcm_handle) {
182         pa_hal_interface_pcm_close(u->hal_interface, u->pcm_handle);
183         u->pcm_handle = NULL;
184     }
185     return -PA_ERR_IO;
186 }
187
188 /* Called from the IO thread. */
189 static int source_set_state_in_io_thread_cb(pa_source *s, pa_source_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
190     struct userdata *u;
191     int r;
192
193     pa_assert(s);
194     pa_assert_se(u = s->userdata);
195
196     /* It may be that only the suspend cause is changing, in which case there's
197      * nothing more to do. */
198     if (new_state == s->thread_info.state)
199         return 0;
200
201     switch (new_state) {
202         case PA_SOURCE_SUSPENDED: {
203             pa_assert(PA_SOURCE_IS_OPENED(s->thread_info.state));
204             if ((r = suspend(u)) < 0)
205                 return r;
206             break;
207         }
208
209         case PA_SOURCE_IDLE:
210         case PA_SOURCE_RUNNING: {
211             if (s->thread_info.state == PA_SOURCE_INIT) {
212                 if (build_pollfd(u) < 0)
213                     return -PA_ERR_IO;
214             }
215
216             if (s->thread_info.state == PA_SOURCE_SUSPENDED) {
217                 if ((r = unsuspend(u)) < 0)
218                     return r;
219             }
220             break;
221         }
222
223         case PA_SOURCE_UNLINKED:
224         case PA_SOURCE_INIT:
225         case PA_SOURCE_INVALID_STATE:
226             break;
227     }
228
229     return 0;
230 }
231
232 static int source_process_msg(
233         pa_msgobject *o,
234         int code,
235         void *data,
236         int64_t offset,
237         pa_memchunk *chunk) {
238
239     struct userdata *u = PA_SOURCE(o)->userdata;
240
241     switch (code) {
242         case PA_SOURCE_MESSAGE_SET_AEC_STATE: {
243             u->echo_on = !!data;
244             pa_log_info("EC state changed (%d)", u->echo_on);
245             return 0;
246         }
247         case PA_SOURCE_MESSAGE_GET_LATENCY: {
248             uint64_t r = 0;
249
250             if (u->pcm_handle)
251                 r = pa_rtclock_now() - (u->timestamp + pa_bytes_to_usec(u->read_count, &u->source->sample_spec));
252
253             *((int64_t *) data) = r;
254
255             return 0;
256         }
257         case PA_SOURCE_MESSAGE_REBUILD_RTPOLL: {
258             struct arguments {
259                 pa_msgobject *o;
260                 pa_asyncmsgq *q;
261             } *args;
262
263             args = (struct arguments *)data;
264
265             if (args) {
266                 u->ec_object = args->o;
267                 u->ec_asyncmsgq = args->q;
268                 u->ec_poll_item = pa_rtpoll_item_new_asyncmsgq_write(u->rtpoll, PA_RTPOLL_EARLY, args->q);
269             } else {
270                 pa_rtpoll_item_free(u->ec_poll_item);
271                 u->ec_poll_item = NULL;
272                 u->ec_object = NULL;
273             }
274
275             return 0;
276         }
277     }
278
279     return pa_source_process_msg(o, code, data, offset, chunk);
280 }
281
282 static int process_render(struct userdata *u) {
283     void *p;
284     size_t frame_size = pa_frame_size(&u->source->sample_spec);
285     size_t frames_to_read = u->frag_size / frame_size;
286     uint32_t avail = 0;
287     pa_memchunk chunk;
288
289     pa_assert(u);
290
291     /* Fill the buffer up the latency size */
292
293     pa_hal_interface_pcm_available(u->hal_interface, u->pcm_handle, &avail);
294     if (frames_to_read > avail) {
295         pa_log_debug("not enough avail size. frames_to_read(%zu), avail(%u)", frames_to_read, avail);
296         return 0;
297     }
298
299     chunk.length = u->frag_size;
300     chunk.memblock = pa_memblock_new(u->core->mempool, chunk.length);
301
302     p = pa_memblock_acquire(chunk.memblock);
303     if (pa_hal_interface_pcm_read(u->hal_interface, u->pcm_handle, p, (uint32_t)frames_to_read)) {
304         pa_log_error("failed to read pcm. p(%p), size(%zu)", p, frames_to_read);
305         return -1;
306     }
307     pa_memblock_release(chunk.memblock);
308
309     chunk.index = 0;
310     chunk.length = (size_t)frames_to_read * frame_size;
311
312     if (u->echo_on) {
313         pa_asyncmsgq_post(u->ec_asyncmsgq, u->ec_object,
314                             PA_ECHO_CANCEL_MESSAGE_PUSH_DATA, NULL, 0, &chunk, NULL);
315     } else {
316         pa_source_post(u->source, &chunk);
317     }
318
319     pa_memblock_unref(chunk.memblock);
320
321     u->read_count += chunk.length;
322
323     return 0;
324 }
325
326 static void thread_func(void *userdata) {
327     struct userdata *u = userdata;
328     unsigned short revents = 0;
329
330     pa_assert(u);
331     pa_log_debug("Thread starting up");
332
333     if (u->core->realtime_scheduling)
334         pa_thread_make_realtime(u->core->realtime_priority);
335
336     pa_thread_mq_install(&u->thread_mq);
337
338     u->timestamp = pa_rtclock_now();
339
340     for (;;) {
341         int ret;
342
343         /* Render some data and drop it immediately */
344         if (PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
345             if (process_render(u))
346                 goto fail;
347
348             if (u->first) {
349                 pa_log_info("Starting capture.");
350                 pa_hal_interface_pcm_start(u->hal_interface, u->pcm_handle);
351                 u->first = false;
352             }
353         }
354
355         /* Hmm, nothing to do. Let's sleep */
356         if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
357             goto fail;
358
359         if (ret == 0)
360             goto finish;
361
362         if (PA_SOURCE_IS_OPENED(u->source->thread_info.state)) {
363             struct pollfd *pollfd;
364             if (u->rtpoll_item) {
365                 pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
366                 revents = pollfd->revents;
367                 if (revents & ~POLLIN) {
368                     pa_log_debug("Poll error 0x%x occured, try recover.", revents);
369                     pa_hal_interface_pcm_recover(u->hal_interface, u->pcm_handle, revents);
370                     u->first = true;
371                     revents = 0;
372                 }
373             }
374         }
375     }
376
377 fail:
378     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
379     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
380
381 finish:
382     pa_log_debug("Thread shutting down");
383 }
384
385 static int parse_to_get_card(const char *modarg_device, char *card) {
386     const char *name_p;
387     char *card_p;
388
389     if (!strchr(modarg_device, ',')) {
390         pa_log_error("Failed to parse device argument : no comma");
391         return -1;
392     }
393
394     name_p = modarg_device;
395     card_p = card;
396     while (*name_p != ',')
397         *(card_p++) = *(name_p++);
398     *card_p = '\0';
399
400     return 0;
401 }
402
403 static int parse_to_get_device(const char *modarg_device, char *device) {
404     const char *comma_p;
405     char *device_p;
406
407     if (!(comma_p = strchr(modarg_device, ','))) {
408         pa_log_error("Failed to parse device argument : no comma");
409         return -1;
410     }
411
412     comma_p++;
413     device_p = device;
414     while (*comma_p != '\0')
415         *(device_p++) = *(comma_p++);
416     *device_p = '\0';
417
418     return 0;
419 }
420
421 pa_source *pa_tizenaudio_source2_new(pa_module *m, pa_modargs *ma, const char *driver) {
422     struct userdata *u = NULL;
423     pa_sample_spec ss;
424     pa_channel_map map;
425     pa_source_new_data data;
426     uint32_t alternate_sample_rate;
427     const char *modarg_device;
428     char card[DEVICE_NAME_MAX];
429     char device[DEVICE_NAME_MAX];
430     size_t frame_size, buffer_size, period_frames, buffer_frames;
431
432     pa_assert(m);
433
434     ss = m->core->default_sample_spec;
435     map = m->core->default_channel_map;
436     if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_DEFAULT) < 0) {
437         pa_log_error("Invalid sample format specification or channel map");
438         goto fail;
439     }
440
441     alternate_sample_rate = m->core->alternate_sample_rate;
442     if (pa_modargs_get_alternate_sample_rate(ma, &alternate_sample_rate) < 0) {
443         pa_log_error("Failed to parse alternate sample rate");
444         goto fail;
445     }
446
447     u = pa_xnew0(struct userdata, 1);
448     u->core = m->core;
449     u->module = m;
450     u->first = true;
451     u->hal_interface = pa_hal_interface_get(u->core);
452     u->rtpoll = pa_rtpoll_new();
453     pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
454
455     if (!(modarg_device = pa_modargs_get_value(ma, "device", NULL))) {
456         pa_log_error("device is invalid");
457         goto fail;
458     }
459
460     if (parse_to_get_card(modarg_device, card) || parse_to_get_device(modarg_device, device)) {
461         pa_log_error("failed to parse device module argument, %s", modarg_device);
462         goto fail;
463     }
464
465     u->card = pa_xstrdup(card);
466     u->device = pa_xstrdup(device);
467
468     u->frag_size = (uint32_t) pa_usec_to_bytes(DEFAULT_FRAGMENT_MSEC * PA_USEC_PER_MSEC, &ss);
469     u->nfrags = DEFAULT_FRAGMENTS;
470     if (pa_modargs_get_value_u32(ma, "fragment_size", &u->frag_size) < 0 ||
471         pa_modargs_get_value_u32(ma, "fragments", &u->nfrags) < 0) {
472         pa_log_error("fragment_size or fragments are invalid.");
473         goto fail;
474     }
475     pa_log_info("card(%s) device(%s) fragment_size(%u), fragments(%u)", u->card, u->device, u->frag_size, u->nfrags);
476
477     pa_source_new_data_init(&data);
478     data.driver = driver;
479     data.module = m;
480     pa_source_new_data_set_name(&data, pa_modargs_get_value(ma, "source_name", DEFAULT_SOURCE_NAME));
481     pa_source_new_data_set_sample_spec(&data, &ss);
482     pa_source_new_data_set_channel_map(&data, &map);
483     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, _("Tizen audio source2"));
484     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "abstract");
485     pa_proplist_sets(data.proplist, "tizen.card", u->card);
486     pa_proplist_sets(data.proplist, "tizen.device", u->device);
487     pa_proplist_sets(data.proplist, "tizen.version", "2");
488     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "tizen");
489
490     frame_size = pa_frame_size(&ss);
491     buffer_size = (size_t)(u->frag_size * u->nfrags);
492     buffer_frames = buffer_size / frame_size;
493     period_frames = u->frag_size / frame_size;
494     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_BUFFER_SIZE, "%zu", buffer_frames * frame_size);
495     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_FRAGMENT_SIZE, "%zu", period_frames * frame_size);
496
497     if (pa_modargs_get_proplist(ma, "source_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
498         pa_log_error("Invalid properties.");
499         pa_source_new_data_done(&data);
500         goto fail;
501     }
502
503     u->source = pa_source_new(m->core, &data, PA_SOURCE_LATENCY);
504     pa_source_new_data_done(&data);
505
506     if (!u->source) {
507         pa_log_error("Failed to create source object.");
508         goto fail;
509     }
510
511     u->source->parent.process_msg = source_process_msg;
512     u->source->set_state_in_io_thread = source_set_state_in_io_thread_cb;
513     u->source->userdata = u;
514
515     if (pa_hal_interface_pcm_open(u->hal_interface,
516               u->card,
517               u->device,
518               DIRECTION_IN,
519               &u->source->sample_spec,
520               u->frag_size / pa_frame_size(&u->source->sample_spec),
521               u->nfrags,
522               (void **)&u->pcm_handle)) {
523         pa_log_error("Error opening PCM device");
524         goto fail;
525     }
526
527     pa_source_set_asyncmsgq(u->source, u->thread_mq.inq);
528     pa_source_set_rtpoll(u->source, u->rtpoll);
529
530     u->timestamp = 0ULL;
531
532     if (!(u->thread = pa_thread_new("tizenaudio-source2", thread_func, u))) {
533         pa_log_error("Failed to create thread.");
534         goto fail;
535     }
536
537     pa_source_set_fixed_latency(u->source, pa_bytes_to_usec(buffer_size, &ss));
538     pa_source_put(u->source);
539
540     return u->source;
541
542 fail:
543     userdata_free(u);
544     return NULL;
545 }
546
547 static void userdata_free(struct userdata *u) {
548     pa_assert(u);
549
550     if (u->source)
551         pa_source_unlink(u->source);
552
553     if (u->thread) {
554         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
555         pa_thread_free(u->thread);
556     }
557
558     pa_thread_mq_done(&u->thread_mq);
559
560     if (u->source)
561         pa_source_unref(u->source);
562
563     pa_xfree(u->card);
564     pa_xfree(u->device);
565
566     if (u->rtpoll)
567         pa_rtpoll_free(u->rtpoll);
568
569     if (u->pcm_handle) {
570         pa_hal_interface_pcm_stop(u->hal_interface, u->pcm_handle);
571         pa_hal_interface_pcm_close(u->hal_interface, u->pcm_handle);
572     }
573
574     if (u->hal_interface)
575         pa_hal_interface_unref(u->hal_interface);
576
577     pa_xfree(u);
578 }
579
580 void pa_tizenaudio_source2_free(pa_source *s) {
581     struct userdata *u;
582
583     pa_source_assert_ref(s);
584     pa_assert_se((u = s->userdata));
585
586     userdata_free(u);
587 }