Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@omarpolo.com>
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"
31 #ifndef nitems
32 #define nitems(x) (sizeof(x)/sizeof(x[0]))
33 #endif
35 int
36 play_opus(int fd, const char **errstr)
37 {
38 static int16_t pcm[BUFSIZ];
39 static uint8_t out[BUFSIZ * 2];
40 OggOpusFile *of;
41 void *f;
42 int64_t seek = -1;
43 int r, ret = 0;
44 OpusFileCallbacks cb = {NULL, NULL, NULL, NULL};
45 int i, li, prev_li = -1, duration_set = 0;
47 if ((f = op_fdopen(&cb, fd, "r")) == NULL) {
48 *errstr = "fdopen failed";
49 close(fd);
50 return -1;
51 }
53 of = op_open_callbacks(f, &cb, NULL, 0, &r);
54 if (of == NULL) {
55 fclose(f);
56 return -1;
57 }
59 for (;;) {
60 if (seek != -1) {
61 r = op_pcm_seek(of, seek);
62 if (r != 0)
63 break;
64 player_setpos(seek);
65 }
67 /* NB: will downmix multichannels files into two channels */
68 r = op_read_stereo(of, pcm, nitems(pcm));
69 if (r == OP_HOLE) /* corrupt file segment? */
70 continue;
71 if (r < 0) {
72 *errstr = "opus decoding error";
73 ret = -1;
74 break;
75 }
76 if (r == 0)
77 break; /* eof */
79 li = op_current_link(of);
80 if (li != prev_li) {
81 const OpusHead *head;
83 prev_li = li;
84 head = op_head(of, li);
85 if (head->input_sample_rate &&
86 player_setup(16, head->input_sample_rate, 2) == -1)
87 err(1, "player_setup");
89 if (!duration_set) {
90 duration_set = 1;
91 player_setduration(op_pcm_total(of, -1));
92 }
93 }
95 for (i = 0; i < 2*r; ++i) {
96 out[2*i+0] = pcm[i] & 0xFF;
97 out[2*i+1] = (pcm[i] >> 8) & 0xFF;
98 }
100 if (!play(out, 4*r, &seek)) {
101 ret = 1;
102 break;
106 op_free(of);
107 return ret;