1 /* Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file mood.c Paraslash's mood handling functions. */
19 * Mood parser API. It's overkill to have an own header file for
20 * these declarations as they are only needed in this .c file.
23 int mp_init(const char *definition, int nbytes, struct mp_context **result,
25 bool mp_eval_row(const struct osl_row *aft_row, struct mp_context *ctx);
26 void mp_shutdown(struct mp_context *ctx);
29 * Contains statistical data of the currently admissible audio files.
31 * It is used to assign normalized score values to each admissible audio file.
33 struct afs_statistics {
34 /** Sum of num played over all admissible files. */
35 int64_t num_played_sum;
36 /** Sum of last played times over all admissible files. */
37 int64_t last_played_sum;
38 /** Quadratic deviation of num played count. */
39 int64_t num_played_qd;
40 /** Quadratic deviation of last played time. */
41 int64_t last_played_qd;
42 /** Number of admissible files */
45 static struct afs_statistics statistics;
48 * Each line of the current mood corresponds to a mood_item.
51 /** The method this line is referring to. */
52 const struct mood_method *method;
53 /** The data structure computed by the mood parser. */
55 /** The given score value, or zero if none was given. */
57 /** Non-zero if random scoring was requested. */
59 /** Whether the "not" keyword was given in the mood line. */
61 /** The position in the list of items. */
62 struct list_head mood_item_node;
66 * Created from the mood definition by \ref change_current_mood().
68 * When a mood is opened, each line of its definition is investigated, and a
69 * corresponding mood item is produced. Each mood line starts with accept,
70 * deny, or score which determines the type of the mood line. For each such
71 * type a linked list is maintained whose entries are the mood items.
74 /** The name of this mood. */
76 /** The list of mood items of type \p accept. */
77 struct list_head accept_list;
78 /** The list of mood items of type \p deny. */
79 struct list_head deny_list;
80 /** The list of mood items of type \p score. */
81 struct list_head score_list;
82 /* Only used for version 2 moods. */
83 struct mp_context *parser_context;
87 * If current_mood is NULL then no mood is currently open. If
88 * current_mood->name is NULL, the dummy mood is currently open.
90 static struct mood *current_mood;
93 * Find the position of the most-significant set bit.
95 * Copied and slightly adapted from the linux source tree, version 4.9.39
98 __a_const static uint32_t fls64(uint64_t v)
101 const uint64_t ones = ~(uint64_t)0U;
103 if ((v & (ones << 32)) == 0) {
107 if ((v & (ones << (64 - 16))) == 0) {
111 if ((v & (ones << (64 - 8))) == 0) {
115 if ((v & (ones << (64 - 4))) == 0) {
119 if ((v & (ones << (64 - 2))) == 0) {
123 if ((v & (ones << (64 - 1))) == 0)
129 * Compute the integer square root floor(sqrt(x)).
131 * Taken 2007 from the linux source tree.
133 __a_const static uint64_t int_sqrt(uint64_t x)
135 uint64_t op = x, res = 0, one = 1;
137 one = one << (fls64(x) & ~one);
139 if (op >= res + one) {
140 op = op - (res + one);
150 * Returns true if row matches, false if it does not match. In any case score
151 * and score_arg_sum are set/increased accordingly.
153 static bool get_item_score(struct mood_item *item, const struct afs_info *afsi,
154 const struct afh_info *afhi, const char *path, long *score,
160 *score_arg_sum += item->random_score? 100 : PARA_ABS(item->score_arg);
163 ret = item->method->score_function(path, afsi, afhi,
165 if ((ret < 0 && !item->logical_not) || (ret >= 0 && item->logical_not))
168 if (item->random_score)
169 *score = PARA_ABS(ret) * para_random(100);
171 *score = PARA_ABS(ret) * item->score_arg;
175 /* returns 1 if row admissible, 0 if not, negative on errors */
176 static int row_is_admissible(const struct osl_row *aft_row, struct mood *m,
179 struct mood_item *item;
182 long score_arg_sum = 0, score = 0, item_score;
183 struct afs_info afsi;
184 struct afh_info afhi;
189 if (m->parser_context) {
191 return mp_eval_row(aft_row, m->parser_context);
193 ret = get_afsi_of_row(aft_row, &afsi);
196 ret = get_afhi_of_row(aft_row, &afhi);
199 ret = get_audio_file_path_of_row(aft_row, &path);
202 /* reject audio file if it matches any entry in the deny list */
203 list_for_each_entry(item, &m->deny_list, mood_item_node) {
204 match = get_item_score(item, &afsi, &afhi, path, &item_score,
206 if (match) /* not admissible */
211 list_for_each_entry(item, &m->accept_list, mood_item_node) {
212 ret = get_item_score(item, &afsi, &afhi, path, &item_score,
219 /* reject if there is no matching entry in the accept list */
220 if (!match && !list_empty(&m->accept_list))
222 list_for_each_entry(item, &m->score_list, mood_item_node) {
223 match = get_item_score(item, &afsi, &afhi, path, &item_score,
229 score /= score_arg_sum;
234 static void cleanup_list_entry(struct mood_item *item)
236 if (item->method && item->method->cleanup)
237 item->method->cleanup(item->parser_data);
239 free(item->parser_data);
240 list_del(&item->mood_item_node);
244 static void destroy_mood(struct mood *m)
246 struct mood_item *tmp, *item;
250 list_for_each_entry_safe(item, tmp, &m->accept_list, mood_item_node)
251 cleanup_list_entry(item);
252 list_for_each_entry_safe(item, tmp, &m->deny_list, mood_item_node)
253 cleanup_list_entry(item);
254 list_for_each_entry_safe(item, tmp, &m->score_list, mood_item_node)
255 cleanup_list_entry(item);
257 mp_shutdown(m->parser_context);
261 static struct mood *alloc_new_mood(const char *name)
263 struct mood *m = para_calloc(sizeof(struct mood));
265 m->name = para_strdup(name);
266 INIT_LIST_HEAD(&m->accept_list);
267 INIT_LIST_HEAD(&m->deny_list);
268 INIT_LIST_HEAD(&m->score_list);
272 /** The different types of a mood line. */
273 enum mood_line_type {
284 /** Data passed to the parser of a mood line. */
285 struct mood_line_parser_data {
286 /** The mood this mood line belongs to. */
288 /** The line number in the mood definition. */
293 * <accept [with score <score>] | deny [with score <score>] | score <score>>
294 * [if] [not] <mood_method> [options]
295 * <score> is either an integer or "random" which assigns a random score to
298 static int parse_mood_line(char *mood_line, void *data)
300 struct mood_line_parser_data *mlpd = data;
305 enum mood_line_type mlt = ML_INVALID;
306 struct mood_item *mi = NULL;
309 ret = create_argv(mood_line, " \t", &argv);
313 if (!num_words) /* empty line */
316 if (**w == '#') /* comment */
318 if (!strcmp(*w, "accept"))
320 else if (!strcmp(*w, "deny"))
322 else if (!strcmp(*w, "score"))
324 ret = -E_MOOD_SYNTAX;
325 if (mlt == ML_INVALID)
327 mi = para_calloc(sizeof(struct mood_item));
328 if (mlt != ML_SCORE) {
329 ret = -E_MOOD_SYNTAX;
333 if (strcmp(*w, "with"))
338 if (strcmp(*w, "score"))
341 if (mlt == ML_SCORE || !strcmp(*w, "score")) {
342 ret = -E_MOOD_SYNTAX;
346 if (strcmp(*w, "random")) {
347 mi->random_score = 0;
348 ret = para_atoi32(*w, &mi->score_arg);
352 mi->random_score = 1;
354 goto success; /* the line "score random" is valid */
358 ret = -E_MOOD_SYNTAX;
363 if (!strcmp(*w, "if")) {
364 ret = -E_MOOD_SYNTAX;
369 if (!strcmp(*w, "not")) {
370 ret = -E_MOOD_SYNTAX;
377 for (i = 0; mood_methods[i].parser; i++) {
378 if (strcmp(*w, mood_methods[i].name))
382 ret = -E_MOOD_SYNTAX;
383 if (!mood_methods[i].parser)
385 ret = mood_methods[i].parser(num_words - 1 - (w - argv), w,
389 mi->method = &mood_methods[i];
392 if (mlt == ML_ACCEPT)
393 para_list_add(&mi->mood_item_node, &mlpd->m->accept_list);
394 else if (mlt == ML_DENY)
395 para_list_add(&mi->mood_item_node, &mlpd->m->deny_list);
397 para_list_add(&mi->mood_item_node, &mlpd->m->score_list);
399 PARA_DEBUG_LOG("%s entry added, method: %p\n", mlt == ML_ACCEPT? "accept" :
400 (mlt == ML_DENY? "deny" : "score"), mi->method);
404 if (mi && (ret < 0 || !mlpd->m)) { /* mi was not added to any list */
405 free(mi->parser_data);
411 static int load_mood(const struct osl_row *mood_row, struct mood **m,
415 struct osl_object mood_def;
416 struct mood_line_parser_data mlpd = {.line_num = 0};
420 ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
425 mlpd.m = alloc_new_mood(mood_name);
426 ret = for_each_line(FELF_READ_ONLY, mood_def.data, mood_def.size,
427 parse_mood_line, &mlpd);
429 PARA_INFO_LOG("opening version 2 mood %s\n", mlpd.m->name);
430 ret = mp_init(mood_def.data, mood_def.size, &mlpd.m->parser_context,
433 destroy_mood(mlpd.m);
435 PARA_WARNING_LOG("loaded version 1 mood %s\n", mlpd.m->name);
436 PARA_WARNING_LOG("please convert to version 2\n");
439 osl_close_disk_object(&mood_def);
445 static int check_mood(struct osl_row *mood_row, void *data)
447 struct para_buffer *pb = data;
449 struct osl_object mood_def;
450 struct mood_line_parser_data mlpd = {.line_num = 0};
452 int ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
455 para_printf(pb, "cannot read mood\n");
458 if (!*mood_name) /* ignore dummy row */
460 ret = for_each_line(FELF_READ_ONLY, mood_def.data, mood_def.size,
461 parse_mood_line, &mlpd);
464 struct mood *m = alloc_new_mood("check");
465 ret = mp_init(mood_def.data, mood_def.size, &m->parser_context,
468 para_printf(pb, "%s: %s\n", mood_name, errmsg);
470 para_printf(pb, "%s\n", para_strerror(-ret));
474 para_printf(pb, "%s: v1 mood, please convert to v2\n",
478 ret = 1; /* don't fail the loop on invalid mood definitions */
480 osl_close_disk_object(&mood_def);
485 * Check all moods for syntax errors.
487 * \param aca Only ->pbout is used for diagnostics.
489 * \return Negative on fatal errors. Inconsistent mood definitions are not
490 * considered an error.
492 int mood_check_callback(struct afs_callback_arg *aca)
494 para_printf(&aca->pbout, "checking moods...\n");
495 return osl(osl_rbtree_loop(moods_table, BLOBCOL_ID, &aca->pbout,
499 static int64_t normalized_value(int64_t x, int64_t n, int64_t sum, int64_t qd)
503 return 100 * (n * x - sum) / (int64_t)int_sqrt(n) / (int64_t)int_sqrt(qd);
506 static long compute_score(struct afs_info *afsi, long mood_score)
508 mood_score -= normalized_value(afsi->num_played, statistics.num,
509 statistics.num_played_sum, statistics.num_played_qd);
510 mood_score -= normalized_value(afsi->last_played, statistics.num,
511 statistics.last_played_sum, statistics.last_played_qd);
512 return mood_score / 3;
515 static int add_afs_statistics(const struct osl_row *row)
518 struct afs_info afsi;
521 ret = get_afsi_of_row(row, &afsi);
525 x = afsi.last_played;
526 s = statistics.last_played_sum;
528 q = (x > s / n)? x - s / n : s / n - x;
529 statistics.last_played_qd += q * q * n / (n + 1);
531 statistics.last_played_sum += x;
534 s = statistics.num_played_sum;
536 q = (x > s / n)? x - s / n : s / n - x;
537 statistics.num_played_qd += q * q * n / (n + 1);
539 statistics.num_played_sum += x;
544 static int del_afs_statistics(const struct osl_row *row)
546 uint64_t n, s, q, a, new_s;
547 struct afs_info afsi;
549 ret = get_afsi_of_row(row, &afsi);
555 memset(&statistics, 0, sizeof(statistics));
559 s = statistics.last_played_sum;
560 q = statistics.last_played_qd;
561 a = afsi.last_played;
563 statistics.last_played_sum = new_s;
564 statistics.last_played_qd = q + s * s / n - a * a
565 - new_s * new_s / (n - 1);
567 s = statistics.num_played_sum;
568 q = statistics.num_played_qd;
571 statistics.num_played_sum = new_s;
572 statistics.num_played_qd = q + s * s / n - a * a
573 - new_s * new_s / (n - 1);
580 * At mood open time we determine the set of admissible files for the given
581 * mood. The mood score of each admissible file is computed by adding up all
582 * mood item scores. Next, we update the afs statistics and append a struct
583 * admissible_file_info to a temporary array.
585 * When all files have been processed in this way, the final score of each
586 * admissible file is computed by adding the dynamic score (which depends on
587 * the afs_statistics and the current time) to the mood score. Finally, all
588 * audio files in the temporary array are added to the score table and the
591 struct admissible_file_info
593 /** The admissible audio file. */
594 struct osl_row *aft_row;
599 /** The temporary array of admissible files. */
600 struct admissible_array {
601 /** Files are admissible wrt. this mood. */
603 /** The size of the array */
605 /** Pointer to the array of admissible files. */
606 struct admissible_file_info *array;
610 * Add an entry to the array of admissible files.
612 * \param aft_row The audio file to be added.
613 * \param private_data Pointer to a struct admissible_file_info.
615 * \return 1 if row admissible, 0 if not, negative on errors.
617 static int add_if_admissible(struct osl_row *aft_row, void *data)
619 struct admissible_array *aa = data;
623 ret = row_is_admissible(aft_row, aa->m, &score);
626 if (statistics.num >= aa->size) {
629 aa->array = para_realloc(aa->array,
630 aa->size * sizeof(struct admissible_file_info));
632 aa->array[statistics.num].aft_row = aft_row;
633 aa->array[statistics.num].score = score;
634 ret = add_afs_statistics(aft_row);
641 * Compute the new quadratic deviation in case one element changes.
643 * \param n Number of elements.
644 * \param old_qd The quadratic deviation before the change.
645 * \param old_val The value that was replaced.
646 * \param new_val The replacement value.
647 * \param old_sum The sum of all elements before the update.
649 * \return The new quadratic deviation resulting from replacing old_val
652 * Given n real numbers a_1, ..., a_n, their sum S = a_1 + ... + a_n,
653 * their quadratic deviation
655 * q = (a_1 - S/n)^2 + ... + (a_n - S/n)^2,
657 * and a real number b, the quadratic deviation q' of a_1,...a_{n-1}, b (ie.
658 * the last number a_n was replaced by b) may be computed in O(1) time in terms
659 * of n, q, a_n, b, and S as
661 * q' = q + d * s - (2 * S + d) * d / n
662 * = q + d * (s - 2 * S / n - d /n),
664 * where d = b - a_n, and s = b + a_n.
666 * Example: n = 3, a_1 = 3, a_2 = 5, a_3 = 7, b = 10. Then S = 15, q = 8, d = 3,
669 * q + d * s - (2 * S + d) * d / n = 8 + 51 - 33 = 26,
671 * which equals q' = (3 - 6)^2 + (5 - 6)^2 + (10 - 6)^2.
674 _static_inline_ int64_t update_quadratic_deviation(int64_t n, int64_t old_qd,
675 int64_t old_val, int64_t new_val, int64_t old_sum)
677 int64_t delta = new_val - old_val;
678 int64_t sigma = new_val + old_val;
679 return old_qd + delta * (sigma - 2 * old_sum / n - delta / n);
682 static int update_afs_statistics(struct afs_info *old_afsi,
683 struct afs_info *new_afsi)
686 int ret = get_num_admissible_files(&n);
692 statistics.last_played_qd = update_quadratic_deviation(n,
693 statistics.last_played_qd, old_afsi->last_played,
694 new_afsi->last_played, statistics.last_played_sum);
695 statistics.last_played_sum += new_afsi->last_played - old_afsi->last_played;
697 statistics.num_played_qd = update_quadratic_deviation(n,
698 statistics.num_played_qd, old_afsi->num_played,
699 new_afsi->num_played, statistics.num_played_sum);
700 statistics.num_played_sum += new_afsi->num_played - old_afsi->num_played;
704 static int add_to_score_table(const struct osl_row *aft_row, long mood_score)
707 struct afs_info afsi;
708 int ret = get_afsi_of_row(aft_row, &afsi);
712 score = compute_score(&afsi, mood_score);
713 return score_add(aft_row, score);
716 static int delete_from_statistics_and_score_table(const struct osl_row *aft_row)
718 int ret = del_afs_statistics(aft_row);
721 return score_delete(aft_row);
725 * Delete one entry from the statistics and from the score table.
727 * \param aft_row The audio file which is no longer admissible.
729 * \return Positive on success, negative on errors.
731 * \sa \ref score_delete().
733 static int mood_delete_audio_file(const struct osl_row *aft_row)
737 ret = row_belongs_to_score_table(aft_row, NULL);
740 if (!ret) /* not admissible, nothing to do */
742 return delete_from_statistics_and_score_table(aft_row);
746 * Compute the new score of an audio file wrt. the current mood.
748 * \param aft_row Determines the audio file.
749 * \param old_afsi The audio file selector info before updating.
751 * The \a old_afsi argument may be \p NULL which indicates that no changes to
752 * the audio file info were made.
754 * \return Positive on success, negative on errors.
756 static int mood_update_audio_file(const struct osl_row *aft_row,
757 struct afs_info *old_afsi)
760 int ret, is_admissible, was_admissible = 0;
761 struct afs_info afsi;
765 return 1; /* nothing to do */
766 ret = row_belongs_to_score_table(aft_row, &rank);
769 was_admissible = ret;
770 ret = row_is_admissible(aft_row, current_mood, &score);
773 is_admissible = (ret > 0);
774 if (!was_admissible && !is_admissible)
776 if (was_admissible && !is_admissible)
777 return delete_from_statistics_and_score_table(aft_row);
778 if (!was_admissible && is_admissible) {
779 ret = add_afs_statistics(aft_row);
782 return add_to_score_table(aft_row, score);
785 ret = get_afsi_of_row(aft_row, &afsi);
789 ret = update_afs_statistics(old_afsi, &afsi);
793 score = compute_score(&afsi, score);
794 PARA_DEBUG_LOG("score: %li\n", score);
795 percent = (score + 100) / 3;
798 else if (percent < 0)
800 PARA_DEBUG_LOG("moving from rank %u to %li%%\n", rank, percent);
801 return score_update(aft_row, percent);
804 static void log_statistics(void)
806 unsigned n = statistics.num;
807 int mean_days, sigma_days;
809 * We can not use the "now" pointer from sched.c here because we are
810 * called before schedule(), which initializes "now".
814 assert(current_mood);
815 PARA_NOTICE_LOG("loaded mood %s\n", current_mood->name?
816 current_mood->name : "(dummy)");
818 PARA_WARNING_LOG("no admissible files\n");
821 PARA_NOTICE_LOG("%u admissible files\n", statistics.num);
822 clock_get_realtime(&rnow);
823 mean_days = (rnow.tv_sec - statistics.last_played_sum / n) / 3600 / 24;
824 sigma_days = int_sqrt(statistics.last_played_qd / n) / 3600 / 24;
825 PARA_NOTICE_LOG("last_played mean/sigma: %d/%d days\n", mean_days, sigma_days);
826 PARA_NOTICE_LOG("num_played mean/sigma: %llu/%llu\n",
827 (long long unsigned)statistics.num_played_sum / n,
828 (long long unsigned)int_sqrt(statistics.num_played_qd / n));
832 * Close the current mood.
834 * Frees all resources of the current mood.
836 void close_current_mood(void)
838 destroy_mood(current_mood);
840 memset(&statistics, 0, sizeof(statistics));
844 * Change the current mood.
846 * \param mood_name The name of the mood to open.
847 * \param errmsg Error description is returned here.
849 * If \a mood_name is \a NULL, load the dummy mood that accepts every audio file
850 * and uses a scoring method based only on the \a last_played information.
852 * The errmsg pointer may be NULL, in which case no error message will be
853 * returned. If a non-NULL pointer is given, the caller must free *errmsg.
855 * If there is already an open mood, it will be closed first.
857 * \return Positive on success, negative on errors. Loading the dummy mood
860 * \sa struct \ref afs_info::last_played, \ref mp_eval_row().
862 int change_current_mood(const char *mood_name, char **errmsg)
865 struct admissible_array aa = {
873 struct osl_object obj = {
874 .data = (char *)mood_name,
875 .size = strlen(mood_name) + 1
877 ret = osl(osl_get_row(moods_table, BLOBCOL_NAME, &obj, &row));
879 PARA_NOTICE_LOG("no such mood: %s\n", mood_name);
882 ret = load_mood(row, &m, errmsg);
885 close_current_mood();
887 } else { /* load dummy mood */
888 close_current_mood();
889 current_mood = alloc_new_mood(NULL);
892 PARA_NOTICE_LOG("computing statistics of admissible files\n");
893 ret = audio_file_loop(&aa, add_if_admissible);
896 for (i = 0; i < statistics.num; i++) {
897 struct admissible_file_info *a = aa.array + i;
898 ret = add_to_score_table(a->aft_row, a->score);
903 ret = statistics.num;
910 * Close and re-open the current mood.
912 * This function is called on events which render the current list of
913 * admissible files useless, for example if an attribute is removed from the
916 * If no mood is currently open, the function returns success.
918 static int reload_current_mood(void)
921 char *mood_name = NULL;
923 ret = clear_score_table();
928 PARA_NOTICE_LOG("reloading %s\n", current_mood->name?
929 current_mood->name : "(dummy)");
930 if (current_mood->name)
931 mood_name = para_strdup(current_mood->name);
932 close_current_mood();
933 ret = change_current_mood(mood_name, NULL);
939 * Notification callback for the moods table.
941 * \param event Type of the event just occurred.
943 * \param data Its type depends on the event.
945 * This function performs actions required due to the occurrence of the given
946 * event. Possible actions include reload of the current mood and update of the
947 * score of an audio file.
951 int moods_event_handler(enum afs_events event, __a_unused struct para_buffer *pb,
958 * The three blob events might change the set of admissible files,
959 * so we must reload the score list.
964 if (data == moods_table || data == playlists_table)
965 return 1; /* no reload necessary for these */
966 return reload_current_mood();
967 /* these also require reload of the score table */
969 case ATTRIBUTE_REMOVE:
970 case ATTRIBUTE_RENAME:
971 return reload_current_mood();
972 /* changes to the aft only require to re-examine the audio file */
974 struct afsi_change_event_data *aced = data;
975 return mood_update_audio_file(aced->aft_row, aced->old_afsi);
978 case AUDIO_FILE_RENAME:
980 return mood_update_audio_file(data, NULL);
981 case AUDIO_FILE_REMOVE:
982 return mood_delete_audio_file(data);