Merge branch 'ipc'
[paraslash.git] / play.c
1 /*
2  * Copyright (C) 2005-2006 Andre Noll <maan@systemlinux.org>
3  *
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  *
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  *
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 /*
20  * Based in parts on aplay.c from the alsa-utils-1.0.8 package,
21  * Copyright (c) by Jaroslav Kysela <perex@suse.cz>, which is
22  * based on the vplay program by Michael Beck.
23  */
24
25 #define BUFFER_SIZE 1000 * 1000
26 #define WAV_HEADER_LEN 44
27 #include <sys/time.h> /* gettimeofday */
28 #include "para.h"
29 #include "play.cmdline.h"
30 #include <alsa/asoundlib.h>
31
32 enum {  E_BROKEN_CONF,          /* Broken configuration for this PCM */
33         E_ACCESS_TYPE,          /* Access type not available */
34         E_SAMPLE_FORMAT,        /* Sample format not available */
35         E_CHANNEL_COUNT,        /* Channels count not available */
36         E_HW_PARAMS,            /* Unable to install hw params */
37         E_SW_PARAMS,            /* Unable to install sw params */
38         E_BAD_PERIOD,           /* Can't use period equal to buffer size */
39         E_GET_XFER,             /* Unable to obtain xfer align */
40         E_SET_XFER,             /* snd_pcm_sw_params_set_xfer_align failed */
41         E_MEM,                  /* not enough memory */
42         E_READ,                 /* read error */
43         E_WRITE,                /* write error */
44         E_PIPE,                 /* write to pipe with other side closed */
45         E_PCM_OPEN,             /* unable to open pcm */
46         E_SND_PCM_INFO,         /* pcm info error */
47         E_GET_BUFFER_TIME,      /* snd_pcm_hw_params_get_buffer_time_max failed */
48         E_SET_BUFFER_TIME,      /* snd_pcm_hw_params_set_buffer_time_near failed */
49         E_SET_RATE,             /* snd_pcm_hw_params_set_rate_near failed */
50         E_START_THRESHOLD,      /* snd_pcm_sw_params_set_start_threshold failed */
51         E_STOP_THRESHOLD,       /* snd_pcm_sw_params_set_stop_threshold failed */
52         E_LOG,                  /* snd_output_stdio_attach failed */
53         E_SYNTAX                /* could not parse start_time option */
54 };
55
56 #define FORMAT SND_PCM_FORMAT_S16_LE
57
58 #define EXIT(EXP) \
59 do { if (EXP) \
60         fprintf (stderr, "error: " #EXP "\n"); exit(EXP);} \
61 while (0)
62
63 static snd_pcm_t *handle;
64 static unsigned char *audiobuf;
65 static snd_pcm_uframes_t chunk_size;
66 static size_t bytes_per_frame;
67 static struct timeval *start_time;
68 static struct gengetopt_args_info conf;
69
70 /*
71  * read_wav_header - read WAV_HEADER_LEN bytes from stdin to audio buffer
72  *
73  * Exit on errors and on eof before WAV_HEADER_LEN could be read.
74  */
75 static void read_wav_header(void)
76 {
77         ssize_t ret, count = 0;
78
79         while (count < WAV_HEADER_LEN) {
80                 ret = read(STDIN_FILENO, audiobuf + count, WAV_HEADER_LEN - count);
81                 if (ret <= 0)
82                         EXIT(E_READ);
83                 count += ret;
84         }
85 }
86
87 /*
88  * set_alsa_params - Prepare the PCM handle for writing
89  *
90  * Install PCM software and hardware configuration. Exit on errors.
91  */
92 static void set_alsa_params(void)
93 {
94         snd_pcm_hw_params_t *hwparams;
95         snd_pcm_sw_params_t *swparams;
96         snd_pcm_uframes_t buffer_size, xfer_align, start_threshold,
97                 stop_threshold;
98         unsigned buffer_time = 0;
99         int err;
100
101         snd_pcm_hw_params_alloca(&hwparams);
102         snd_pcm_sw_params_alloca(&swparams);
103         if (snd_pcm_hw_params_any(handle, hwparams) < 0)
104                 EXIT(E_BROKEN_CONF);
105         if (snd_pcm_hw_params_set_access(handle, hwparams,
106                         SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
107                 EXIT(E_ACCESS_TYPE);
108         if (snd_pcm_hw_params_set_format(handle, hwparams, FORMAT) < 0)
109                 EXIT(E_SAMPLE_FORMAT);
110         if (snd_pcm_hw_params_set_channels(handle, hwparams, conf.channels_arg) < 0)
111                 EXIT(E_CHANNEL_COUNT);
112         if (snd_pcm_hw_params_set_rate_near(handle, hwparams, (unsigned int*) &conf.sample_rate_arg, 0) < 0)
113                 EXIT(E_SET_RATE);
114         err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time, 0);
115         if (err < 0 || !buffer_time)
116                 EXIT(E_GET_BUFFER_TIME);
117         if (buffer_time > 500000)
118                 buffer_time = 500000;
119         if (snd_pcm_hw_params_set_buffer_time_near(handle, hwparams,
120                         &buffer_time, 0) < 0)
121                 EXIT(E_SET_BUFFER_TIME);
122         if (snd_pcm_hw_params(handle, hwparams) < 0)
123                 EXIT(E_HW_PARAMS);
124         snd_pcm_hw_params_get_period_size(hwparams, &chunk_size, 0);
125         snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size);
126         if (chunk_size == buffer_size)
127                 EXIT(E_BAD_PERIOD);
128         snd_pcm_sw_params_current(handle, swparams);
129         err = snd_pcm_sw_params_get_xfer_align(swparams, &xfer_align);
130         if (err < 0 || !xfer_align)
131                 EXIT(E_GET_XFER);
132         snd_pcm_sw_params_set_sleep_min(handle, swparams, 0);
133         snd_pcm_sw_params_set_avail_min(handle, swparams, chunk_size);
134         /* round to closest transfer boundary */
135         start_threshold = (buffer_size / xfer_align) * xfer_align;
136         if (start_threshold < 1)
137                 start_threshold = 1;
138         if (snd_pcm_sw_params_set_start_threshold(handle, swparams,
139                         start_threshold) < 0)
140                 EXIT(E_START_THRESHOLD);
141         stop_threshold = buffer_size;
142         if (snd_pcm_sw_params_set_stop_threshold(handle, swparams,
143                         stop_threshold) < 0)
144                 EXIT(E_STOP_THRESHOLD);
145         if (snd_pcm_sw_params_set_xfer_align(handle, swparams, xfer_align) < 0)
146                 EXIT(E_SET_XFER);
147         if (snd_pcm_sw_params(handle, swparams) < 0)
148                 EXIT(E_SW_PARAMS);
149         bytes_per_frame = snd_pcm_format_physical_width(FORMAT) * conf.channels_arg / 8;
150 }
151
152 /*
153  * pcm_write - push out pcm frames
154  * @data: pointer do data to be written
155  * @count: number of frames
156  *
157  * Return value: Number of bytes written. Exit on errors.
158  */
159 static snd_pcm_sframes_t pcm_write(u_char *data, size_t count)
160 {
161         snd_pcm_sframes_t r, result = 0;
162 #if 0
163         if (count < chunk_size) {
164                 snd_pcm_format_set_silence(FORMAT, data
165                         + count * bytes_per_frame,
166                         (chunk_size - count) * conf.channels_arg);
167                 count = chunk_size;
168         }
169 #endif
170         while (count > 0) {
171                 /* write interleaved frames */
172                 r = snd_pcm_writei(handle, data, count);
173                 if (r == -EAGAIN || (r >= 0 && r < count))
174                         snd_pcm_wait(handle, 1);
175                 else if (r == -EPIPE)
176                         snd_pcm_prepare(handle);
177                 else if (r < 0)
178                         EXIT(E_WRITE);
179                 if (r > 0) {
180                         result += r;
181                         count -= r;
182                         data += r * bytes_per_frame;
183                 }
184         }
185         return result;
186 }
187
188 /*
189  * start_time_in_future - check if current time is later than start_time
190  * @diff: pointer to write remaining time to
191  *
192  * If start_time was not given, or current time is later than given
193  * start_time, return 0. Otherwise, return 1 and write the time
194  * difference between current time and start_time to diff. diff may be
195  * NULL.
196  *
197  */
198 static int start_time_in_future(struct timeval *diff)
199 {
200         struct timeval now;
201
202         if (!conf.start_time_given)
203                 return 0;
204         gettimeofday(&now, NULL);
205         return tv_diff(start_time, &now, diff) > 0? 1 : 0;
206 }
207
208 /*
209  * do_initial_delay - sleep until time given at command line
210  *
211  * This is called if the initial buffer is filled. It returns
212  * immediately if no start_time was given at the command line
213  * or if the given start time is in the past.
214  *
215  */
216 static void do_initial_delay(void)
217 {
218         struct timeval diff;
219         int ret;
220
221         fprintf(stderr, "initial delay\n");
222         if (!conf.start_time_given)
223                 return;
224 again:
225         if (!start_time_in_future(&diff))
226                 return;
227         ret = select(1, NULL, NULL, NULL, &diff);
228         if (ret < 0 && errno == EINTR)
229                 goto again;
230 }
231
232
233 /*
234  * play_pcm - play raw pcm data
235  * @l: number of bytes already loaded
236  *
237  * If start_time was given, prebuffer data until buffer is full or
238  * start_time is reached. In any case, do not start playing before
239  * start_time.
240  */
241 static void play_pcm(size_t l)
242 {
243         ssize_t r, w;
244         unsigned long written = 0;
245         size_t chunk_bytes;
246
247         set_alsa_params();
248         chunk_bytes = chunk_size * bytes_per_frame;
249         audiobuf = realloc(audiobuf, BUFFER_SIZE);
250 //      fprintf(stderr, "loaded: %d, chunk_bytes: %d\n", l, chunk_bytes);
251         if (!audiobuf)
252                 EXIT(E_MEM);
253         for (;;) {
254                 for (;;) {
255                         if (l >= chunk_bytes) {
256                                 if (written)
257                                         break;
258                                 if (!start_time)
259                                         break;
260                                 if (!start_time_in_future(NULL))
261                                         break;
262                                 if (l > BUFFER_SIZE) {
263                                         do_initial_delay();
264                                         break;
265                                 }
266                         }
267 //                      fprintf(stderr, "l = %d, chunk_Bytes = %d\n", l, chunk_bytes);
268                         r = read(STDIN_FILENO, audiobuf + l, BUFFER_SIZE -l);
269                         if (r < 0)
270                                 EXIT(E_READ);
271                         l += r;
272 //                      fprintf(stderr, "loaded: %d, r= %d\n", l, r);
273                         if (!r)
274                                 goto out;;
275                 }
276                 w = MIN(chunk_bytes, l);
277 //              fprintf(stderr, "play: writing %d\n", w);
278                 r = (ssize_t) pcm_write(audiobuf, w / bytes_per_frame) * bytes_per_frame;
279 //              fprintf(stderr, "wrote %d\n", r);
280                 if (r < 0)
281                         EXIT(E_WRITE);
282                 written += r;
283                 l -= r;
284                 if (l)
285                         memmove(audiobuf, audiobuf + r, l);
286 //              fprintf(stderr, "written %lu, loaded : %d\n", written, l);
287         }
288 out:
289         snd_pcm_drain(handle);
290 }
291
292 /*
293  * check_wave - test if audio buffer contains a valid wave header
294  *
295  * If not, return 0, otherwise, store number of channels and sample rate
296  * in struct conf and return WAV_HEADER_LEN.
297  */
298 static size_t check_wave(void)
299 {
300         unsigned char *a = audiobuf;
301         if (a[0] != 'R' || a[1] != 'I' || a[2] != 'F' || a[3] != 'F')
302                 return WAV_HEADER_LEN;
303         conf.channels_arg = (unsigned) a[22];
304         conf.sample_rate_arg = a[24] + (a[25] << 8) + (a[26] << 16) + (a[27] << 24);
305 //      fprintf(stderr, "channels: %d, rate: %d\n", conf.channels_arg,
306 //              conf.sample_rate_arg);
307         return 0;
308 }
309
310 int main(int argc, char *argv[])
311 {
312         snd_pcm_info_t *info;
313         snd_output_t *log;
314         struct timeval tv;
315         int err;
316
317         cmdline_parser(argc, argv, &conf);
318         if (conf.start_time_given) {
319                 if (sscanf(conf.start_time_arg, "%lu:%lu",
320                                 &tv.tv_sec, &tv.tv_usec) != 2)
321                         EXIT(E_SYNTAX);
322                 start_time = &tv;
323         }
324 //      fprintf(stderr, "argc=%d, argv[1]=%s\n",argc,  argv[1]);
325         snd_pcm_info_alloca(&info);
326         if (snd_output_stdio_attach(&log, stderr, 0) < 0)
327                 EXIT(E_LOG);
328         err = snd_pcm_open(&handle, "plug:swmix",
329                 SND_PCM_STREAM_PLAYBACK, 0);
330         if (err < 0)
331                 EXIT(E_PCM_OPEN);
332         if ((err = snd_pcm_info(handle, info)) < 0)
333                 EXIT(E_SND_PCM_INFO);
334         audiobuf = malloc(WAV_HEADER_LEN);
335         read_wav_header();
336         play_pcm(check_wave());
337         snd_pcm_close(handle);
338         free(audiobuf);
339         snd_output_close(log);
340         snd_config_update_free_global();
341         return EXIT_SUCCESS;
342 }