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