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/types.h>
18 #include <sys/queue.h>
19 #include <sys/uio.h>
21 #include <err.h>
22 #include <event.h>
23 #include <fcntl.h>
24 #include <math.h>
25 #include <inttypes.h>
26 #include <sndio.h>
27 #include <stdio.h>
28 #include <stdint.h>
29 #include <imsg.h>
30 #include <unistd.h>
32 #include <opusfile.h>
34 #include "amused.h"
36 #ifndef nitems
37 #define nitems(x) (sizeof(x)/sizeof(x[0]))
38 #endif
40 void
41 play_opus(int fd)
42 {
43 static uint16_t pcm[BUFSIZ];
44 static uint8_t out[BUFSIZ * 2];
45 OggOpusFile *of;
46 void *f;
47 int ret;
48 OpusFileCallbacks cb = {NULL, NULL, NULL, NULL};
49 int i, li, prev_li = -1;
51 if ((f = op_fdopen(&cb, fd, "r")) == NULL)
52 err(1, "fdopen");
54 of = op_open_callbacks(f, &cb, NULL, 0, &ret);
55 if (of == NULL)
56 errx(1, "failed open opus file");
58 for (;;) {
59 if (player_shouldstop())
60 break;
62 ret = op_read_stereo(of, pcm, nitems(pcm));
63 if (ret == OP_HOLE) /* corrupt file segment? */
64 continue;
65 if (ret < 0)
66 errx(1, "error decoding file (%d)", ret);
67 if (ret == 0)
68 break; /* eof */
70 li = op_current_link(of);
71 if (li != prev_li) {
72 const OpusHead *head;
74 prev_li = li;
76 head = op_head(of, li);
77 if (head->input_sample_rate) {
78 if (player_setrate(head->input_sample_rate)
79 == -1)
80 err(1, "player_setrate");
81 }
82 }
84 for (i = 0; i < 2*ret; ++i) {
85 out[2*i+0] = pcm[i] & 0xFF;
86 out[2*i+1] = (pcm[i] >> 8) & 0xFF;
87 }
88 sio_write(hdl, out, 4*ret);
89 }
91 op_free(of);
92 }