source: mainline/uspace/app/wavplay/dplay.c@ cb500a2

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since cb500a2 was 4a9728ec, checked in by Jan Vesely <jano.vesely@…>, 12 years ago

avplay: increase work time to work around timing issues on 100 HZ timer

  • Property mode set to 100644
File size: 11.4 KB
Line 
1/*
2 * Copyright (c) 2012 Jan Vesely
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup dplay
30 * @{
31 */
32/**
33 * @file PCM playback audio devices
34 */
35
36#include <assert.h>
37#include <errno.h>
38#include <str_error.h>
39#include <str.h>
40#include <audio_pcm_iface.h>
41#include <fibril_synch.h>
42#include <pcm/format.h>
43#include <sys/mman.h>
44#include <sys/time.h>
45#include <inttypes.h>
46
47#include <stdio.h>
48#include <macros.h>
49
50#include "wave.h"
51#include "dplay.h"
52
53#define DEFAULT_FRAGMENTS 2
54
55/** Playback helper structure */
56typedef struct {
57 struct {
58 void *base;
59 size_t size;
60 void* write_ptr;
61 } buffer;
62 pcm_format_t f;
63 FILE* source;
64 volatile bool playing;
65 fibril_mutex_t mutex;
66 fibril_condvar_t cv;
67 audio_pcm_sess_t *device;
68} playback_t;
69
70/**
71 * Initialize playback helper structure.
72 * @param pb Pointer to helper structure to initialize
73 * @param sess Pointer to audio device IPC session
74 * @return
75 */
76static void playback_initialize(playback_t *pb, audio_pcm_sess_t *sess)
77{
78 assert(sess);
79 assert(pb);
80 pb->buffer.base = NULL;
81 pb->buffer.size = 0;
82 pb->buffer.write_ptr = NULL;
83 pb->playing = false;
84 pb->source = NULL;
85 pb->device = sess;
86 fibril_mutex_initialize(&pb->mutex);
87 fibril_condvar_initialize(&pb->cv);
88}
89
90/**
91 * Fragment playback callback function.
92 * @param iid IPC call id.
93 * @param icall Pointer to the call structure
94 * @param arg Argument, pointer to the playback helper function
95 */
96static void device_event_callback(ipc_callid_t iid, ipc_call_t *icall, void* arg)
97{
98 async_answer_0(iid, EOK);
99 playback_t *pb = arg;
100 const size_t fragment_size = pb->buffer.size / DEFAULT_FRAGMENTS;
101 while (1) {
102 ipc_call_t call;
103 ipc_callid_t callid = async_get_call(&call);
104 switch(IPC_GET_IMETHOD(call)) {
105 case PCM_EVENT_PLAYBACK_STARTED:
106 case PCM_EVENT_FRAMES_PLAYED:
107 printf("%" PRIun " frames: ", IPC_GET_ARG1(call));
108 async_answer_0(callid, EOK);
109 break;
110 case PCM_EVENT_PLAYBACK_TERMINATED:
111 printf("Playback terminated\n");
112 fibril_mutex_lock(&pb->mutex);
113 pb->playing = false;
114 fibril_condvar_signal(&pb->cv);
115 async_answer_0(callid, EOK);
116 fibril_mutex_unlock(&pb->mutex);
117 return;
118 default:
119 printf("Unknown event %" PRIun ".\n", IPC_GET_IMETHOD(call));
120 async_answer_0(callid, ENOTSUP);
121 continue;
122
123 }
124 const size_t bytes = fread(pb->buffer.write_ptr,
125 sizeof(uint8_t), fragment_size, pb->source);
126 printf("Copied from position %p size %zu/%zu\n",
127 pb->buffer.write_ptr, bytes, fragment_size);
128 if (bytes == 0) {
129 audio_pcm_last_playback_fragment(pb->device);
130 }
131 /* any constant is silence */
132 memset(pb->buffer.write_ptr + bytes, 0, fragment_size - bytes);
133 pb->buffer.write_ptr += fragment_size;
134
135 if (pb->buffer.write_ptr >= (pb->buffer.base + pb->buffer.size))
136 pb->buffer.write_ptr -= pb->buffer.size;
137 }
138}
139
140/**
141 * Start event based playback.
142 * @param pb Playback helper structure.
143 */
144static void play_fragment(playback_t *pb)
145{
146 assert(pb);
147 assert(pb->device);
148 const size_t fragment_size = pb->buffer.size / DEFAULT_FRAGMENTS;
149 printf("Registering event callback\n");
150 int ret = audio_pcm_register_event_callback(pb->device,
151 device_event_callback, pb);
152 if (ret != EOK) {
153 printf("Failed to register event callback.\n");
154 return;
155 }
156 printf("Playing: %dHz, %s, %d channel(s).\n", pb->f.sampling_rate,
157 pcm_sample_format_str(pb->f.sample_format), pb->f.channels);
158 const size_t bytes = fread(pb->buffer.base, sizeof(uint8_t),
159 fragment_size, pb->source);
160 if (bytes != fragment_size)
161 memset(pb->buffer.base + bytes, 0, fragment_size - bytes);
162 printf("Initial: Copied from position %p size %zu/%zu\n",
163 pb->buffer.base, bytes, fragment_size);
164 pb->buffer.write_ptr = pb->buffer.base + fragment_size;
165 fibril_mutex_lock(&pb->mutex);
166 const unsigned frames =
167 pcm_format_size_to_frames(fragment_size, &pb->f);
168 ret = audio_pcm_start_playback_fragment(pb->device, frames,
169 pb->f.channels, pb->f.sampling_rate, pb->f.sample_format);
170 if (ret != EOK) {
171 fibril_mutex_unlock(&pb->mutex);
172 printf("Failed to start playback: %s.\n", str_error(ret));
173 audio_pcm_unregister_event_callback(pb->device);
174 return;
175 }
176
177 for (pb->playing = true; pb->playing;
178 fibril_condvar_wait(&pb->cv, &pb->mutex));
179
180 fibril_mutex_unlock(&pb->mutex);
181 printf("\n");
182 audio_pcm_unregister_event_callback(pb->device);
183}
184
185/**
186 * Count occupied space in a cyclic buffer.
187 * @param pb Playback helper structure.
188 * @param pos read pointer position.
189 * @return Occupied space size.
190 */
191static size_t buffer_occupied(const playback_t *pb, size_t pos)
192{
193 assert(pb);
194 void *read_ptr = pb->buffer.base + pos;
195 if (read_ptr > pb->buffer.write_ptr)
196 return pb->buffer.write_ptr + pb->buffer.size - read_ptr;
197 return pb->buffer.write_ptr - read_ptr;
198
199}
200
201/**
202 * Count available space in a cyclic buffer.
203 * @param pb Playback helper structure.
204 * @param pos read pointer position.
205 * @return Free space size.
206 */
207static size_t buffer_avail(const playback_t *pb, size_t pos)
208{
209 assert(pb);
210 void *read_ptr = pb->buffer.base + pos;
211 if (read_ptr <= pb->buffer.write_ptr)
212 return read_ptr + pb->buffer.size - pb->buffer.write_ptr - 1;
213 return (read_ptr - pb->buffer.write_ptr) - 1;
214}
215
216/**
217 * Size of the space between write pointer and the end of a cyclic buffer
218 * @param pb Playback helper structure.
219 */
220static size_t buffer_remain(const playback_t *pb)
221{
222 assert(pb);
223 return (pb->buffer.base + pb->buffer.size) - pb->buffer.write_ptr;
224}
225
226/**
227 * Move write pointer forward. Wrap around the end.
228 * @param pb Playback helper structure.
229 * @param bytes NUmber of bytes to advance.
230 */
231static void buffer_advance(playback_t *pb, size_t bytes)
232{
233 assert(pb);
234 pb->buffer.write_ptr += bytes;
235 while (pb->buffer.write_ptr >= (pb->buffer.base + pb->buffer.size))
236 pb->buffer.write_ptr -= pb->buffer.size;
237}
238
239#define DPRINTF(f, ...) \
240 printf("%.2lu:%.6lu "f, time.tv_sec % 100, time.tv_usec, __VA_ARGS__)
241
242/**
243 * Start playback using buffer position api.
244 * @param pb Playback helper function.
245 */
246static void play(playback_t *pb)
247{
248 assert(pb);
249 assert(pb->device);
250 pb->buffer.write_ptr = pb->buffer.base;
251 printf("Playing: %dHz, %s, %d channel(s).\n", pb->f.sampling_rate,
252 pcm_sample_format_str(pb->f.sample_format), pb->f.channels);
253 useconds_t work_time = 50000; /* 50 ms */
254 bool started = false;
255 size_t pos = 0;
256 struct timeval time = { 0 };
257 getuptime(&time);
258 do {
259 size_t available = buffer_avail(pb, pos);
260 /* Writing might need wrap around the end,
261 * read directly to device buffer */
262 size_t bytes = fread(pb->buffer.write_ptr, sizeof(uint8_t),
263 min(available, buffer_remain(pb)), pb->source);
264 buffer_advance(pb, bytes);
265 DPRINTF("POS %zu: %zu bytes free in buffer, read %zu, wp %zu\n",
266 pos, available, bytes,
267 pb->buffer.write_ptr - pb->buffer.base);
268 available -= bytes;
269
270 /* continue if we wrapped around the end */
271 if (available) {
272 bytes = fread(pb->buffer.write_ptr,
273 sizeof(uint8_t), min(available, buffer_remain(pb)),
274 pb->source);
275 buffer_advance(pb, bytes);
276 DPRINTF("POS %zu: %zu bytes still free in buffer, "
277 "read %zu, wp %zu\n", pos, available, bytes,
278 pb->buffer.write_ptr - pb->buffer.base);
279 available -= bytes;
280 }
281
282 if (!started) {
283 int ret = audio_pcm_start_playback(pb->device,
284 pb->f.channels, pb->f.sampling_rate,
285 pb->f.sample_format);
286 if (ret != EOK) {
287 printf("Failed to start playback\n");
288 return;
289 }
290 started = true;
291 ret = audio_pcm_get_buffer_pos(pb->device, &pos);
292 if (ret != EOK) {
293 printf("Failed to update position indicator\n");
294 }
295 }
296 const size_t to_play = buffer_occupied(pb, pos);
297 const useconds_t usecs =
298 pcm_format_size_to_usec(to_play, &pb->f);
299
300 /* Compute delay time */
301 const useconds_t real_delay = (usecs > work_time)
302 ? usecs - work_time : 0;
303 DPRINTF("POS %zu: %u usecs (%u) to play %zu bytes.\n",
304 pos, usecs, real_delay, to_play);
305 if (real_delay)
306 async_usleep(real_delay);
307 /* update buffer position */
308 const int ret = audio_pcm_get_buffer_pos(pb->device, &pos);
309 if (ret != EOK) {
310 printf("Failed to update position indicator\n");
311 }
312 getuptime(&time);
313
314 /* we did not use all the space we had,
315 * that is the end */
316 if (available)
317 break;
318
319 } while (1);
320 audio_pcm_stop_playback_immediate(pb->device);
321}
322
323/**
324 * Play audio file usign direct device access.
325 * @param device The device.
326 * @param file The file.
327 * @return Error code.
328 */
329int dplay(const char *device, const char *file)
330{
331 int ret = EOK;
332 audio_pcm_sess_t *session = NULL;
333 if (str_cmp(device, "default") == 0) {
334 session = audio_pcm_open_default();
335 } else {
336 session = audio_pcm_open(device);
337 }
338 if (!session) {
339 printf("Failed to connect to device %s.\n", device);
340 return 1;
341 }
342 printf("Playing on device: %s.\n", device);
343 if (audio_pcm_query_cap(session, AUDIO_CAP_PLAYBACK) <= 0) {
344 printf("Device %s does not support playback\n", device);
345 ret = ENOTSUP;
346 goto close_session;
347 }
348
349 const char* info = NULL;
350 ret = audio_pcm_get_info_str(session, &info);
351 if (ret != EOK) {
352 printf("Failed to get PCM info.\n");
353 goto close_session;
354 }
355 printf("Playing on %s.\n", info);
356 free(info);
357
358 playback_t pb;
359 playback_initialize(&pb, session);
360
361 ret = audio_pcm_get_buffer(pb.device, &pb.buffer.base, &pb.buffer.size);
362 if (ret != EOK) {
363 printf("Failed to get PCM buffer: %s.\n", str_error(ret));
364 goto close_session;
365 }
366 printf("Buffer: %p %zu.\n", pb.buffer.base, pb.buffer.size);
367
368 pb.source = fopen(file, "rb");
369 if (pb.source == NULL) {
370 ret = ENOENT;
371 printf("Failed to open file: %s.\n", file);
372 goto cleanup;
373 }
374
375 wave_header_t header;
376 fread(&header, sizeof(header), 1, pb.source);
377 const char *error;
378 ret = wav_parse_header(&header, NULL, NULL,
379 &pb.f.channels, &pb.f.sampling_rate, &pb.f.sample_format, &error);
380 if (ret != EOK) {
381 printf("Error parsing wav header: %s.\n", error);
382 goto cleanup;
383 }
384 if (audio_pcm_query_cap(pb.device, AUDIO_CAP_BUFFER_POS) > 0) {
385 play(&pb);
386 } else {
387 if (audio_pcm_query_cap(pb.device, AUDIO_CAP_INTERRUPT) > 0)
388 play_fragment(&pb);
389 else
390 printf("Neither playing method is supported");
391 }
392
393cleanup:
394 fclose(pb.source);
395 munmap(pb.buffer.base, pb.buffer.size);
396 audio_pcm_release_buffer(pb.device);
397close_session:
398 audio_pcm_close(session);
399 return ret == EOK ? 0 : 1;
400}
401/**
402 * @}
403 */
Note: See TracBrowser for help on using the repository browser.