Debian Codegraph @

src/libout123/buffer.c

raw
1 /*
2 buffer.c: output buffer
3
4 copyright 1997-2023 by the mpg123 project - free software under the terms of the LGPL 2.1
5 see COPYING and AUTHORS files in distribution or http://mpg123.org
6 initially written by Oliver Fromme
7
8 I (ThOr) am reviewing this file at about the same daytime as Oliver's timestamp here:
9 Mon Apr 14 03:53:18 MET DST 1997
10 - dammed night coders;-)
11
12 This has been heavily reworked to be barely recognizable for the creation of
13 libout123. There is more structure in the communication, as is necessary if
14 the libout123 functionality is offered via some API to unknown client
15 programs instead of being used from mpg123 alone. The basic idea is the same,
16 the xfermem part only sligthly modified for more synchronization, as I sensed
17 potential deadlocks. --ThOr
18 */
19
20 /*
21 Communication to the buffer is normally via INT123_xfermem_putcmd() and blocking
22 on a response, relying on the buffer process periodically checking for
23 pending commands.
24
25 For more immediate concerns, you can send SIGINT. The only result is that this
26 interrupts a current device writing operation and causes the buffer to wait
27 for a following command.
28 */
29
30 /* Needed for kill() from signal.h. */
31 #define _POSIX_SOURCE
32
33 #include "buffer.h"
34 #include "out123_int.h"
35 #include "xfermem.h"
36 #include <errno.h>
37 #ifdef HAVE_SYS_WAIT_H
38 #include <sys/wait.h>
39 #endif
40 #ifdef HAVE_SIGNAL_H
41 #include <signal.h>
42 #else
43 #ifdef HAVE_SYS_SIGNAL_H
44 #include <sys/signal.h>
45 #endif
46 #endif
47
48 #include "../common/debug.h"
49
50 #define BUF_CMD_OPEN XF_CMD_CUSTOM1
51 #define BUF_CMD_CLOSE XF_CMD_CUSTOM2
52 #define BUF_CMD_START XF_CMD_CUSTOM3
53 #define BUF_CMD_STOP XF_CMD_CUSTOM4
54 #define BUF_CMD_AUDIOCAP XF_CMD_CUSTOM5
55 #define BUF_CMD_PARAM XF_CMD_CUSTOM6
56 #define BUF_CMD_NDRAIN XF_CMD_CUSTOM7
57 #define BUF_CMD_AUDIOFMT XF_CMD_CUSTOM8
58
59 /* TODO: Dynamically allocate that to allow multiple instances. */
60 int outburst = 32768;
61
62 /* This is static and global for the forked buffer process.
63 Another forked buffer process will have its on value. */
64 static int intflag = FALSE;
65
66 static void catch_interrupt (int sig)
67 {
68 intflag = TRUE;
69 }
70
71 static int xfer_write_string(out123_handle *ao, int who, const char *buf);
72 static int xfer_read_string(out123_handle *ao, int who, char **buf);
73 static int read_buf(int fd, void *addr, size_t size, byte *prebuf, int *preoff, int presize);
74 static int read_record(out123_handle *ao
75 , int who, void **buf, byte *prebuf, int *preoff, int presize, size_t *recsize);
76 static int buffer_loop(out123_handle *ao);
77
78 static void catch_child(int sig)
79 {
80 /* Disabled for now. We do not really need that.
81 Rather get return status in a controlled way in INT123_buffer_exit(). */
82 /* while (waitpid(-1, NULL, WNOHANG) > 0); */
83 }
84
85 /*
86 Functions called from the controlling process.
87 */
88
89 /* Start a buffer process. */
90 int INT123_buffer_init(out123_handle *ao, size_t bytes)
91 {
92 INT123_buffer_exit(ao);
93 if(bytes < outburst) bytes = 2*outburst;
94
95 #ifdef DONT_CATCH_SIGNALS
96 #error I really need to catch signals here!
97 #endif
98 INT123_xfermem_init(&ao->buffermem, bytes, 0, 0);
99 /* Is catch_child() really useful? INT123_buffer_exit() does waitpid().
100 And if INT123_buffer_exit() is not called, the main process might be
101 killed off and not be able to run a signal handler anyway. */
102 INT123_catchsignal(SIGCHLD, catch_child);
103 switch((ao->buffer_pid = fork()))
104 {
105 case -1: /* error */
106 if(!AOQUIET)
107 error("cannot fork!");
108 goto buffer_init_bad;
109 case 0: /* child */
110 {
111 int ret;
112 /*
113 Ensure the normal default value for buffer_pid to be able
114 to call normal out123 routines from the buffer proess.
115 One could keep it at zero and even use this for detecting the
116 buffer process and do special stuff for that. But the point
117 is that there shouldn't be special stuff.
118 */
119 ao->buffer_pid = -1;
120 /* Not preparing audio output anymore, that comes later. */
121 INT123_xfermem_init_reader(ao->buffermem);
122 ret = buffer_loop(ao); /* Here the work happens. */
123 xfermem_done_reader(ao->buffermem);
124 INT123_xfermem_done(ao->buffermem);
125 /* Proper cleanup of output handle, including out123_close(). */
126 out123_del(ao);
127 exit(ret);
128 }
129 default: /* parent */
130 {
131 int cmd;
132 INT123_xfermem_init_writer(ao->buffermem);
133 debug("waiting for inital pong from buffer process");
134 if( (cmd=INT123_xfermem_getcmd(ao->buffermem->fd[XF_WRITER], TRUE))
135 != XF_CMD_PONG )
136 {
137 if(!AOQUIET)
138 error2("Got %i instead of expected initial response %i. Killing rogue buffer process."
139 , cmd, XF_CMD_PONG);
140 kill(ao->buffer_pid, SIGKILL);
141 INT123_buffer_exit(ao);
142 return -1;
143 }
144 }
145 }
146
147 return 0;
148 buffer_init_bad:
149 if(ao->buffermem)
150 {
151 INT123_xfermem_done(ao->buffermem);
152 ao->buffermem = NULL;
153 }
154 return -1;
155 }
156
157 /* End a buffer process. */
158 void INT123_buffer_exit(out123_handle *ao)
159 {
160 int status = 0;
161 if(ao->buffer_pid == -1) return;
162
163 debug("ending buffer");
164 INT123_buffer_stop(ao); /* Puts buffer into waiting-for-command mode. */
165 INT123_buffer_end(ao); /* Gives command to end operation. */
166 xfermem_done_writer(ao->buffermem);
167 waitpid(ao->buffer_pid, &status, 0);
168 INT123_xfermem_done(ao->buffermem);
169 ao->buffermem = NULL;
170 ao->buffer_pid = -1;
171 if(WIFEXITED(status))
172 {
173 int ret = WEXITSTATUS(status);
174 if(ret && !AOQUIET)
175 error1("Buffer process isses arose, non-zero return value %i.", ret);
176 }
177 else if(!AOQUIET)
178 error("Buffer process did not exit normally.");
179 }
180
181 /*
182 Communication from writer to reader (buffer process).
183 Remember: The ao struct here is the writer's instance.
184 */
185
186 static int buffer_cmd_finish(out123_handle *ao)
187 {
188 /* Only if buffer returns XF_CMD_OK we got lucky. Otherwise, we expect
189 the buffer to deliver a reason right after XF_CMD_ERROR. */
190 switch(INT123_xfermem_getcmd(ao->buffermem->fd[XF_WRITER], TRUE))
191 {
192 case XF_CMD_OK: return 0;
193 case XF_CMD_ERROR:
194 if(!GOOD_READVAL(ao->buffermem->fd[XF_WRITER], ao->errcode))
195 ao->errcode = OUT123_BUFFER_ERROR;
196 return -1;
197 break;
198 default:
199 ao->errcode = OUT123_BUFFER_ERROR;
200 return -1;
201 }
202 }
203
204 /* Serialization of tunable parameters to communicate them between
205 main process and buffer. Make sure these two stay in sync ... */
206
207 static int write_parameters(out123_handle *ao, int who)
208 {
209 int fd = ao->buffermem->fd[who];
210 if(
211 GOOD_WRITEVAL(fd, ao->flags)
212 && GOOD_WRITEVAL(fd, ao->preload)
213 && GOOD_WRITEVAL(fd, ao->gain)
214 && GOOD_WRITEVAL(fd, ao->device_buffer)
215 && GOOD_WRITEVAL(fd, ao->verbose)
216 && !xfer_write_string(ao, who, ao->name)
217 && !xfer_write_string(ao, who, ao->bindir)
218 )
219 return 0;
220 else
221 return -1;
222 }
223
224 static int read_parameters(out123_handle *ao
225 , int who, byte *prebuf, int *preoff, int presize)
226 {
227 int fd = ao->buffermem->fd[who];
228 #define GOOD_READVAL_BUF(fd, val) \
229 !read_buf(fd, &val, sizeof(val), prebuf, preoff, presize)
230 if(
231 GOOD_READVAL_BUF(fd, ao->flags)
232 && GOOD_READVAL_BUF(fd, ao->preload)
233 && GOOD_READVAL_BUF(fd, ao->gain)
234 && GOOD_READVAL_BUF(fd, ao->device_buffer)
235 && GOOD_READVAL_BUF(fd, ao->verbose)
236 && !read_record(ao, who, (void**)&ao->name, prebuf, preoff, presize, NULL)
237 && !read_record(ao, who, (void**)&ao->bindir, prebuf, preoff, presize, NULL)
238 )
239 return 0;
240 else
241 return -1;
242 #undef GOOD_READVAL_BUF
243 }
244
245 int INT123_buffer_sync_param(out123_handle *ao)
246 {
247 int writerfd = ao->buffermem->fd[XF_WRITER];
248 if(INT123_xfermem_putcmd(writerfd, BUF_CMD_PARAM) != 1)
249 {
250 ao->errcode = OUT123_BUFFER_ERROR;
251 return -1;
252 }
253 /* Calling an external serialization routine to avoid forgetting
254 any fresh parameters here. */
255 if(write_parameters(ao, XF_WRITER))
256 {
257 ao->errcode = OUT123_BUFFER_ERROR;
258 return -1;
259 }
260 return buffer_cmd_finish(ao);
261 }
262
263 int INT123_buffer_open(out123_handle *ao, const char* driver, const char* device)
264 {
265 int writerfd = ao->buffermem->fd[XF_WRITER];
266
267 if(INT123_xfermem_putcmd(writerfd, BUF_CMD_OPEN) != 1)
268 {
269 ao->errcode = OUT123_BUFFER_ERROR;
270 return -1;
271 }
272 /* Passing over driver and device name. */
273 if( xfer_write_string(ao, XF_WRITER, driver)
274 || xfer_write_string(ao, XF_WRITER, device) )
275 {
276 ao->errcode = OUT123_BUFFER_ERROR;
277 return -1;
278 }
279
280 if(buffer_cmd_finish(ao) == 0)
281 /* Retrieve driver and device name. */
282 return ( xfer_read_string(ao, XF_WRITER, &ao->driver)
283 || xfer_read_string(ao, XF_WRITER, &ao->device)
284 || xfer_read_string(ao, XF_WRITER, &ao->realname)
285 || !GOOD_READVAL(writerfd, ao->propflags) );
286 else
287 return -1;
288 }
289
290 int INT123_buffer_encodings(out123_handle *ao)
291 {
292 int writerfd = ao->buffermem->fd[XF_WRITER];
293
294 if(INT123_xfermem_putcmd(writerfd, BUF_CMD_AUDIOCAP) != 1)
295 {
296 ao->errcode = OUT123_BUFFER_ERROR;
297 return -1;
298 }
299 /* Now shoving over the parameters for opening the device. */
300 if(
301 !GOOD_WRITEVAL(writerfd, ao->channels)
302 || !GOOD_WRITEVAL(writerfd, ao->rate)
303 )
304 {
305 ao->errcode = OUT123_BUFFER_ERROR;
306 return -1;
307 }
308
309 if(buffer_cmd_finish(ao) == 0)
310 {
311 int encodings;
312 /* If all good, the answer can be read how. */
313 if(!GOOD_READVAL(writerfd, encodings))
314 {
315 ao->errcode = OUT123_BUFFER_ERROR;
316 return -1;
317 }
318 else return encodings;
319 }
320 else return -1;
321 }
322
323 int INT123_buffer_formats( out123_handle *ao, const long *rates, int ratecount
324 , int minchannels, int maxchannels
325 , struct mpg123_fmt **fmtlist )
326 {
327 int writerfd = ao->buffermem->fd[XF_WRITER];
328 size_t ratesize;
329
330 debug("INT123_buffer_formats");
331
332 if(INT123_xfermem_putcmd(writerfd, BUF_CMD_AUDIOFMT) != 1)
333 {
334 ao->errcode = OUT123_BUFFER_ERROR;
335 return -1;
336 }
337
338 ratesize = ratecount*sizeof(rates);
339
340 if(
341 !GOOD_WRITEVAL(writerfd, maxchannels)
342 || !GOOD_WRITEVAL(writerfd, minchannels)
343 || !GOOD_WRITEVAL(writerfd, ratesize)
344 || !GOOD_WRITEBUF(writerfd, rates, ratesize)
345 ){
346 ao->errcode = OUT123_BUFFER_ERROR;
347 return -1;
348 }
349 if(buffer_cmd_finish(ao) == 0)
350 {
351 int fmtcount;
352 size_t fmtsize;
353 if(
354 !GOOD_READVAL(writerfd, fmtcount)
355 || read_record(ao, XF_WRITER, (void**)fmtlist, NULL, NULL, 0, &fmtsize)
356 ){
357 ao->errcode = OUT123_BUFFER_ERROR;
358 return -1;
359 } else
360 return fmtsize/sizeof(struct mpg123_fmt);
361 }
362 else return -1;
363 }
364
365 int INT123_buffer_start(out123_handle *ao)
366 {
367 int writerfd = ao->buffermem->fd[XF_WRITER];
368 if(INT123_xfermem_putcmd(writerfd, BUF_CMD_START) != 1)
369 {
370 ao->errcode = OUT123_BUFFER_ERROR;
371 return -1;
372 }
373 /* Now shoving over the parameters for opening the device. */
374 if(
375 !GOOD_WRITEVAL(writerfd, ao->format)
376 || !GOOD_WRITEVAL(writerfd, ao->channels)
377 || !GOOD_WRITEVAL(writerfd, ao->rate)
378 )
379 {
380 ao->errcode = OUT123_BUFFER_ERROR;
381 return -1;
382 }
383
384 return buffer_cmd_finish(ao);
385 }
386
387 #define BUFFER_SIMPLE_CONTROL(name, cmd) \
388 void name(out123_handle *ao) \
389 { \
390 INT123_xfermem_putcmd(ao->buffermem->fd[XF_WRITER], cmd); \
391 INT123_xfermem_getcmd(ao->buffermem->fd[XF_WRITER], TRUE); \
392 }
393
394 BUFFER_SIMPLE_CONTROL(INT123_buffer_stop, BUF_CMD_STOP)
395 BUFFER_SIMPLE_CONTROL(INT123_buffer_continue, XF_CMD_CONTINUE)
396 BUFFER_SIMPLE_CONTROL(INT123_buffer_ignore_lowmem, XF_CMD_IGNLOW)
397 BUFFER_SIMPLE_CONTROL(INT123_buffer_drain, XF_CMD_DRAIN)
398 BUFFER_SIMPLE_CONTROL(INT123_buffer_end, XF_CMD_TERMINATE)
399 BUFFER_SIMPLE_CONTROL(INT123_buffer_close, BUF_CMD_CLOSE)
400
401 #define BUFFER_SIGNAL_CONTROL(name, cmd) \
402 void name(out123_handle *ao) \
403 { \
404 kill(ao->buffer_pid, SIGINT); \
405 INT123_xfermem_putcmd(ao->buffermem->fd[XF_WRITER], cmd); \
406 INT123_xfermem_getcmd(ao->buffermem->fd[XF_WRITER], TRUE); \
407 }
408
409 BUFFER_SIGNAL_CONTROL(INT123_buffer_pause, XF_CMD_PAUSE)
410 BUFFER_SIGNAL_CONTROL(INT123_buffer_drop, XF_CMD_DROP)
411
412 size_t INT123_buffer_fill(out123_handle *ao)
413 {
414 return INT123_xfermem_get_usedspace(ao->buffermem);
415 }
416
417 void INT123_buffer_ndrain(out123_handle *ao, size_t bytes)
418 {
419 size_t oldfill;
420 int writerfd = ao->buffermem->fd[XF_WRITER];
421
422 oldfill = INT123_buffer_fill(ao);
423 if(INT123_xfermem_putcmd(writerfd, BUF_CMD_NDRAIN) != 1)
424 {
425 ao->errcode = OUT123_BUFFER_ERROR;
426 return;
427 }
428 /* Now shoving over the parameters for opening the device. */
429 if( !GOOD_WRITEVAL(writerfd, bytes)
430 || !GOOD_WRITEVAL(writerfd, oldfill) )
431 {
432 ao->errcode = OUT123_BUFFER_ERROR;
433 return;
434 }
435
436 buffer_cmd_finish(ao);
437 }
438
439 /* The workhorse: Send data to the buffer with some synchronization and even
440 error checking. */
441 size_t INT123_buffer_write(out123_handle *ao, void *buffer, size_t bytes)
442 {
443 /*
444 Writing the whole buffer in one piece is no good as that means
445 waiting for the buffer being empty. That is called a buffer underrun.
446 We want to refill the buffer before that happens. So, what is sane?
447 */
448 size_t written = 0;
449 size_t max_piece = ao->buffermem->size / 2;
450 while(bytes)
451 {
452 size_t count_piece = bytes > max_piece
453 ? max_piece
454 : bytes;
455 int ret = INT123_xfermem_write(ao->buffermem
456 , (char*)buffer+written, count_piece);
457 if(ret)
458 {
459 if(!AOQUIET)
460 error1("writing to buffer memory failed (%i)", ret);
461 if(ret == XF_CMD_ERROR)
462 {
463 /* Buffer tells me that it has an error waiting. */
464 if(!GOOD_READVAL(ao->buffermem->fd[XF_WRITER], ao->errcode))
465 ao->errcode = OUT123_BUFFER_ERROR;
466 }
467 return 0;
468 }
469 bytes -= count_piece;
470 written += count_piece;
471 }
472 return written;
473 }
474
475
476 /*
477 Code for the buffer process itself.
478 */
479
480 /*
481
482 buffer loop:
483
484 {
485 1. normal operation: get data, feed to audio device
486 (if device open and alive, if data there, if no other command pending)
487 2. command response: pause/unpause, open module/device, query caps
488
489 One command at a time, synchronized ... writer process blocks, waiting for
490 response.
491 }
492
493 */
494
495 /*
496 Fill buffer to that value when starting playback from stopped state or after
497 experiencing a serious underrun.
498 One might also define intermediate preload to recover from underruns. Earlier
499 code used 1/8 of the buffer.
500 */
501 static size_t preload_size(out123_handle *ao)
502 {
503 size_t preload = 0;
504 txfermem *xf = ao->buffermem;
505 /* Fill configured part of buffer on first run before starting to play.
506 * Live mp3 streams constantly approach buffer underrun otherwise. [dk]
507 */
508 if(ao->preload > 0.) preload = (size_t)(ao->preload*xf->size);
509 if(preload > xf->size/2) preload = xf->size/2;
510
511 return preload;
512 }
513
514 /* Play one piece of audio from the buffer after settling preload etc.
515 On error, the device is closed and this naturally stops playback
516 as that depends on ao->state == play_live.
517 This plays _at_ _most_ the given amount of bytes, usually less. */
518 static void buffer_play(out123_handle *ao, size_t bytes)
519 {
520 size_t written;
521 txfermem *xf = ao->buffermem;
522 /* Settle amount of bytes accessible in one block. */
523 if (bytes > xf->size - xf->readindex)
524 bytes = xf->size - xf->readindex;
525 /* Not more than configured output block. */
526 if (bytes > outburst)
527 bytes = outburst;
528 /* The output can only take multiples of framesize. */
529 bytes -= bytes % ao->framesize;
530 /* Actual work by out123_play to ensure logic like automatic continue. */
531 written = out123_play(ao, (unsigned char*)xf->data+xf->readindex, bytes);
532 /* Advance read pointer by the amount of written bytes. */
533 xf->readindex = (xf->readindex + written) % xf->size;
534 /* Detect a fatal error by proxy. */
535 if(ao->errcode == OUT123_DEV_PLAY)
536 out123_close(ao);
537 }
538
539 /* Now I'm getting really paranoid: Helper to skip bytes from command
540 channel if we cannot allocate enough memory to hold the data. */
541 static void skip_bytes(int fd, size_t count)
542 {
543 while(count)
544 {
545 char buf[1024];
546 if(!INT123_unintr_read(fd, buf, (count < sizeof(buf) ? count : sizeof(buf))))
547 return;
548 }
549 }
550
551 /* Write a string to command channel.
552 Return 0 on success, set ao->errcode on issues. */
553 int xfer_write_string(out123_handle *ao, int who, const char *buf)
554 {
555 txfermem *xf = ao->buffermem;
556 int my_fd = xf->fd[who];
557 size_t len;
558
559 /* A NULL string is passed als zero bytes. */
560 len = buf ? (strlen(buf)+1) : 0;
561 if( !GOOD_WRITEVAL(my_fd, len)
562 || !GOOD_WRITEBUF(my_fd, buf, len) )
563 {
564 ao->errcode = OUT123_BUFFER_ERROR;
565 return -1;
566 }
567 return 0;
568 }
569
570
571 static int xfer_read_string(out123_handle *ao, int who, char **buf)
572 {
573 /* ao->errcode set in read_record() */
574 return read_record(ao, who, (void**)buf, NULL, NULL, 0, NULL)
575 ? -1 /* read_record could return 2, normalize to -1 */
576 : 0;
577 }
578
579 /* Read a value from command channel with prebuffer.
580 This assumes responsible use and avoids needless checking of input.
581 And, yes, it modifies the preoff argument!
582 Returns 0 on success, modifies prebuffer fill. */
583 static int read_buf(int fd, void *addr, size_t size, byte *prebuf, int *preoff, int presize)
584 {
585 size_t need = size;
586
587 if(prebuf)
588 {
589 int have = presize - *preoff;
590 if(have > need)
591 have = need;
592 memcpy(addr, prebuf+*preoff, have);
593 *preoff += have;
594 addr = (char*)addr+have;
595 need -= have;
596 }
597 if(need)
598 return !GOOD_READBUF(fd, addr, need);
599 else
600 return 0;
601 }
602
603
604 /* Read a record of unspecified type from command channel.
605 Return 0 on success, set ao->errcode on issues. */
606 static int read_record(out123_handle *ao
607 , int who, void **buf, byte *prebuf, int *preoff, int presize
608 , size_t *reclen)
609 {
610 txfermem *xf = ao->buffermem;
611 int my_fd = xf->fd[who];
612 size_t len;
613
614 if(*buf)
615 free(*buf);
616 *buf = NULL;
617
618 if(read_buf(my_fd, &len, sizeof(len), prebuf, preoff, presize))
619 {
620 ao->errcode = OUT123_BUFFER_ERROR;
621 return 2;
622 }
623 if(reclen)
624 *reclen = len;
625 /* If there is an insane length of given, that shall be handled. */
626 if(len && !(*buf = malloc(len)))
627 {
628 ao->errcode = OUT123_DOOM;
629 skip_bytes(my_fd, len);
630 return -1;
631 }
632 if(read_buf(my_fd, *buf, len, prebuf, preoff, presize))
633 {
634 ao->errcode = OUT123_BUFFER_ERROR;
635 free(*buf);
636 *buf = NULL;
637 return 2;
638 }
639 // If caller is not interested in the length, a zero-terminated string
640 // is assumed. Ensure that zero byte for defense in depth.
641 if(len && !reclen)
642 ((byte*)(*buf))[len-1] = 0;
643 return 0;
644 }
645
646
647 /* The main loop, returns 0 when no issue occured. */
648 int buffer_loop(out123_handle *ao)
649 {
650 txfermem *xf = ao->buffermem;
651 int my_fd = xf->fd[XF_READER];
652 int preloading = FALSE;
653 int draining = FALSE;
654 /* The buffer loop maintains a playback state that can differ from
655 the underlying device's. During prebuffering, the device is paused,
656 but we are playing (as soon as enough data is there, the device is,
657 too). */
658 enum playstate mystate = ao->state;
659
660 ao->flags &= ~OUT123_KEEP_PLAYING; /* No need for that here. */
661 /* Be prepared to use SIGINT for communication. */
662 INT123_catchsignal (SIGINT, catch_interrupt);
663 /* sigprocmask (SIG_SETMASK, oldsigset, NULL); */
664 /* Say hello to the writer. */
665 INT123_xfermem_putcmd(my_fd, XF_CMD_PONG);
666
667 debug1("buffer with preload %g", ao->preload);
668 while(1)
669 {
670 /* If a device is opened and playing, it is our first duty to keep it playing. */
671 if(mystate == play_live)
672 {
673 size_t bytes = INT123_xfermem_get_usedspace(xf);
674 debug4( "Play or preload? Got %zu B / %zu B (%i,%i)."
675 , bytes, preload_size(ao), preloading, draining );
676 if(preloading)
677 preloading = (bytes < preload_size(ao));
678 if(!preloading)
679 {
680 if(!draining && bytes < outburst)
681 preloading = TRUE;
682 else
683 {
684 buffer_play(ao, bytes);
685 mystate = ao->state; /* Maybe changed, must be in sync now. */
686 }
687 }
688 /* Be nice and pause the device on preloading. */
689 if(preloading && ao->state == play_live)
690 out123_pause(ao);
691 }
692 /* Now always check for a pending command, in a blocking way if there is
693 no playback. */
694 debug2("Buffer cmd? (Interruped: %i) (mystate=%i)", intflag, (int)mystate);
695 /*
696 The writer only ever signals before sending a command and also waiting
697 for a response. So, the right place to reset the flag is any time
698 before giving the response. But let's ensure two things:
699 1. The flag really is only cleared when a command response is given.
700 2. Command parsing does not stop until a command demanding a response
701 was handled.
702 */
703 do
704 {
705 /* Getting a whole block of commands to efficiently process those
706 XF_CMD_DATA messages. */
707 byte cmd[100];
708 int cmdcount;
709 int i;
710
711 cmdcount = INT123_xfermem_getcmds( my_fd
712 , (preloading || intflag || (mystate != play_live))
713 , cmd
714 , sizeof(cmd) );
715 if(cmdcount < 0)
716 {
717 if(!AOQUIET)
718 error1("Reading a command set returned %i, my link is broken.", cmdcount);
719 return 1;
720 }
721 #ifdef DEBUG
722 for(i=0; i<cmdcount; ++i)
723 debug2("cmd[%i]=%u", i, cmd[i]);
724 #endif
725 /*
726 These actions should rely heavily on calling the normal out123
727 API functions, just with some parameter passing and error checking
728 wrapped around. If there is much code here, it is wrong.
729 */
730 for(i=0; i<cmdcount;) switch(cmd[i++])
731 {
732 #define GOOD_READVAL_BUF(fd, val) \
733 !read_buf(my_fd, &val, sizeof(val), cmd, &i, cmdcount)
734 case XF_CMD_DATA:
735 debug("got new data");
736 /* Other states should not happen. */
737 if(mystate == play_paused)
738 mystate = play_live;
739 /* When new data arrives, we are obviously not draining. */
740 draining = FALSE;
741 break;
742 case XF_CMD_PING:
743 intflag = FALSE;
744 /* Expecting ping-pong only while playing! Otherwise, the writer
745 could get stuck waiting for free space forever. */
746 if(mystate == play_live)
747 INT123_xfermem_putcmd(my_fd, XF_CMD_PONG);
748 else
749 {
750 INT123_xfermem_putcmd(my_fd, XF_CMD_ERROR);
751 if(ao->errcode == OUT123_OK)
752 ao->errcode = OUT123_NOT_LIVE;
753 if(!GOOD_WRITEVAL(my_fd, ao->errcode))
754 return 2;
755 }
756 break;
757 case BUF_CMD_PARAM:
758 intflag = FALSE;
759 /* If that does not work, communication is broken anyway and
760 writer will notice soon enough. */
761 read_parameters(ao, XF_READER, cmd, &i, cmdcount);
762 ao->flags &= ~OUT123_KEEP_PLAYING; /* No need for that here. */
763 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
764 break;
765 case BUF_CMD_OPEN:
766 {
767 char *driver = NULL;
768 char *device = NULL;
769 int success;
770
771 intflag = FALSE;
772 success = (
773 !read_record( ao, XF_READER, (void**)&driver
774 , cmd, &i, cmdcount, NULL )
775 && !read_record( ao, XF_READER, (void**)&device
776 , cmd, &i, cmdcount, NULL )
777 && !out123_open(ao, driver, device)
778 );
779 free(device);
780 free(driver);
781 draining = FALSE;
782 mystate = ao->state;
783 if(success)
784 {
785 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
786 if( xfer_write_string(ao, XF_READER, ao->driver)
787 || xfer_write_string(ao, XF_READER, ao->device)
788 || xfer_write_string(ao, XF_READER, ao->realname )
789 || !GOOD_WRITEVAL(my_fd, ao->propflags) )
790 return 2;
791 }
792 else
793 {
794 INT123_xfermem_putcmd(my_fd, XF_CMD_ERROR);
795 /* Again, no sense to bitch around about communication errors,
796 just quit. */
797 if(!GOOD_WRITEVAL(my_fd, ao->errcode))
798 return 2;
799 }
800 }
801 break;
802 case BUF_CMD_CLOSE:
803 intflag = FALSE;
804 out123_close(ao);
805 draining = FALSE;
806 mystate = ao->state;
807 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
808 break;
809 case BUF_CMD_AUDIOCAP:
810 {
811 int encodings;
812
813 intflag = FALSE;
814 if(
815 !GOOD_READVAL_BUF(my_fd, ao->channels)
816 || !GOOD_READVAL_BUF(my_fd, ao->rate)
817 )
818 return 2;
819 encodings = out123_encodings(ao, ao->rate, ao->channels);
820 mystate = ao->state;
821 if(encodings >= 0)
822 {
823 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
824 if(!GOOD_WRITEVAL(my_fd, encodings))
825 return 2;
826 }
827 else
828 {
829 INT123_xfermem_putcmd(my_fd, XF_CMD_ERROR);
830 if(!GOOD_WRITEVAL(my_fd, ao->errcode))
831 return 2;
832 }
833 }
834 break;
835 case BUF_CMD_AUDIOFMT:
836 {
837 size_t blocksize;
838 long *rates = NULL;
839 int minchannels;
840 int maxchannels;
841 struct mpg123_fmt *fmtlist;
842 int fmtcount = -1;
843
844 if(
845 !GOOD_READVAL_BUF(my_fd, maxchannels)
846 || !GOOD_READVAL_BUF(my_fd, minchannels)
847 )
848 return 2;
849 if(
850 read_record( ao, XF_READER, (void**)&rates
851 , cmd, &i, cmdcount, &blocksize )
852 ){
853 INT123_xfermem_putcmd(my_fd, XF_CMD_ERROR);
854 if(!GOOD_WRITEVAL(my_fd, ao->errcode))
855 return 2;
856 }
857 fmtcount = out123_formats( ao, rates
858 , (int)(blocksize/sizeof(*rates))
859 , minchannels, maxchannels, &fmtlist );
860 mystate = ao->state;
861 free(rates);
862 if(fmtcount >= 0)
863 {
864 int success;
865
866 blocksize = sizeof(*fmtlist)*fmtcount;
867 debug2("responding with %i formats (block: %zu)", fmtcount, blocksize);
868 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
869 success =
870 GOOD_WRITEVAL(my_fd, fmtcount)
871 && GOOD_WRITEVAL(my_fd, blocksize)
872 && GOOD_WRITEBUF(my_fd, fmtlist, blocksize);
873 free(fmtlist);
874 if(!success)
875 return 2;
876 } else
877 {
878 INT123_xfermem_putcmd(my_fd, XF_CMD_ERROR);
879 if(!GOOD_WRITEVAL(my_fd, ao->errcode))
880 return 2;
881 }
882 }
883 break;
884 case BUF_CMD_START:
885 intflag = FALSE;
886 draining = FALSE;
887 if(
888 !GOOD_READVAL_BUF(my_fd, ao->format)
889 || !GOOD_READVAL_BUF(my_fd, ao->channels)
890 || !GOOD_READVAL_BUF(my_fd, ao->rate)
891 )
892 return 2;
893 if(!out123_start(ao, ao->rate, ao->channels, ao->format))
894 {
895 out123_pause(ao); /* Be nice, start only on buffer_play(). */
896 mystate = play_live;
897 preloading = TRUE;
898 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
899 }
900 else
901 {
902 mystate = ao->state;
903 INT123_xfermem_putcmd(my_fd, XF_CMD_ERROR);
904 if(!GOOD_WRITEVAL(my_fd, ao->errcode))
905 return 2;
906 }
907 break;
908 case BUF_CMD_STOP:
909 intflag = FALSE;
910 if(mystate == play_live)
911 { /* Drain is implied! */
912 size_t bytes;
913 while((bytes = INT123_xfermem_get_usedspace(xf)))
914 buffer_play(ao, bytes);
915 }
916 out123_stop(ao);
917 draining = FALSE;
918 mystate = ao->state;
919 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
920 break;
921 case XF_CMD_CONTINUE:
922 intflag = FALSE;
923 debug("continuing");
924 mystate = play_live; /* We'll get errors reported later if that is not right. */
925 preloading = FALSE; /* It should continue without delay. */
926 draining = FALSE; /* But outburst should be cared for. */
927 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
928 break;
929 case XF_CMD_IGNLOW:
930 intflag = FALSE;
931 preloading = FALSE;
932 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
933 break;
934 case XF_CMD_DRAIN:
935 debug("buffer drain");
936 intflag = FALSE;
937 if(mystate == play_live)
938 {
939 size_t bytes;
940 while(
941 (bytes = INT123_xfermem_get_usedspace(xf))
942 && bytes > ao->framesize
943 )
944 buffer_play(ao, bytes);
945 out123_drain(ao);
946 mystate = ao->state;
947 }
948 draining = FALSE;
949 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
950 break;
951 case BUF_CMD_NDRAIN:
952 {
953 size_t limit;
954 size_t oldfill;
955
956 debug("buffer ndrain");
957 intflag = FALSE;
958 /* Expect further calls to ndrain, avoid prebuffering. */
959 draining = TRUE;
960 preloading = FALSE;
961 if(
962 !GOOD_READVAL_BUF(my_fd, limit)
963 || !GOOD_READVAL_BUF(my_fd, oldfill)
964 )
965 return 2;
966 if(mystate == play_live)
967 {
968 size_t bytes;
969 while(
970 (bytes = INT123_xfermem_get_usedspace(xf))
971 && bytes > ao->framesize
972 && oldfill >= bytes /* paranoia, overflow would handle it anyway */
973 && (oldfill-bytes) < limit
974 )
975 buffer_play(ao, bytes > limit ? limit : bytes);
976 /* Only drain hardware if the end was reached. */
977 if(!INT123_xfermem_get_usedspace(xf))
978 {
979 out123_drain(ao);
980 mystate = ao->state;
981 draining = FALSE;
982 }
983 debug2("buffer drained %zu / %zu", oldfill-bytes, limit);
984 }
985 else
986 debug("drain without playback ... not good");
987 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
988 }
989 break;
990 case XF_CMD_TERMINATE:
991 intflag = FALSE;
992 /* Will that response always reach the writer? Well, at worst,
993 it's an ignored error on INT123_xfermem_getcmd(). */
994 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
995 return 0;
996 case XF_CMD_PAUSE:
997 intflag = FALSE;
998 draining = FALSE;
999 out123_pause(ao);
1000 mystate = ao->state;
1001 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
1002 break;
1003 case XF_CMD_DROP:
1004 intflag = FALSE;
1005 draining = FALSE;
1006 xf->readindex = xf->freeindex;
1007 out123_drop(ao);
1008 INT123_xfermem_putcmd(my_fd, XF_CMD_OK);
1009 break;
1010 default:
1011 if(!AOQUIET)
1012 error1("Unknown command %u encountered. Confused Suicide!", cmd[i]);
1013 return 1;
1014 #undef GOOD_READVAL_BUF
1015 }
1016 } /* Ensure that an interrupt-giving command has been received. */
1017 while(intflag);
1018 if(intflag && !AOQUIET)
1019 error("buffer: The intflag should not be set anymore.");
1020 intflag = FALSE; /* Any possible harm by _not_ ensuring that the flag is cleared here? */
1021 }
1022 }