tizenaudio-sink2: Use hardware interrupt for playback
[platform/core/multimedia/pulseaudio-modules-tizen.git] / src / module-tizenaudio-sink2.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/sink.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
50 PA_MODULE_AUTHOR("Tizen");
51 PA_MODULE_DESCRIPTION("Tizen Audio Sink2");
52 PA_MODULE_VERSION(PACKAGE_VERSION);
53 PA_MODULE_LOAD_ONCE(false);
54 PA_MODULE_USAGE(
55         "sink_name=<name of sink> "
56         "sink_properties=<properties for the sink> "
57         "device=<device to use, card comma device (e.g. 0,0)> "
58         "format=<sample format> "
59         "rate=<sample rate> "
60         "channels=<number of channels> "
61         "channel_map=<channel map>"
62         "fragments=<number of fragments> "
63         "fragment_size=<fragment size> ");
64
65 #define DEFAULT_SINK_NAME "tizenaudio-sink2"
66
67 #define DEVICE_NAME_MAX                     30
68
69 struct userdata {
70     pa_core *core;
71     pa_module *module;
72     pa_sink *sink;
73
74     pa_thread *thread;
75     pa_thread_mq thread_mq;
76     pa_rtpoll *rtpoll;
77     pa_usec_t timestamp;
78
79     void *pcm_handle;
80     uint32_t nfrags;
81     uint32_t frag_size;
82
83     char* card;
84     char* device;
85     bool first;
86
87     pa_rtpoll_item *rtpoll_item;
88
89     uint64_t write_count;
90     pa_hal_interface *hal_interface;
91 };
92
93 static const char* const valid_modargs[] = {
94     "sink_name",
95     "sink_properties",
96     "device",
97     "format",
98     "rate",
99     "channels",
100     "channel_map",
101     "fragments",
102     "fragment_size",
103     NULL
104 };
105
106 static int build_pollfd(struct userdata *u) {
107     int32_t ret;
108     struct pollfd *pollfd;
109     int fd = -1;
110
111     pa_assert(u);
112     pa_assert(u->pcm_handle);
113     pa_assert(u->rtpoll);
114
115     if (u->rtpoll_item)
116         pa_rtpoll_item_free(u->rtpoll_item);
117
118     u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
119     pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
120     ret = pa_hal_interface_pcm_get_fd(u->hal_interface, u->pcm_handle, &fd);
121     if (ret < 0 || fd < 0) {
122         pa_log_error("Failed to get fd(%d) of PCM device %d", fd, ret);
123         return -1;
124     }
125     pollfd->fd = fd;
126     pollfd->events = POLLOUT | POLLERR | POLLNVAL;
127
128     return 0;
129 }
130
131 /* Called from IO context */
132 static int suspend(struct userdata *u) {
133     int32_t ret;
134     pa_assert(u);
135     pa_assert(u->pcm_handle);
136
137     ret = pa_hal_interface_pcm_close(u->hal_interface, u->pcm_handle);
138     if (ret) {
139         pa_log_error("Error closing PCM device %x", ret);
140     }
141     u->pcm_handle = NULL;
142
143     if (u->rtpoll_item) {
144         pa_rtpoll_item_free(u->rtpoll_item);
145         u->rtpoll_item = NULL;
146     }
147
148     pa_log_info("Device suspended...");
149
150     return 0;
151 }
152
153 /* Called from IO context */
154 static int unsuspend(struct userdata *u) {
155     pa_sample_spec sample_spec;
156     int32_t ret;
157     size_t frame_size;
158
159     pa_assert(u);
160     pa_assert(!u->pcm_handle);
161
162     pa_log_info("Trying resume...");
163
164     sample_spec = u->sink->sample_spec;
165     frame_size = pa_frame_size(&sample_spec);
166     if (frame_size == 0) {
167         pa_log_error("Unexpected frame size zero!");
168         goto fail;
169     }
170
171     ret = pa_hal_interface_pcm_open(u->hal_interface,
172               u->card,
173               u->device,
174               DIRECTION_OUT,
175               &sample_spec,
176               u->frag_size / frame_size,
177               u->nfrags,
178               (void **)&u->pcm_handle);
179     if (ret) {
180         pa_log_error("Error opening PCM device %x", ret);
181         goto fail;
182     }
183
184     if (build_pollfd(u) < 0)
185         goto fail;
186
187     u->write_count = 0;
188     u->first = true;
189     u->timestamp = pa_rtclock_now();
190
191     pa_log_info("Resumed successfully...");
192
193     return 0;
194
195 fail:
196     if (u->pcm_handle) {
197         pa_hal_interface_pcm_close(u->hal_interface, u->pcm_handle);
198         u->pcm_handle = NULL;
199     }
200     return -PA_ERR_IO;
201 }
202
203 /* Called from the IO thread. */
204 static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
205     struct userdata *u;
206     int r;
207
208     pa_assert(s);
209     pa_assert_se(u = s->userdata);
210
211     /* It may be that only the suspend cause is changing, in which case there's
212      * nothing to do. */
213     if (new_state == s->thread_info.state)
214         return 0;
215
216     switch (new_state) {
217         case PA_SINK_SUSPENDED: {
218             pa_assert(PA_SINK_IS_OPENED(s->thread_info.state));
219             if ((r = suspend(u)) < 0)
220                 return r;
221             break;
222         }
223
224         case PA_SINK_IDLE:
225         case PA_SINK_RUNNING: {
226             if (s->thread_info.state == PA_SINK_INIT) {
227                 if (build_pollfd(u) < 0)
228                     return -PA_ERR_IO;
229             }
230
231             if (s->thread_info.state == PA_SINK_SUSPENDED) {
232                 if ((r = unsuspend(u)) < 0)
233                     return r;
234             }
235             break;
236         }
237
238         case PA_SINK_UNLINKED:
239         case PA_SINK_INIT:
240         case PA_SINK_INVALID_STATE:
241             break;
242     }
243
244     return 0;
245 }
246
247 static int sink_process_msg(
248         pa_msgobject *o,
249         int code,
250         void *data,
251         int64_t offset,
252         pa_memchunk *chunk) {
253
254     struct userdata *u = PA_SINK(o)->userdata;
255
256     switch (code) {
257         case PA_SINK_MESSAGE_GET_LATENCY: {
258             int64_t r = 0;
259
260             if (u->pcm_handle)
261                 r = u->timestamp + pa_bytes_to_usec(u->write_count, &u->sink->sample_spec) - pa_rtclock_now();
262
263             *((int64_t *) data) = r;
264
265             return 0;
266         }
267     }
268
269     return pa_sink_process_msg(o, code, data, offset, chunk);
270 }
271
272 static void process_rewind(struct userdata *u) {
273 #if 1
274     /* Rewind not supported */
275     pa_sink_process_rewind(u->sink, 0);
276 #else
277     size_t rewind_nbytes, in_buffer;
278     pa_usec_t delay;
279
280     pa_assert(u);
281
282     rewind_nbytes = u->sink->thread_info.rewind_nbytes;
283
284     if (!PA_SINK_IS_OPENED(u->sink->thread_info.state) || rewind_nbytes <= 0)
285         goto do_nothing;
286
287     pa_log_debug("Requested to rewind %lu bytes.", (unsigned long)rewind_nbytes);
288
289     if (u->timestamp <= now)
290         goto do_nothing;
291
292     delay = u->timestamp - now;
293     in_buffer = pa_usec_to_bytes(delay, &u->sink->sample_spec);
294
295     if (in_buffer <= 0)
296         goto do_nothing;
297
298     if (rewind_nbytes > in_buffer)
299         rewind_nbytes = in_buffer;
300
301     pa_sink_process_rewind(u->sink, rewind_nbytes);
302     u->timestamp -= pa_bytes_to_usec(rewind_nbytes, &u->sink->sample_spec);
303
304     pa_log_debug("Rewound %lu bytes.", (unsigned long)rewind_nbytes);
305     return;
306
307 do_nothing:
308     pa_sink_process_rewind(u->sink, 0);
309 #endif
310 }
311
312 static int process_render(struct userdata *u) {
313     void *p;
314     size_t frame_size = pa_frame_size(&u->sink->sample_spec);
315     size_t frames_to_write = u->frag_size / u->nfrags;
316     uint32_t avail = 0;
317     pa_memchunk chunk;
318
319     pa_assert(u);
320
321     pa_hal_interface_pcm_available(u->hal_interface, u->pcm_handle, &avail);
322     if (frames_to_write > avail) {
323         pa_log_debug("not enough avail size. frames_to_write(%d), avail(%d)", frames_to_write, avail);
324         return 0;
325     }
326
327     pa_sink_render_full(u->sink, frames_to_write * frame_size, &chunk);
328     p = pa_memblock_acquire(chunk.memblock);
329
330     if (pa_hal_interface_pcm_write(u->hal_interface, u->pcm_handle, (const char*)p + chunk.index, (uint32_t)frames_to_write)) {
331         pa_log_error("failed to write pcm. p(%p), size(%d)", p, frames_to_write);
332         return -1;
333     }
334
335     pa_memblock_release(chunk.memblock);
336     pa_memblock_unref(chunk.memblock);
337
338     u->write_count += chunk.length;
339
340     return 0;
341 }
342
343 static void thread_func(void *userdata) {
344     struct userdata *u = userdata;
345     unsigned short revents = 0;
346
347     pa_assert(u);
348
349     pa_log_debug("Thread starting up");
350
351     if (u->core->realtime_scheduling)
352         pa_thread_make_realtime(u->core->realtime_priority);
353
354     pa_thread_mq_install(&u->thread_mq);
355
356     u->timestamp = pa_rtclock_now();
357
358     for (;;) {
359         int ret;
360
361         if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
362             process_rewind(u);
363
364         if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
365             if (process_render(u))
366                 goto fail;
367
368             if (u->first) {
369                 pa_log_info("Starting playback.");
370                 pa_hal_interface_pcm_start(u->hal_interface, u->pcm_handle);
371                 u->first = false;
372             }
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_SINK_IS_OPENED(u->sink->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 & ~POLLOUT) {
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_sink_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     size_t frame_size, buffer_size, period_frames, buffer_frames;
456
457     pa_assert(m);
458
459     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
460         pa_log_error("Failed to parse module arguments.");
461         goto fail;
462     }
463
464     ss = m->core->default_sample_spec;
465     map = m->core->default_channel_map;
466     if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_DEFAULT) < 0) {
467         pa_log_error("Invalid sample format specification or channel map");
468         goto fail;
469     }
470
471     alternate_sample_rate = m->core->alternate_sample_rate;
472     if (pa_modargs_get_alternate_sample_rate(ma, &alternate_sample_rate) < 0) {
473         pa_log_error("Failed to parse alternate sample rate");
474         goto fail;
475     }
476
477     m->userdata = u = pa_xnew0(struct userdata, 1);
478     u->core = m->core;
479     u->module = m;
480     u->first = true;
481     u->timestamp = 0ULL;
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(m->core->default_fragment_size_msec*PA_USEC_PER_MSEC, &ss);
500     u->nfrags = m->core->default_n_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_sink_new_data_init(&data);
509     data.driver = __FILE__;
510     data.module = m;
511     pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
512     pa_sink_new_data_set_sample_spec(&data, &ss);
513     pa_sink_new_data_set_channel_map(&data, &map);
514     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, _("Tizen audio sink"));
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, PA_PROP_DEVICE_API, "tizen");
519
520     frame_size = pa_frame_size(&ss);
521     buffer_size = u->frag_size * u->nfrags;
522     buffer_frames = buffer_size / frame_size;
523     period_frames = u->frag_size / frame_size;
524     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_BUFFER_SIZE, "%zu", buffer_frames * frame_size);
525     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_BUFFERING_FRAGMENT_SIZE, "%zu", period_frames * frame_size);
526
527     if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
528         pa_log_error("Invalid properties.");
529         pa_sink_new_data_done(&data);
530         goto fail;
531     }
532
533     u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY);
534     pa_sink_new_data_done(&data);
535
536     if (!u->sink) {
537         pa_log_error("Failed to create sink object.");
538         goto fail;
539     }
540
541     u->sink->parent.process_msg = sink_process_msg;
542     u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
543     u->sink->userdata = u;
544
545     if (pa_hal_interface_pcm_open(u->hal_interface,
546               u->card,
547               u->device,
548               DIRECTION_OUT,
549               &u->sink->sample_spec,
550               u->frag_size / pa_frame_size(&u->sink->sample_spec),
551               u->nfrags,
552               (void **)&u->pcm_handle)) {
553         pa_log_error("Error opening PCM device");
554         goto fail;
555     }
556
557     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
558     pa_sink_set_rtpoll(u->sink, u->rtpoll);
559
560     pa_sink_set_max_request(u->sink, buffer_size);
561     pa_sink_set_max_rewind(u->sink, buffer_size);
562
563     if (!(u->thread = pa_thread_new("tizenaudio-sink", thread_func, u))) {
564         pa_log_error("Failed to create thread.");
565         goto fail;
566     }
567     pa_sink_set_fixed_latency(u->sink, pa_bytes_to_usec(buffer_size, &ss));
568     pa_sink_put(u->sink);
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_sink_linked_by(u->sink);
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->sink)
599         pa_sink_unlink(u->sink);
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->sink)
609         pa_sink_unref(u->sink);
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     pa_xfree(u);
623 }