2 * Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file mood.c Paraslash's mood handling functions. */
23 * Contains statistical data of the currently admissible audio files.
25 * It is used to assign normalized score values to each admissible audio file.
27 struct afs_statistics {
28 /** Sum of num played over all admissible files. */
29 int64_t num_played_sum;
30 /** Sum of last played times over all admissible files. */
31 int64_t last_played_sum;
32 /** Quadratic deviation of num played count. */
33 int64_t num_played_qd;
34 /** Quadratic deviation of last played time. */
35 int64_t last_played_qd;
36 /** Number of admissible files */
39 static struct afs_statistics statistics;
42 * Each line of the current mood corresponds to a mood_item.
45 /** The method this line is referring to. */
46 const struct mood_method *method;
47 /** The data structure computed by the mood parser. */
49 /** The given score value, or zero if none was given. */
51 /** Non-zero if random scoring was requested. */
53 /** Whether the "not" keyword was given in the mood line. */
55 /** The position in the list of items. */
56 struct list_head mood_item_node;
60 * Created from the mood definition by \ref change_current_mood().
62 * When a mood is opened, each line of its definition is investigated, and a
63 * corresponding mood item is produced. Each mood line starts with accept,
64 * deny, or score which determines the type of the mood line. For each such
65 * type a linked list is maintained whose entries are the mood items.
68 /** The name of this mood. */
70 /** The list of mood items of type \p accept. */
71 struct list_head accept_list;
72 /** The list of mood items of type \p deny. */
73 struct list_head deny_list;
74 /** The list of mood items of type \p score. */
75 struct list_head score_list;
79 * If current_mood is NULL then no mood is currently open. If
80 * current_mood->name is NULL, the dummy mood is currently open.
82 static struct mood *current_mood;
85 * Find the position of the most-significant set bit.
87 * Copied and slightly adapted from the linux source tree, version 4.9.39
90 __a_const static uint32_t fls64(uint64_t v)
93 const uint64_t ones = ~(uint64_t)0U;
95 if ((v & (ones << 32)) == 0) {
99 if ((v & (ones << (64 - 16))) == 0) {
103 if ((v & (ones << (64 - 8))) == 0) {
107 if ((v & (ones << (64 - 4))) == 0) {
111 if ((v & (ones << (64 - 2))) == 0) {
115 if ((v & (ones << (64 - 1))) == 0)
121 * Compute the integer square root floor(sqrt(x)).
123 * Taken 2007 from the linux source tree.
125 __a_const static uint64_t int_sqrt(uint64_t x)
127 uint64_t op = x, res = 0, one = 1;
129 one = one << (fls64(x) & ~one);
131 if (op >= res + one) {
132 op = op - (res + one);
142 * Returns true if row matches, false if it does not match. In any case score
143 * and score_arg_sum are set/increased accordingly.
145 static bool get_item_score(struct mood_item *item, const struct afs_info *afsi,
146 const struct afh_info *afhi, const char *path, long *score,
152 *score_arg_sum += item->random_score? 100 : PARA_ABS(item->score_arg);
155 ret = item->method->score_function(path, afsi, afhi,
157 if ((ret < 0 && !item->logical_not) || (ret >= 0 && item->logical_not))
160 if (item->random_score)
161 *score = PARA_ABS(ret) * para_random(100);
163 *score = PARA_ABS(ret) * item->score_arg;
167 /* returns 1 if row admissible, 0 if not, negative on errors */
168 static int row_is_admissible(const struct osl_row *aft_row, struct mood *m,
171 struct mood_item *item;
174 long score_arg_sum = 0, score = 0, item_score;
175 struct afs_info afsi;
176 struct afh_info afhi;
181 ret = get_afsi_of_row(aft_row, &afsi);
184 ret = get_afhi_of_row(aft_row, &afhi);
187 ret = get_audio_file_path_of_row(aft_row, &path);
190 /* reject audio file if it matches any entry in the deny list */
191 list_for_each_entry(item, &m->deny_list, mood_item_node) {
192 match = get_item_score(item, &afsi, &afhi, path, &item_score,
194 if (match) /* not admissible */
199 list_for_each_entry(item, &m->accept_list, mood_item_node) {
200 ret = get_item_score(item, &afsi, &afhi, path, &item_score,
207 /* reject if there is no matching entry in the accept list */
208 if (!match && !list_empty(&m->accept_list))
210 list_for_each_entry(item, &m->score_list, mood_item_node) {
211 match = get_item_score(item, &afsi, &afhi, path, &item_score,
217 score /= score_arg_sum;
222 static void cleanup_list_entry(struct mood_item *item)
224 if (item->method && item->method->cleanup)
225 item->method->cleanup(item->parser_data);
227 free(item->parser_data);
228 list_del(&item->mood_item_node);
232 static void destroy_mood(struct mood *m)
234 struct mood_item *tmp, *item;
238 list_for_each_entry_safe(item, tmp, &m->accept_list, mood_item_node)
239 cleanup_list_entry(item);
240 list_for_each_entry_safe(item, tmp, &m->deny_list, mood_item_node)
241 cleanup_list_entry(item);
242 list_for_each_entry_safe(item, tmp, &m->score_list, mood_item_node)
243 cleanup_list_entry(item);
248 static struct mood *alloc_new_mood(const char *name)
250 struct mood *m = para_calloc(sizeof(struct mood));
252 m->name = para_strdup(name);
253 INIT_LIST_HEAD(&m->accept_list);
254 INIT_LIST_HEAD(&m->deny_list);
255 INIT_LIST_HEAD(&m->score_list);
259 /** The different types of a mood line. */
260 enum mood_line_type {
271 /** Data passed to the parser of a mood line. */
272 struct mood_line_parser_data {
273 /** The mood this mood line belongs to. */
275 /** The line number in the mood definition. */
280 * <accept [with score <score>] | deny [with score <score>] | score <score>>
281 * [if] [not] <mood_method> [options]
282 * <score> is either an integer or "random" which assigns a random score to
285 static int parse_mood_line(char *mood_line, void *data)
287 struct mood_line_parser_data *mlpd = data;
292 enum mood_line_type mlt = ML_INVALID;
293 struct mood_item *mi = NULL;
296 ret = create_argv(mood_line, " \t", &argv);
300 if (!num_words) /* empty line */
303 if (**w == '#') /* comment */
305 if (!strcmp(*w, "accept"))
307 else if (!strcmp(*w, "deny"))
309 else if (!strcmp(*w, "score"))
311 ret = -E_MOOD_SYNTAX;
312 if (mlt == ML_INVALID)
314 mi = para_calloc(sizeof(struct mood_item));
315 if (mlt != ML_SCORE) {
316 ret = -E_MOOD_SYNTAX;
320 if (strcmp(*w, "with"))
325 if (strcmp(*w, "score"))
328 if (mlt == ML_SCORE || !strcmp(*w, "score")) {
329 ret = -E_MOOD_SYNTAX;
333 if (strcmp(*w, "random")) {
334 mi->random_score = 0;
335 ret = para_atoi32(*w, &mi->score_arg);
339 mi->random_score = 1;
341 goto success; /* the line "score random" is valid */
345 ret = -E_MOOD_SYNTAX;
350 if (!strcmp(*w, "if")) {
351 ret = -E_MOOD_SYNTAX;
356 if (!strcmp(*w, "not")) {
357 ret = -E_MOOD_SYNTAX;
364 for (i = 0; mood_methods[i].parser; i++) {
365 if (strcmp(*w, mood_methods[i].name))
369 ret = -E_MOOD_SYNTAX;
370 if (!mood_methods[i].parser)
372 ret = mood_methods[i].parser(num_words - 1 - (w - argv), w,
376 mi->method = &mood_methods[i];
379 if (mlt == ML_ACCEPT)
380 para_list_add(&mi->mood_item_node, &mlpd->m->accept_list);
381 else if (mlt == ML_DENY)
382 para_list_add(&mi->mood_item_node, &mlpd->m->deny_list);
384 para_list_add(&mi->mood_item_node, &mlpd->m->score_list);
386 PARA_DEBUG_LOG("%s entry added, method: %p\n", mlt == ML_ACCEPT? "accept" :
387 (mlt == ML_DENY? "deny" : "score"), mi->method);
391 if (mi && (ret < 0 || !mlpd->m)) { /* mi was not added to any list */
392 free(mi->parser_data);
398 static int load_mood(const struct osl_row *mood_row, struct mood **m)
401 struct osl_object mood_def;
402 struct mood_line_parser_data mlpd = {.line_num = 0};
406 ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
411 mlpd.m = alloc_new_mood(mood_name);
412 ret = for_each_line(FELF_READ_ONLY, mood_def.data, mood_def.size,
413 parse_mood_line, &mlpd);
414 osl_close_disk_object(&mood_def);
416 PARA_ERROR_LOG("unable to load mood %s: %s\n", mlpd.m->name,
417 para_strerror(-ret));
418 destroy_mood(mlpd.m);
425 static int check_mood(struct osl_row *mood_row, void *data)
427 struct para_buffer *pb = data;
429 struct osl_object mood_def;
430 struct mood_line_parser_data mlpd = {.line_num = 0};
432 int ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
435 para_printf(pb, "cannot read mood\n");
438 if (!*mood_name) /* ignore dummy row */
440 para_printf(pb, "checking mood %s...\n", mood_name);
441 ret = for_each_line(FELF_READ_ONLY, mood_def.data, mood_def.size,
442 parse_mood_line, &mlpd);
444 para_printf(pb, "mood %s: error in line %u: %s\n", mood_name,
445 mlpd.line_num, para_strerror(-ret));
446 ret = 1; /* don't fail the loop on invalid mood definitions */
448 osl_close_disk_object(&mood_def);
453 * Check all moods for syntax errors.
455 * \param aca Only ->pbout is used for diagnostics.
457 * \return Negative on fatal errors. Inconsistent mood definitions are not
458 * considered an error.
460 int mood_check_callback(struct afs_callback_arg *aca)
462 para_printf(&aca->pbout, "checking moods...\n");
463 return osl(osl_rbtree_loop(moods_table, BLOBCOL_ID, &aca->pbout,
467 static int64_t normalized_value(int64_t x, int64_t n, int64_t sum, int64_t qd)
471 return 100 * (n * x - sum) / (int64_t)int_sqrt(n) / (int64_t)int_sqrt(qd);
474 static long compute_score(struct afs_info *afsi, long mood_score)
476 mood_score -= normalized_value(afsi->num_played, statistics.num,
477 statistics.num_played_sum, statistics.num_played_qd);
478 mood_score -= normalized_value(afsi->last_played, statistics.num,
479 statistics.last_played_sum, statistics.last_played_qd);
480 return mood_score / 3;
483 static int add_afs_statistics(const struct osl_row *row)
486 struct afs_info afsi;
489 ret = get_afsi_of_row(row, &afsi);
493 x = afsi.last_played;
494 s = statistics.last_played_sum;
496 q = (x > s / n)? x - s / n : s / n - x;
497 statistics.last_played_qd += q * q * n / (n + 1);
499 statistics.last_played_sum += x;
502 s = statistics.num_played_sum;
504 q = (x > s / n)? x - s / n : s / n - x;
505 statistics.num_played_qd += q * q * n / (n + 1);
507 statistics.num_played_sum += x;
512 static int del_afs_statistics(const struct osl_row *row)
514 uint64_t n, s, q, a, new_s;
515 struct afs_info afsi;
517 ret = get_afsi_of_row(row, &afsi);
523 memset(&statistics, 0, sizeof(statistics));
527 s = statistics.last_played_sum;
528 q = statistics.last_played_qd;
529 a = afsi.last_played;
531 statistics.last_played_sum = new_s;
532 statistics.last_played_qd = q + s * s / n - a * a
533 - new_s * new_s / (n - 1);
535 s = statistics.num_played_sum;
536 q = statistics.num_played_qd;
539 statistics.num_played_sum = new_s;
540 statistics.num_played_qd = q + s * s / n - a * a
541 - new_s * new_s / (n - 1);
548 * At mood open time we determine the set of admissible files for the given
549 * mood. The mood score of each admissible file is computed by adding up all
550 * mood item scores. Next, we update the afs statistics and append a struct
551 * admissible_file_info to a temporary array.
553 * When all files have been processed in this way, the final score of each
554 * admissible file is computed by adding the dynamic score (which depends on
555 * the afs_statistics and the current time) to the mood score. Finally, all
556 * audio files in the temporary array are added to the score table and the
559 struct admissible_file_info
561 /** The admissible audio file. */
562 struct osl_row *aft_row;
567 /** The temporary array of admissible files. */
568 struct admissible_array {
569 /** Files are admissible wrt. this mood. */
571 /** The size of the array */
573 /** Pointer to the array of admissible files. */
574 struct admissible_file_info *array;
578 * Add an entry to the array of admissible files.
580 * \param aft_row The audio file to be added.
581 * \param private_data Pointer to a struct admissible_file_info.
583 * \return 1 if row admissible, 0 if not, negative on errors.
585 static int add_if_admissible(struct osl_row *aft_row, void *data)
587 struct admissible_array *aa = data;
591 ret = row_is_admissible(aft_row, aa->m, &score);
594 if (statistics.num >= aa->size) {
597 aa->array = para_realloc(aa->array,
598 aa->size * sizeof(struct admissible_file_info));
600 aa->array[statistics.num].aft_row = aft_row;
601 aa->array[statistics.num].score = score;
602 ret = add_afs_statistics(aft_row);
609 * Compute the new quadratic deviation in case one element changes.
611 * \param n Number of elements.
612 * \param old_qd The quadratic deviation before the change.
613 * \param old_val The value that was replaced.
614 * \param new_val The replacement value.
615 * \param old_sum The sum of all elements before the update.
617 * \return The new quadratic deviation resulting from replacing old_val
620 * Given n real numbers a_1, ..., a_n, their sum S = a_1 + ... + a_n,
621 * their quadratic deviation
623 * q = (a_1 - S/n)^2 + ... + (a_n - S/n)^2,
625 * and a real number b, the quadratic deviation q' of a_1,...a_{n-1}, b (ie.
626 * the last number a_n was replaced by b) may be computed in O(1) time in terms
627 * of n, q, a_n, b, and S as
629 * q' = q + d * s - (2 * S + d) * d / n
630 * = q + d * (s - 2 * S / n - d /n),
632 * where d = b - a_n, and s = b + a_n.
634 * Example: n = 3, a_1 = 3, a_2 = 5, a_3 = 7, b = 10. Then S = 15, q = 8, d = 3,
637 * q + d * s - (2 * S + d) * d / n = 8 + 51 - 33 = 26,
639 * which equals q' = (3 - 6)^2 + (5 - 6)^2 + (10 - 6)^2.
642 _static_inline_ int64_t update_quadratic_deviation(int64_t n, int64_t old_qd,
643 int64_t old_val, int64_t new_val, int64_t old_sum)
645 int64_t delta = new_val - old_val;
646 int64_t sigma = new_val + old_val;
647 return old_qd + delta * (sigma - 2 * old_sum / n - delta / n);
650 static int update_afs_statistics(struct afs_info *old_afsi,
651 struct afs_info *new_afsi)
654 int ret = get_num_admissible_files(&n);
660 statistics.last_played_qd = update_quadratic_deviation(n,
661 statistics.last_played_qd, old_afsi->last_played,
662 new_afsi->last_played, statistics.last_played_sum);
663 statistics.last_played_sum += new_afsi->last_played - old_afsi->last_played;
665 statistics.num_played_qd = update_quadratic_deviation(n,
666 statistics.num_played_qd, old_afsi->num_played,
667 new_afsi->num_played, statistics.num_played_sum);
668 statistics.num_played_sum += new_afsi->num_played - old_afsi->num_played;
672 static int add_to_score_table(const struct osl_row *aft_row, long mood_score)
675 struct afs_info afsi;
676 int ret = get_afsi_of_row(aft_row, &afsi);
680 score = compute_score(&afsi, mood_score);
681 return score_add(aft_row, score);
684 static int delete_from_statistics_and_score_table(const struct osl_row *aft_row)
686 int ret = del_afs_statistics(aft_row);
689 return score_delete(aft_row);
693 * Delete one entry from the statistics and from the score table.
695 * \param aft_row The audio file which is no longer admissible.
697 * \return Positive on success, negative on errors.
699 * \sa \ref score_delete().
701 static int mood_delete_audio_file(const struct osl_row *aft_row)
705 ret = row_belongs_to_score_table(aft_row, NULL);
708 if (!ret) /* not admissible, nothing to do */
710 return delete_from_statistics_and_score_table(aft_row);
714 * Compute the new score of an audio file wrt. the current mood.
716 * \param aft_row Determines the audio file.
717 * \param old_afsi The audio file selector info before updating.
719 * The \a old_afsi argument may be \p NULL which indicates that no changes to
720 * the audio file info were made.
722 * \return Positive on success, negative on errors.
724 static int mood_update_audio_file(const struct osl_row *aft_row,
725 struct afs_info *old_afsi)
728 int ret, is_admissible, was_admissible = 0;
729 struct afs_info afsi;
733 return 1; /* nothing to do */
734 ret = row_belongs_to_score_table(aft_row, &rank);
737 was_admissible = ret;
738 ret = row_is_admissible(aft_row, current_mood, &score);
741 is_admissible = (ret > 0);
742 if (!was_admissible && !is_admissible)
744 if (was_admissible && !is_admissible)
745 return delete_from_statistics_and_score_table(aft_row);
746 if (!was_admissible && is_admissible) {
747 ret = add_afs_statistics(aft_row);
750 return add_to_score_table(aft_row, score);
753 ret = get_afsi_of_row(aft_row, &afsi);
757 ret = update_afs_statistics(old_afsi, &afsi);
761 score = compute_score(&afsi, score);
762 PARA_DEBUG_LOG("score: %li\n", score);
763 percent = (score + 100) / 3;
766 else if (percent < 0)
768 PARA_DEBUG_LOG("moving from rank %u to %li%%\n", rank, percent);
769 return score_update(aft_row, percent);
772 static void log_statistics(void)
774 unsigned n = statistics.num;
775 int mean_days, sigma_days;
777 * We can not use the "now" pointer from sched.c here because we are
778 * called before schedule(), which initializes "now".
782 assert(current_mood);
783 PARA_NOTICE_LOG("loaded mood %s\n", current_mood->name?
784 current_mood->name : "(dummy)");
786 PARA_WARNING_LOG("no admissible files\n");
789 PARA_NOTICE_LOG("%u admissible files\n", statistics.num);
790 clock_get_realtime(&rnow);
791 mean_days = (rnow.tv_sec - statistics.last_played_sum / n) / 3600 / 24;
792 sigma_days = int_sqrt(statistics.last_played_qd / n) / 3600 / 24;
793 PARA_NOTICE_LOG("last_played mean/sigma: %d/%d days\n", mean_days, sigma_days);
794 PARA_NOTICE_LOG("num_played mean/sigma: %llu/%llu\n",
795 (long long unsigned)statistics.num_played_sum / n,
796 (long long unsigned)int_sqrt(statistics.num_played_qd / n));
800 * Close the current mood.
802 * Frees all resources of the current mood.
804 void close_current_mood(void)
806 destroy_mood(current_mood);
808 memset(&statistics, 0, sizeof(statistics));
812 * Change the current mood.
814 * \param mood_name The name of the mood to open.
816 * If \a mood_name is \a NULL, load the dummy mood that accepts every audio file
817 * and uses a scoring method based only on the \a last_played information.
819 * If there is already an open mood, it will be closed first.
821 * \return Positive on success, negative on errors. Loading the dummy mood
824 * \sa struct \ref afs_info::last_played.
826 int change_current_mood(const char *mood_name)
829 struct admissible_array aa = {
837 struct osl_object obj = {
838 .data = (char *)mood_name,
839 .size = strlen(mood_name) + 1
841 ret = osl(osl_get_row(moods_table, BLOBCOL_NAME, &obj, &row));
843 PARA_NOTICE_LOG("no such mood: %s\n", mood_name);
846 ret = load_mood(row, &m);
849 close_current_mood();
851 } else { /* load dummy mood */
852 close_current_mood();
853 current_mood = alloc_new_mood(NULL);
856 PARA_NOTICE_LOG("computing statistics of admissible files\n");
857 ret = audio_file_loop(&aa, add_if_admissible);
860 for (i = 0; i < statistics.num; i++) {
861 struct admissible_file_info *a = aa.array + i;
862 ret = add_to_score_table(a->aft_row, a->score);
867 ret = statistics.num;
874 * Close and re-open the current mood.
876 * This function is called on events which render the current list of
877 * admissible files useless, for example if an attribute is removed from the
880 * If no mood is currently open, the function returns success.
882 static int reload_current_mood(void)
885 char *mood_name = NULL;
887 ret = clear_score_table();
892 PARA_NOTICE_LOG("reloading %s\n", current_mood->name?
893 current_mood->name : "(dummy)");
894 if (current_mood->name)
895 mood_name = para_strdup(current_mood->name);
896 close_current_mood();
897 ret = change_current_mood(mood_name);
903 * Notification callback for the moods table.
905 * \param event Type of the event just occurred.
907 * \param data Its type depends on the event.
909 * This function performs actions required due to the occurrence of the given
910 * event. Possible actions include reload of the current mood and update of the
911 * score of an audio file.
915 int moods_event_handler(enum afs_events event, __a_unused struct para_buffer *pb,
922 * The three blob events might change the set of admissible files,
923 * so we must reload the score list.
928 if (data == moods_table || data == playlists_table)
929 return 1; /* no reload necessary for these */
930 return reload_current_mood();
931 /* these also require reload of the score table */
933 case ATTRIBUTE_REMOVE:
934 case ATTRIBUTE_RENAME:
935 return reload_current_mood();
936 /* changes to the aft only require to re-examine the audio file */
938 struct afsi_change_event_data *aced = data;
939 return mood_update_audio_file(aced->aft_row, aced->old_afsi);
942 case AUDIO_FILE_RENAME:
944 return mood_update_audio_file(data, NULL);
945 case AUDIO_FILE_REMOVE:
946 return mood_delete_audio_file(data);