2 * This file is part of DisOrder
3 * Copyright (C) 2008 Richard Kettlewell
4 * Copyright (C) 2008 Mark Wooding
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22 * @brief Random track chooser
24 * Picks a track at random and writes it to standard output. If for
25 * any reason no track can be picked - even a trivial reason like a
26 * deadlock - it just exits and expects the server to try again.
38 #include <sys/types.h>
46 #include "configuration.h"
54 #include "trackdb-int.h"
56 #include "trackname.h"
58 #include "server-queue.h"
61 #define BASE_WEIGHT 90000
63 static DB_TXN *global_tid;
65 static const struct option options[] = {
66 { "help", no_argument, 0, 'h' },
67 { "version", no_argument, 0, 'V' },
68 { "config", required_argument, 0, 'c' },
69 { "debug", no_argument, 0, 'd' },
70 { "no-debug", no_argument, 0, 'D' },
71 { "syslog", no_argument, 0, 's' },
72 { "no-syslog", no_argument, 0, 'S' },
76 /* display usage message and terminate */
77 static void help(void) {
79 " disorder-choose [OPTIONS]\n"
81 " --help, -h Display usage message\n"
82 " --version, -V Display version number\n"
83 " --config PATH, -c PATH Set configuration file\n"
84 " --debug, -d Turn on debugging\n"
85 " --[no-]syslog Enable/disable logging to syslog\n"
87 "Track choose for DisOrder. Not intended to be run\n"
92 /** @brief Sum of all weights */
93 static unsigned long long total_weight;
95 /** @brief The winning track */
96 static const char *winning = 0;
98 /** @brief Count of tracks */
101 static char **required_tags;
102 static char **prohibited_tags;
104 static int queue_contains(const struct queue_entry *head,
106 const struct queue_entry *q;
108 for(q = head->next; q != head; q = q->next)
109 if(!strcmp(q->track, track))
114 /** @brief Compute the weight of a track
115 * @param track Track name (UTF-8)
116 * @param data Track data
117 * @param prefs Track preferences
118 * @return Track weight (non-negative)
120 * Tracks to be excluded entirely are given a weight of 0.
122 static unsigned long compute_weight(const char *track,
127 time_t last, now = time(0);
129 /* Reject tracks not in any collection (race between edit config and
131 if(!find_track_root(track)) {
132 info("found track not in any collection: %s", track);
136 /* Reject aliases to avoid giving aliased tracks extra weight */
137 if(kvp_get(data, "_alias_for"))
140 /* Reject tracks with random play disabled */
141 if((s = kvp_get(prefs, "pick_at_random"))
145 /* Reject tracks played within the last 8 hours */
146 if((s = kvp_get(prefs, "played_time"))) {
148 if(now < last + config->replay_min)
152 /* Reject tracks currently in the queue or in the recent list */
153 if(queue_contains(&qhead, track)
154 || queue_contains(&phead, track))
157 /* We'll need tags for a number of things */
158 track_tags = parsetags(kvp_get(prefs, "tags"));
160 /* Reject tracks with prohibited tags */
161 if(prohibited_tags && tag_intersection(track_tags, prohibited_tags))
164 /* Reject tracks that lack required tags */
165 if(*required_tags && !tag_intersection(track_tags, required_tags))
168 /* Use the configured weight if available */
169 if((s = kvp_get(prefs, "weight"))) {
173 n = strtol(s, 0, 10);
174 if((errno == 0 || errno == ERANGE) && n >= 0)
178 /* Bias up tracks that were recently added */
179 if((s = kvp_get(data, "_noticed"))) {
180 const time_t noticed = atoll(s);
182 if(noticed + config->new_bias_age < now)
183 /* Currently we just step up the weight of tracks that are in range. A
184 * more sophisticated approach would be to linearly decay from new_bias
185 * down to BASE_WEIGHT over the course of the new_bias_age interval
186 * starting when the track is added. */
187 return config->new_bias;
193 /** @brief Pick a random integer uniformly from [0, limit) */
194 static unsigned long long pick_weight(unsigned long long limit) {
195 unsigned char buf[(sizeof(unsigned long long) * CHAR_BIT + 7)/8], m;
196 unsigned long long t, r, slop;
199 D(("pick_weight: limit = %#016llx", limit));
201 /* First, decide how many bits of output we actually need; do bytes first
202 * (they're quicker) and then bits.
204 * To speed this up, we could use a binary search if we knew where to
205 * start. (Note that shifting by ULLONG_BITS or more (if such a constant
206 * existed) is undefined behaviour, so we mustn't do that.) Figuring out a
207 * start point involves preprocessor and/or autoconf magic.
209 for (nby = 1, t = (limit - 1) >> 8; t; nby++, t >>= 8)
211 nbi = (nby - 1) << 3; t = limit >> nbi;
212 if (t >> 4) { t >>= 4; nbi += 4; }
213 if (t >> 2) { t >>= 2; nbi += 2; }
214 if (t >> 1) { t >>= 1; nbi += 1; }
216 D(("nby = %d; nbi = %d", nby, nbi));
218 /* Main randomness collection loop. We read a number of bytes from the
219 * randomness source, and glue them together into an integer (dropping
220 * bits off the top byte as necessary). Call the result r; we have
221 * 2^{nbi - 1) <= limit < 2^nbi and r < 2^nbi. If r < limit then we win;
222 * otherwise we try again. Given the above bounds, we expect fewer than 2
225 * Unfortunately there are subtleties. In particular, 2^nbi may in fact be
226 * zero due to overflow. So in fact what we do is compute slop = 2^nbi -
227 * limit > 0; if r < slop then we try again, otherwise r - slop is our
230 slop = ((unsigned long long)2 << (nbi - 1)) - limit;
231 m = nbi & 7 ? (1 << (nbi & 7)) - 1 : 0xff;
232 D(("slop = %#016llx", slop));
233 D(("m = 0x%02x", m));
236 /* Actually get some random data. */
237 random_get(buf, nby);
239 /* Clobber the top byte. */
242 /* Turn it into an integer. */
243 for (r = 0, i = 0; i < nby; i++)
244 r = (r << 8) | buf[i];
245 D(("r = %#016llx", r));
248 D((" result=%#016llx", r - slop));
252 /** @brief Called for each track */
253 static int collect_tracks_callback(const char *track,
256 void attribute((unused)) *u,
257 DB_TXN attribute((unused)) *tid) {
258 unsigned long weight = compute_weight(track, data, prefs);
260 /* Decide whether this is the winning track.
262 * Suppose that we have n things, and thing i, for 0 <= i < n, has weight
263 * w_i. Let c_i = w_0 + ... + w_{i-1} be the cumulative weight of the
264 * things previous to thing i, and let W = c_n = w_0 + ... + w_{i-1} be the
265 * total weight. We can clearly choose a random thing with the correct
266 * weightings by picking a random number r in [0, W) and chooeing thing i
267 * where c_i <= r < c_i + w_i. But this involves having an enormous list
268 * and taking two passes over it (which has bad locality and is ugly).
270 * Here's another way. Initialize v = -1. Examine the things in order;
271 * for thing i, choose a random number r_i in [0, c_i + w_i). If r_i < w_i
274 * Claim. For all 0 <= i < n, the above algorithm chooses thing i with
277 * Proof. Induction on n. The claim is clear for n = 1. Suppose it's
278 * true for n - 1. Let L be the event that we choose thing n - 1. Clearly
279 * Pr[L] = w_{n-1}/W. Condition on not-L: then the probabilty that we
280 * choose thing i, for 0 <= i < n - 1, is w_i/c_{n-1} (induction
281 * hypothesis); undoing the conditioning gives the desired result.
283 D(("consider %s", track));
285 total_weight += weight;
286 if (pick_weight(total_weight) < weight)
293 int main(int argc, char **argv) {
294 int n, logsyslog = !isatty(2), err;
299 if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
300 while((n = getopt_long(argc, argv, "hVc:dDSs", options, 0)) >= 0) {
303 case 'V': version("disorder-choose");
304 case 'c': configfile = optarg; break;
305 case 'd': debugging = 1; break;
306 case 'D': debugging = 0; break;
307 case 'S': logsyslog = 0; break;
308 case 's': logsyslog = 1; break;
309 default: fatal(0, "invalid option");
313 openlog(progname, LOG_PID, LOG_DAEMON);
314 log_default = &log_syslog;
316 if(config_read(0)) fatal(0, "cannot read configuration");
317 /* Find out current queue/recent list */
320 /* Generate the candidate track list */
321 trackdb_init(TRACKDB_NO_RECOVER);
322 trackdb_open(TRACKDB_NO_UPGRADE|TRACKDB_READ_ONLY);
323 global_tid = trackdb_begin_transaction();
324 if((err = trackdb_get_global_tid("required-tags", global_tid, &tags)))
325 fatal(0, "error getting required-tags: %s", db_strerror(err));
326 required_tags = parsetags(tags);
327 if((err = trackdb_get_global_tid("prohibited-tags", global_tid, &tags)))
328 fatal(0, "error getting prohibited-tags: %s", db_strerror(err));
329 prohibited_tags = parsetags(tags);
330 if(trackdb_scan(0, collect_tracks_callback, 0, global_tid))
332 trackdb_commit_transaction(global_tid);
335 D(("ntracks=%ld total_weight=%lld", ntracks, total_weight));
337 fatal(0, "no tracks match random choice criteria");
339 fatal(0, "internal: failed to pick a track");
341 xprintf("%s", winning);