1 /* Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file mood.c Paraslash's mood handling functions. */
18 * Mood parser API. It's overkill to have an own header file for
19 * these declarations as they are only needed in this .c file.
22 int mp_init(const char *definition, int nbytes, struct mp_context **result,
24 bool mp_eval_row(const struct osl_row *aft_row, struct mp_context *ctx);
25 void mp_shutdown(struct mp_context *ctx);
28 * Contains statistical data of the currently admissible audio files.
30 * It is used to assign normalized score values to each admissible audio file.
32 struct afs_statistics {
33 /** Sum of num played over all admissible files. */
34 int64_t num_played_sum;
35 /** Sum of last played times over all admissible files. */
36 int64_t last_played_sum;
37 /** Quadratic deviation of num played count. */
38 int64_t num_played_qd;
39 /** Quadratic deviation of last played time. */
40 int64_t last_played_qd;
41 /** Correction factor for the num played score. */
42 int64_t num_played_correction;
43 /** Correction factor for the last played score. */
44 int64_t last_played_correction;
45 /** Common divisor of the correction factors. */
46 int64_t normalization_divisor;
47 /** Number of admissible files */
50 static struct afs_statistics statistics = {.normalization_divisor = 1};
53 /** The name of this mood. */
55 /** Info for the bison parser. */
56 struct mp_context *parser_context;
60 * If current_mood is NULL then no mood is currently open. If
61 * current_mood->name is NULL, the dummy mood is currently open.
63 static struct mood *current_mood;
66 * Find the position of the most-significant set bit.
68 * Copied and slightly adapted from the linux source tree, version 4.9.39
71 __a_const static uint32_t fls64(uint64_t v)
74 const uint64_t ones = ~(uint64_t)0U;
76 if ((v & (ones << 32)) == 0) {
80 if ((v & (ones << (64 - 16))) == 0) {
84 if ((v & (ones << (64 - 8))) == 0) {
88 if ((v & (ones << (64 - 4))) == 0) {
92 if ((v & (ones << (64 - 2))) == 0) {
96 if ((v & (ones << (64 - 1))) == 0)
102 * Compute the integer square root floor(sqrt(x)).
104 * Taken 2007 from the linux source tree.
106 __a_const static uint64_t int_sqrt(uint64_t x)
108 uint64_t op = x, res = 0, one = 1;
110 one = one << (fls64(x) & ~one);
112 if (op >= res + one) {
113 op = op - (res + one);
122 /* returns 1 if row admissible, 0 if not, negative on errors */
123 static int row_is_admissible(const struct osl_row *aft_row, struct mood *m)
126 return mp_eval_row(aft_row, m->parser_context);
129 static void destroy_mood(struct mood *m)
133 mp_shutdown(m->parser_context);
138 static struct mood *alloc_new_mood(const char *name)
140 struct mood *m = zalloc(sizeof(struct mood));
142 m->name = para_strdup(name);
146 static int load_mood(const struct osl_row *mood_row, struct mood **m,
150 struct osl_object mood_def;
153 ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
156 *errmsg = make_message(
157 "could not read mood definition");
161 *m = alloc_new_mood(mood_name);
162 PARA_INFO_LOG("opening mood %s\n", mood_name);
163 ret = mp_init(mood_def.data, mood_def.size, &(*m)->parser_context, errmsg);
164 osl_close_disk_object(&mood_def);
170 static int check_mood(struct osl_row *mood_row, void *data)
172 struct para_buffer *pb = data;
173 char *mood_name, *errmsg;
174 struct osl_object mood_def;
176 int ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
179 para_printf(pb, "cannot read mood\n");
182 if (!*mood_name) /* ignore dummy row */
184 m = alloc_new_mood("check");
185 ret = mp_init(mood_def.data, mood_def.size, &m->parser_context,
188 para_printf(pb, "%s: %s\n", mood_name, errmsg);
190 para_printf(pb, "%s\n", para_strerror(-ret));
193 ret = 1; /* don't fail the loop on invalid mood definitions */
195 osl_close_disk_object(&mood_def);
200 * Check all moods for syntax errors.
202 * \param aca Only ->pbout is used for diagnostics.
204 * \return Negative on fatal errors. Inconsistent mood definitions are not
205 * considered an error.
207 int mood_check_callback(struct afs_callback_arg *aca)
209 para_printf(&aca->pbout, "checking moods...\n");
210 return osl(osl_rbtree_loop(moods_table, BLOBCOL_ID, &aca->pbout,
215 * The normalized num_played and last_played values are defined as
217 * nn := -(np - mean_n) / sigma_n and nl := -(lp - mean_l) / sigma_l
219 * For a (hypothetical) file with np = 0 and lp = now we thus have
221 * nn = mean_n / sigma_n =: hn > 0
222 * nl = -(now - mean_l) / sigma_l =: hl < 0
224 * We design the score function so that both contributions get the same
225 * weight. Define the np and lp score of an arbitrary file as
227 * sn := nn * -hl and sl := nl * hn
230 * num_played mean/sigma: 87/14
231 * last_played mean/sigma: 45/32 days
233 * We have hn = 87 / 14 = 6.21 and hl = -45 / 32 = -1.41. Multiplying
234 * nn of every file with the correction factor 1.41 and nl with
235 * 6.21 makes the weight of the two contributions equal.
237 * The total score s := sn + sl has the representation
239 * s = -cn * (np - mean_n) - cl * (lp - mean_l)
241 * with positive correction factors
243 * cn = (now - mean_l) / (sqrt(ql) * sqrt(qn) / n)
244 * cl = mean_n / (sqrt(ql) * sqrt(qn) / n)
246 * where ql and qn are the quadratic deviations stored in the statistics
247 * structure and n is the number of admissible files. To avoid integer
248 * overflows and rounding errors we store the common divisor of the
249 * correction factors separately.
251 static int64_t normalized_value(int64_t x, int64_t n, int64_t sum, int64_t qd)
255 return 100 * (n * x - sum) / (int64_t)int_sqrt(n) / (int64_t)int_sqrt(qd);
258 static long compute_score(struct afs_info *afsi)
260 long score = -normalized_value(afsi->num_played, statistics.num,
261 statistics.num_played_sum, statistics.num_played_qd);
262 score -= normalized_value(afsi->last_played, statistics.num,
263 statistics.last_played_sum, statistics.last_played_qd);
267 static int add_afs_statistics(const struct osl_row *row)
270 struct afs_info afsi;
273 ret = get_afsi_of_row(row, &afsi);
277 x = afsi.last_played;
278 s = statistics.last_played_sum;
280 q = (x > s / n)? x - s / n : s / n - x;
281 statistics.last_played_qd += q * q * n / (n + 1);
283 statistics.last_played_sum += x;
286 s = statistics.num_played_sum;
288 q = (x > s / n)? x - s / n : s / n - x;
289 statistics.num_played_qd += q * q * n / (n + 1);
291 statistics.num_played_sum += x;
296 static int del_afs_statistics(const struct osl_row *row)
298 uint64_t n, s, q, a, new_s;
299 struct afs_info afsi;
301 ret = get_afsi_of_row(row, &afsi);
307 memset(&statistics, 0, sizeof(statistics));
308 statistics.normalization_divisor = 1;
312 s = statistics.last_played_sum;
313 q = statistics.last_played_qd;
314 a = afsi.last_played;
316 statistics.last_played_sum = new_s;
317 statistics.last_played_qd = q + s * s / n - a * a
318 - new_s * new_s / (n - 1);
320 s = statistics.num_played_sum;
321 q = statistics.num_played_qd;
324 statistics.num_played_sum = new_s;
325 statistics.num_played_qd = q + s * s / n - a * a
326 - new_s * new_s / (n - 1);
333 * At mood open time we determine the set of admissible files for the given
334 * mood where each file is identified by a pointer to a row of the audio file
335 * table. In the first pass the pointers are added to a temporary array and
336 * statistics are computed. When all admissible files have been processed in
337 * this way, the score of each admissible file is computed and the (row, score)
338 * pair is added to the score table. This has to be done in a second pass
339 * since the score depends on the statistics. Finally, the array is freed.
341 struct admissible_array {
342 /** Files are admissible wrt. this mood. */
344 /** The size of the array */
346 /** Pointer to the array of admissible files. */
347 struct osl_row **array;
351 * Check whether the given audio file is admissible. If it is, add it to array
352 * of admissible files.
354 static int add_if_admissible(struct osl_row *aft_row, void *data)
356 struct admissible_array *aa = data;
359 ret = row_is_admissible(aft_row, aa->m);
362 if (statistics.num >= aa->size) {
365 aa->array = arr_realloc(aa->array, aa->size,
366 sizeof(struct osl_row *));
368 aa->array[statistics.num] = aft_row;
369 return add_afs_statistics(aft_row);
373 * Compute the new quadratic deviation in case one element changes.
375 * \param n Number of elements.
376 * \param old_qd The quadratic deviation before the change.
377 * \param old_val The value that was replaced.
378 * \param new_val The replacement value.
379 * \param old_sum The sum of all elements before the update.
381 * \return The new quadratic deviation resulting from replacing old_val
384 * Given n real numbers a_1, ..., a_n, their sum S = a_1 + ... + a_n,
385 * their quadratic deviation
387 * q = (a_1 - S/n)^2 + ... + (a_n - S/n)^2,
389 * and a real number b, the quadratic deviation q' of a_1,...a_{n-1}, b (ie.
390 * the last number a_n was replaced by b) may be computed in O(1) time in terms
391 * of n, q, a_n, b, and S as
393 * q' = q + d * s - (2 * S + d) * d / n
394 * = q + d * (s - 2 * S / n - d /n),
396 * where d = b - a_n, and s = b + a_n.
398 * Example: n = 3, a_1 = 3, a_2 = 5, a_3 = 7, b = 10. Then S = 15, q = 8, d = 3,
401 * q + d * s - (2 * S + d) * d / n = 8 + 51 - 33 = 26,
403 * which equals q' = (3 - 6)^2 + (5 - 6)^2 + (10 - 6)^2.
406 _static_inline_ int64_t update_quadratic_deviation(int64_t n, int64_t old_qd,
407 int64_t old_val, int64_t new_val, int64_t old_sum)
409 int64_t delta = new_val - old_val;
410 int64_t sigma = new_val + old_val;
411 return old_qd + delta * (sigma - 2 * old_sum / n - delta / n);
414 static int update_afs_statistics(struct afs_info *old_afsi,
415 struct afs_info *new_afsi)
418 int ret = get_num_admissible_files(&n);
424 statistics.last_played_qd = update_quadratic_deviation(n,
425 statistics.last_played_qd, old_afsi->last_played,
426 new_afsi->last_played, statistics.last_played_sum);
427 statistics.last_played_sum += new_afsi->last_played - old_afsi->last_played;
429 statistics.num_played_qd = update_quadratic_deviation(n,
430 statistics.num_played_qd, old_afsi->num_played,
431 new_afsi->num_played, statistics.num_played_sum);
432 statistics.num_played_sum += new_afsi->num_played - old_afsi->num_played;
436 static int add_to_score_table(const struct osl_row *aft_row)
439 struct afs_info afsi;
440 int ret = get_afsi_of_row(aft_row, &afsi);
444 score = compute_score(&afsi);
445 return score_add(aft_row, score);
448 static int delete_from_statistics_and_score_table(const struct osl_row *aft_row)
450 int ret = del_afs_statistics(aft_row);
453 return score_delete(aft_row);
457 * Delete one entry from the statistics and from the score table.
459 * \param aft_row The audio file which is no longer admissible.
461 * \return Positive on success, negative on errors.
463 * \sa \ref score_delete().
465 static int mood_delete_audio_file(const struct osl_row *aft_row)
469 ret = row_belongs_to_score_table(aft_row, NULL);
472 if (!ret) /* not admissible, nothing to do */
474 return delete_from_statistics_and_score_table(aft_row);
478 * Compute the new score of an audio file wrt. the current mood.
480 * \param aft_row Determines the audio file.
481 * \param old_afsi The audio file selector info before updating.
483 * The \a old_afsi argument may be \p NULL which indicates that no changes to
484 * the audio file info were made.
486 * \return Positive on success, negative on errors.
488 static int mood_update_audio_file(const struct osl_row *aft_row,
489 struct afs_info *old_afsi)
492 int ret, is_admissible, was_admissible = 0;
493 struct afs_info afsi;
497 return 1; /* nothing to do */
498 ret = row_belongs_to_score_table(aft_row, &rank);
501 was_admissible = ret;
502 ret = row_is_admissible(aft_row, current_mood);
505 is_admissible = (ret > 0);
506 if (!was_admissible && !is_admissible)
508 if (was_admissible && !is_admissible)
509 return delete_from_statistics_and_score_table(aft_row);
510 if (!was_admissible && is_admissible) {
511 ret = add_afs_statistics(aft_row);
514 return add_to_score_table(aft_row);
517 ret = get_afsi_of_row(aft_row, &afsi);
521 ret = update_afs_statistics(old_afsi, &afsi);
525 score = compute_score(&afsi);
526 PARA_DEBUG_LOG("score: %li\n", score);
527 percent = (score + 100) / 3;
530 else if (percent < 0)
532 PARA_DEBUG_LOG("moving from rank %u to %li%%\n", rank, percent);
533 return score_update(aft_row, percent);
536 /* sse: seconds since epoch. */
537 static void log_statistics(int64_t sse)
539 unsigned n = statistics.num;
540 int mean_days, sigma_days;
542 assert(current_mood);
543 PARA_NOTICE_LOG("loaded mood %s\n", current_mood->name?
544 current_mood->name : "(dummy)");
546 PARA_WARNING_LOG("no admissible files\n");
549 PARA_NOTICE_LOG("%u admissible files\n", statistics.num);
550 mean_days = (sse - statistics.last_played_sum / n) / 3600 / 24;
551 sigma_days = int_sqrt(statistics.last_played_qd / n) / 3600 / 24;
552 PARA_NOTICE_LOG("last_played mean/sigma: %d/%d days\n", mean_days, sigma_days);
553 PARA_NOTICE_LOG("num_played mean/sigma: %" PRId64 "/%" PRIu64 "\n",
554 statistics.num_played_sum / n,
555 int_sqrt(statistics.num_played_qd / n));
556 PARA_NOTICE_LOG("num_played correction factor: %" PRId64 "\n",
557 statistics.num_played_correction);
558 PARA_NOTICE_LOG("last_played correction factor: %" PRId64 "\n",
559 statistics.last_played_correction);
560 PARA_NOTICE_LOG("normalization divisor: %" PRId64 "\n",
561 statistics.normalization_divisor);
565 * Close the current mood.
567 * Frees all resources of the current mood.
569 void close_current_mood(void)
571 destroy_mood(current_mood);
573 memset(&statistics, 0, sizeof(statistics));
574 statistics.normalization_divisor = 1;
577 static void compute_correction_factors(int64_t sse)
579 struct afs_statistics *s = &statistics;
582 s->normalization_divisor = int_sqrt(s->last_played_qd)
583 * int_sqrt(s->num_played_qd) / s->num / 100;
584 s->num_played_correction = sse - s->last_played_sum / s->num;
585 s->last_played_correction = s->num_played_sum / s->num;
587 if (s->num_played_correction == 0)
588 s->num_played_correction = 1;
589 if (s->normalization_divisor == 0)
590 s->normalization_divisor = 1;
591 if (s->last_played_correction == 0)
592 s->last_played_correction = 1;
596 * Change the current mood.
598 * \param mood_name The name of the mood to open.
599 * \param errmsg Error description is returned here.
601 * If \a mood_name is \a NULL, load the dummy mood that accepts every audio file
602 * and uses a scoring method based only on the \a last_played information.
604 * The errmsg pointer may be NULL, in which case no error message will be
605 * returned. If a non-NULL pointer is given, the caller must free *errmsg.
607 * If there is already an open mood, it will be closed first.
609 * \return Positive on success, negative on errors.
611 * \sa struct \ref afs_info::last_played, \ref mp_eval_row().
613 int change_current_mood(const char *mood_name, char **errmsg)
616 struct admissible_array aa = {
621 * We can not use the "now" pointer from sched.c here because we are
622 * called before schedule(), which initializes "now".
629 struct osl_object obj;
632 *errmsg = make_message("empty mood name");
633 return -ERRNO_TO_PARA_ERROR(EINVAL);
635 obj.data = (char *)mood_name;
636 obj.size = strlen(mood_name) + 1;
637 ret = osl(osl_get_row(moods_table, BLOBCOL_NAME, &obj, &row));
640 *errmsg = make_message("no such mood: %s",
644 ret = load_mood(row, &m, errmsg);
647 close_current_mood();
649 } else { /* load dummy mood */
650 close_current_mood();
651 current_mood = alloc_new_mood(NULL);
654 PARA_NOTICE_LOG("computing statistics of admissible files\n");
655 ret = audio_file_loop(&aa, add_if_admissible);
658 *errmsg = make_message("audio file loop failed");
661 clock_get_realtime(&rnow);
662 compute_correction_factors(rnow.tv_sec);
663 log_statistics(rnow.tv_sec);
664 for (i = 0; i < statistics.num; i++) {
665 ret = add_to_score_table(aa.array[i]);
668 *errmsg = make_message(
669 "could not add row to score table");
673 ret = statistics.num;
677 close_current_mood();
682 * Close and re-open the current mood.
684 * This function is called on events which render the current list of
685 * admissible files useless, for example if an attribute is removed from the
688 * If no mood is currently open, the function returns success.
690 static int reload_current_mood(void)
693 char *mood_name = NULL;
695 ret = clear_score_table();
700 PARA_NOTICE_LOG("reloading %s\n", current_mood->name?
701 current_mood->name : "(dummy)");
702 if (current_mood->name)
703 mood_name = para_strdup(current_mood->name);
704 close_current_mood();
705 ret = change_current_mood(mood_name, NULL);
711 * Notification callback for the moods table.
713 * \param event Type of the event just occurred.
715 * \param data Its type depends on the event.
717 * This function updates the score table according to the event that has
718 * occurred. Two actions are possible: (a) reload the current mood, or (b)
719 * add/remove/update the row of the score table which corresponds to the audio
720 * file that has been modified or whose afs info has been changed. It depends
721 * on the type of the event which action (if any) is performed.
723 * The callbacks of command handlers such as com_add() or com_touch() which
724 * modify the audio file table call this function. The virtual streaming system
725 * also calls this after it has updated the afs info of the file it is about to
726 * stream (the one with the highest score). If the file stays admissible, its
727 * score is recomputed so that a different file is picked next time.
731 int moods_event_handler(enum afs_events event, __a_unused struct para_buffer *pb,
738 * The three blob events might change the set of admissible files,
739 * so we must reload the score list.
744 if (data == moods_table || data == playlists_table)
745 return 1; /* no reload necessary for these */
746 return reload_current_mood();
747 /* these also require reload of the score table */
749 case ATTRIBUTE_REMOVE:
750 case ATTRIBUTE_RENAME:
751 return reload_current_mood();
752 /* changes to the aft only require to re-examine the audio file */
754 struct afsi_change_event_data *aced = data;
755 return mood_update_audio_file(aced->aft_row, aced->old_afsi);
758 case AUDIO_FILE_RENAME:
760 return mood_update_audio_file(data, NULL);
761 case AUDIO_FILE_REMOVE:
762 return mood_delete_audio_file(data);