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 <limits.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"
35 #include "log.h"
37 #ifndef nitems
38 #define nitems(x) (sizeof(x)/sizeof(x[0]))
39 #endif
41 int
42 play_opus(int fd, const char **errstr)
43 {
44 static uint16_t pcm[BUFSIZ];
45 static uint8_t out[BUFSIZ * 2];
46 OggOpusFile *of;
47 void *f;
48 int64_t seek = -1;
49 int r, ret = 0;
50 OpusFileCallbacks cb = {NULL, NULL, NULL, NULL};
51 int i, li, prev_li = -1, duration_set = 0;
53 if ((f = op_fdopen(&cb, fd, "r")) == NULL)
54 err(1, "fdopen");
56 of = op_open_callbacks(f, &cb, NULL, 0, &r);
57 if (of == NULL) {
58 fclose(f);
59 return -1;
60 }
62 for (;;) {
63 if (seek != -1) {
64 r = op_pcm_seek(of, seek);
65 if (r != 0)
66 break;
67 player_setpos(seek);
68 }
70 /* NB: will downmix multichannels files into two channels */
71 r = op_read_stereo(of, pcm, nitems(pcm));
72 if (r == OP_HOLE) /* corrupt file segment? */
73 continue;
74 if (r < 0) {
75 *errstr = "opus decoding error";
76 ret = -1;
77 break;
78 }
79 if (r == 0)
80 break; /* eof */
82 li = op_current_link(of);
83 if (li != prev_li) {
84 const OpusHead *head;
86 prev_li = li;
87 head = op_head(of, li);
88 if (head->input_sample_rate &&
89 player_setup(16, head->input_sample_rate, 2) == -1)
90 err(1, "player_setup");
92 if (!duration_set) {
93 duration_set = 1;
94 player_setduration(op_pcm_total(of, -1));
95 }
96 }
98 for (i = 0; i < 2*r; ++i) {
99 out[2*i+0] = pcm[i] & 0xFF;
100 out[2*i+1] = (pcm[i] >> 8) & 0xFF;
103 if (!play(out, 4*r, &seek)) {
104 ret = 1;
105 break;
109 op_free(of);
110 return ret;