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 "config.h"
19 #include <fcntl.h>
20 #include <math.h>
21 #include <inttypes.h>
22 #include <limits.h>
23 #include <stdio.h>
24 #include <stdint.h>
25 #include <unistd.h>
27 #include <opusfile.h>
29 #include "amused.h"
30 #include "log.h"
32 #ifndef nitems
33 #define nitems(x) (sizeof(x)/sizeof(x[0]))
34 #endif
36 int
37 play_opus(int fd, const char **errstr)
38 {
39 static int16_t pcm[BUFSIZ];
40 static uint8_t out[BUFSIZ * 2];
41 OggOpusFile *of;
42 void *f;
43 int64_t seek = -1;
44 int r, ret = 0;
45 OpusFileCallbacks cb = {NULL, NULL, NULL, NULL};
46 int i, li, prev_li = -1, duration_set = 0;
48 if ((f = op_fdopen(&cb, fd, "r")) == NULL) {
49 *errstr = "fdopen failed";
50 close(fd);
51 return -1;
52 }
54 of = op_open_callbacks(f, &cb, NULL, 0, &r);
55 if (of == NULL) {
56 fclose(f);
57 return -1;
58 }
60 for (;;) {
61 if (seek != -1) {
62 r = op_pcm_seek(of, seek);
63 if (r != 0)
64 break;
65 player_setpos(seek);
66 }
68 /* NB: will downmix multichannels files into two channels */
69 r = op_read_stereo(of, pcm, nitems(pcm));
70 if (r == OP_HOLE) /* corrupt file segment? */
71 continue;
72 if (r < 0) {
73 *errstr = "opus decoding error";
74 ret = -1;
75 break;
76 }
77 if (r == 0)
78 break; /* eof */
80 li = op_current_link(of);
81 if (li != prev_li) {
82 const OpusHead *head;
84 prev_li = li;
85 head = op_head(of, li);
86 if (head->input_sample_rate &&
87 player_setup(16, head->input_sample_rate, 2) == -1)
88 err(1, "player_setup");
90 if (!duration_set) {
91 duration_set = 1;
92 player_setduration(op_pcm_total(of, -1));
93 }
94 }
96 for (i = 0; i < 2*r; ++i) {
97 out[2*i+0] = pcm[i] & 0xFF;
98 out[2*i+1] = (pcm[i] >> 8) & 0xFF;
99 }
101 if (!play(out, 4*r, &seek)) {
102 ret = 1;
103 break;
107 op_free(of);
108 return ret;