2 * This file is part of DisOrder
3 * Copyright (C) 2008 Richard Kettlewell
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21 * @brief Random track chooser
23 * Picks a track at random and writes it to standard output. If for
24 * any reason no track can be picked - even a trivial reason like a
25 * deadlock - it just exits and expects the server to try again.
37 #include <sys/types.h>
45 #include "configuration.h"
53 #include "trackdb-int.h"
55 #include "trackname.h"
57 #include "server-queue.h"
59 static DB_TXN *global_tid;
61 static const struct option options[] = {
62 { "help", no_argument, 0, 'h' },
63 { "version", no_argument, 0, 'V' },
64 { "config", required_argument, 0, 'c' },
65 { "debug", no_argument, 0, 'd' },
66 { "no-debug", no_argument, 0, 'D' },
67 { "syslog", no_argument, 0, 's' },
68 { "no-syslog", no_argument, 0, 'S' },
72 /* display usage message and terminate */
73 static void help(void) {
75 " disorder-choose [OPTIONS]\n"
77 " --help, -h Display usage message\n"
78 " --version, -V Display version number\n"
79 " --config PATH, -c PATH Set configuration file\n"
80 " --debug, -d Turn on debugging\n"
81 " --[no-]syslog Enable/disable logging to syslog\n"
83 "Track choose for DisOrder. Not intended to be run\n"
89 /** @brief Weighted track record */
90 struct weighted_track {
91 /** @brief Next track in the list */
92 struct weighted_track *next;
93 /** @brief Track name */
95 /** @brief Weight for this track (always positive) */
99 /** @brief List of tracks with nonzero weight */
100 static struct weighted_track *tracks;
102 /** @brief Sum of all weights */
103 static unsigned long long total_weight;
105 /** @brief Count of tracks */
108 static char **required_tags;
109 static char **prohibited_tags;
111 static int queue_contains(const struct queue_entry *head,
113 const struct queue_entry *q;
115 for(q = head->next; q != head; q = q->next)
116 if(!strcmp(q->track, track))
121 /** @brief Compute the weight of a track
122 * @param track Track name (UTF-8)
123 * @param data Track data
124 * @param prefs Track preferences
125 * @return Track weight (non-negative)
127 * Tracks to be excluded entirely are given a weight of 0.
129 static unsigned long compute_weight(const char *track,
136 /* Reject tracks not in any collection (race between edit config and
138 if(!find_track_root(track)) {
139 info("found track not in any collection: %s", track);
143 /* Reject aliases to avoid giving aliased tracks extra weight */
144 if(kvp_get(data, "_alias_for"))
147 /* Reject tracks with random play disabled */
148 if((s = kvp_get(prefs, "pick_at_random"))
152 /* Reject tracks played within the last 8 hours */
153 if((s = kvp_get(prefs, "played_time"))) {
156 if(now < last + config->replay_min)
160 /* Reject tracks currently in the queue or in the recent list */
161 if(queue_contains(&qhead, track)
162 || queue_contains(&phead, track))
165 /* We'll need tags for a number of things */
166 track_tags = parsetags(kvp_get(prefs, "tags"));
168 /* Reject tracks with prohibited tags */
169 if(prohibited_tags && tag_intersection(track_tags, prohibited_tags))
172 /* Reject tracks that lack required tags */
173 if(*required_tags && !tag_intersection(track_tags, required_tags))
176 /* Use the configured weight if available */
177 if((s = kvp_get(prefs, "weight"))) {
181 n = strtol(s, 0, 10);
182 if((errno == 0 || errno == ERANGE) && n >= 0)
189 /** @brief Called for each track */
190 static int collect_tracks_callback(const char *track,
193 void attribute((unused)) *u,
194 DB_TXN attribute((unused)) *tid) {
195 unsigned long weight = compute_weight(track, data, prefs);
198 struct weighted_track *const t = xmalloc(sizeof *t);
200 /* Clamp weight so that we can fit in billions of tracks when we do
201 * arithmetic in long long */
202 if(weight > 0x7fffffff)
208 total_weight += weight;
214 /** @brief Pick a random integer uniformly from [0, limit) */
215 static unsigned long long pick_weight(unsigned long long limit) {
216 unsigned long long n;
221 if((fd = open("/dev/urandom", O_RDONLY)) < 0)
222 fatal(errno, "opening /dev/urandom");
224 if((r = read(fd, &n, sizeof n)) < 0)
225 fatal(errno, "reading /dev/urandom");
226 if((size_t)r < sizeof n)
227 fatal(0, "short read from /dev/urandom");
231 /** @brief Pick a track at random and write it to stdout */
232 static void pick_track(void) {
234 struct weighted_track *t;
236 w = pick_weight(total_weight);
238 while(t && w >= t->weight) {
243 fatal(0, "ran out of tracks but %lld weighting left", w);
244 xprintf("%s", t->track);
247 int main(int argc, char **argv) {
248 int n, logsyslog = !isatty(2), err;
253 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
254 while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
257 case 'V': version("disorder-choose");
258 case 'c': configfile = optarg; break;
259 case 'd': debugging = 1; break;
260 case 'D': debugging = 0; break;
261 case 'S': logsyslog = 0; break;
262 case 's': logsyslog = 1; break;
263 default: fatal(0, "invalid option");
267 openlog(progname, LOG_PID, LOG_DAEMON);
268 log_default = &log_syslog;
270 if(config_read(0)) fatal(0, "cannot read configuration");
271 /* Find out current queue/recent list */
274 /* Generate the candidate track list */
275 trackdb_init(TRACKDB_NO_RECOVER);
276 trackdb_open(TRACKDB_NO_UPGRADE|TRACKDB_READ_ONLY);
277 global_tid = trackdb_begin_transaction();
278 if((err = trackdb_get_global_tid("required-tags", global_tid, &tags)))
279 fatal(0, "error getting required-tags: %s", db_strerror(err));
280 required_tags = parsetags(tags);
281 if((err = trackdb_get_global_tid("prohibited-tags", global_tid, &tags)))
282 fatal(0, "error getting prohibited-tags: %s", db_strerror(err));
283 prohibited_tags = parsetags(tags);
284 if(trackdb_scan(0, collect_tracks_callback, 0, global_tid))
286 trackdb_commit_transaction(global_tid);
289 //info("ntracks=%ld total_weight=%lld", ntracks, total_weight);
291 fatal(0, "no tracks match random choice criteria");