Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/mman.h>
18 #include <sys/stat.h>
19 #include <sys/types.h>
20 #include <sys/queue.h>
21 #include <sys/uio.h>
23 #include <err.h>
24 #include <event.h>
25 #include <limits.h>
26 #include <sndio.h>
27 #include <imsg.h>
28 #include <unistd.h>
30 #include <mpg123.h>
32 #include "amused.h"
33 #include "log.h"
35 static int
36 setup(mpg123_handle *mh)
37 {
38 long rate;
39 int chan, enc;
41 if (mpg123_getformat(mh, &rate, &chan, &enc) != MPG123_OK) {
42 log_warnx("mpg123_getformat failed");
43 return 0;
44 }
46 if (player_setup(mpg123_encsize(enc) * 8, rate, chan) == -1)
47 err(1, "player_setrate");
49 return 1;
50 }
52 void
53 play_mp3(int fd)
54 {
55 static char buf[4096];
56 size_t len;
57 mpg123_handle *mh;
58 int err;
60 if ((mh = mpg123_new(NULL, NULL)) == NULL)
61 fatal("mpg123_new");
63 if (mpg123_open_fd(mh, fd) != MPG123_OK) {
64 log_warnx("mpg123_open_fd failed");
65 close(fd);
66 return;
67 }
69 if (!setup(mh))
70 goto done;
72 for (;;) {
73 if (player_shouldstop())
74 break;
76 err = mpg123_read(mh, buf, sizeof(buf), &len);
77 switch (err) {
78 case MPG123_DONE:
79 goto done;
80 case MPG123_NEW_FORMAT:
81 if (!setup(mh))
82 goto done;
83 break;
84 case MPG123_OK:
85 sio_write(hdl, buf, len);
86 break;
87 default:
88 log_warnx("error %d decoding mp3", err);
89 goto done;
90 }
91 }
93 done:
94 mpg123_delete(mh);
95 close(fd);
96 }