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 <stdlib.h>
18 #include <syslog.h>
20 #include "log.h"
21 #include "xmalloc.h"
22 #include "playlist.h"
24 #define MAX(a, b) ((a) > (b) ? (a) : (b))
26 struct playlist playlist;
27 enum play_state play_state;
28 int repeat_one;
29 int repeat_all = 1;
30 ssize_t play_off = -1;
32 void
33 playlist_enqueue(const char *path)
34 {
35 size_t newcap;
37 if (playlist.len == playlist.cap) {
38 newcap = MAX(16, playlist.cap * 1.5);
39 playlist.songs = xrecallocarray(playlist.songs, playlist.cap,
40 newcap, sizeof(*playlist.songs));
41 playlist.cap = newcap;
42 }
44 playlist.songs[playlist.len++] = xstrdup(path);
45 }
47 const char *
48 playlist_current(void)
49 {
50 if (playlist.len == 0 || play_off == -1) {
51 play_state = STATE_STOPPED;
52 return NULL;
53 }
55 return playlist.songs[play_off];
56 }
58 const char *
59 playlist_advance(void)
60 {
61 if (playlist.len == 0) {
62 play_state = STATE_STOPPED;
63 return NULL;
64 }
66 play_off++;
67 if (play_off == playlist.len) {
68 if (repeat_all)
69 play_off = 0;
70 else {
71 play_state = STATE_STOPPED;
72 play_off = -1;
73 return NULL;
74 }
75 }
77 play_state = STATE_PLAYING;
78 return playlist.songs[play_off];
79 }
81 void
82 playlist_reset(void)
83 {
84 play_off = -1;
85 }
87 void
88 playlist_truncate(void)
89 {
90 size_t i;
92 for (i = 0; i < playlist.len; ++i)
93 free(playlist.songs[i]);
94 free(playlist.songs);
95 playlist.songs = NULL;
97 playlist.len = 0;
98 playlist.cap = 0;
99 play_off = -1;
102 void
103 playlist_dropcurrent(void)
105 size_t i;
107 if (play_off == -1 || playlist.len == 0)
108 return;
110 free(playlist.songs[play_off]);
112 playlist.len--;
113 for (i = play_off; i < playlist.len; ++i)
114 playlist.songs[i] = playlist.songs[i+1];
116 playlist.songs[playlist.len] = NULL;