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