2 * Copyright (c) 2022 Omar Polo <op@openbsd.org>
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.
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.
17 #include <sys/types.h>
27 #define MAX(a, b) ((a) > (b) ? (a) : (b))
29 struct playlist playlist;
30 enum play_state play_state;
33 ssize_t play_off = -1;
36 playlist_swap(struct playlist *p)
40 playlist.len = p->len;
41 playlist.cap = p->cap;
42 playlist.songs = p->songs;
46 playlist_push(struct playlist *playlist, const char *path)
50 if (playlist->len == playlist->cap) {
51 newcap = MAX(16, playlist->cap * 1.5);
52 playlist->songs = xrecallocarray(playlist->songs,
53 playlist->cap, newcap, sizeof(*playlist->songs));
54 playlist->cap = newcap;
57 playlist->songs[playlist->len++] = xstrdup(path);
61 playlist_enqueue(const char *path)
63 playlist_push(&playlist, path);
67 playlist_current(void)
69 if (playlist.len == 0 || play_off == -1) {
70 play_state = STATE_STOPPED;
74 return playlist.songs[play_off];
78 playlist_advance(void)
80 if (playlist.len == 0) {
81 play_state = STATE_STOPPED;
86 if (play_off == playlist.len) {
90 play_state = STATE_STOPPED;
96 play_state = STATE_PLAYING;
97 return playlist.songs[play_off];
101 playlist_previous(void)
103 if (playlist.len == 0) {
104 play_state = STATE_STOPPED;
111 play_off = playlist.len - 1;
113 play_state = STATE_STOPPED;
119 play_state = STATE_PLAYING;
120 return playlist.songs[play_off];
130 playlist_free(struct playlist *playlist)
134 for (i = 0; i < playlist->len; ++i)
135 free(playlist->songs[i]);
136 free(playlist->songs);
137 playlist->songs = NULL;
144 playlist_truncate(void)
146 playlist_free(&playlist);
151 playlist_dropcurrent(void)
155 if (play_off == -1 || playlist.len == 0)
158 free(playlist.songs[play_off]);
161 for (i = play_off; i < playlist.len; ++i)
162 playlist.songs[i] = playlist.songs[i+1];
164 playlist.songs[playlist.len] = NULL;
168 playlist_jump(const char *arg)
173 if (regcomp(&re, arg, REG_ICASE | REG_NOSUB) != 0)
176 for (i = 0; i < playlist.len; ++i) {
177 if (regexec(&re, playlist.songs[i], 0, NULL, 0) == 0)
182 if (i == playlist.len)
185 play_state = STATE_PLAYING;
187 return playlist.songs[i];