2 * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file mood.c Paraslash's mood handling functions. */
17 * Contains statistical data of the currently admissible audio files.
19 * It is used to assign normalized score values to each admissbile audio file.
21 struct afs_statistics {
22 /** sum of num played over all admissible files */
23 int64_t num_played_sum;
24 /** sum of last played times over all admissible files */
25 int64_t last_played_sum;
26 /** quadratic deviation of num played time */
27 int64_t num_played_qd;
28 /** quadratic deviation of last played time */
29 int64_t last_played_qd;
30 /** number of admissible files */
33 struct afs_statistics statistics;
36 * Assign scores according to a mood_method.
38 * Each mood_method has its own mood_score_function. The first parameter passed
39 * to that function is a pointer to a row of the audio file table. It
40 * determines the audio file for which a score is to be assigned. The second
41 * argument depends on the mood method this function is used for. It usually is
42 * the argument given at the end of a mood line.
44 * Mood score functions must return values between -100 and +100 inclisively.
45 * Boolean score functions should always return either -100 or +100.
47 * \sa struct mood_method, mood_parser.
49 typedef int mood_score_function(const struct osl_row*, void *);
52 * Preprocess a mood line.
54 * The mood_parser of a mood_method is called once at mood open time for each
55 * line of the current mood definition that contains the mood_method's name as
56 * a keyword. The line is passed to the mood_parser as the first argument. The
57 * mood_parser must determine whether the line is syntactically correct and
58 * return a positive value if so and a negative value otherwise.
60 * Some mood parsers preprocess the data given in the mood line to compute a
61 * structure which depends of the particular mood_method and which is used
62 * later in the mood_score_function of the mood_method. The mood_parser may
63 * store a pointer to its structure via the second argument.
65 * \sa mood_open(), mood_cleanup_function, mood_score_function.
67 typedef int mood_parser(const char *, void **);
70 * Deallocate resources which were allocated by the mood_parser.
72 * This optional function of a mood_method is used to free any resources
73 * allocated in mood_open() by the mood_parser. The argument passed is a
74 * pointer to the mood_method specific data structure that was returned by the
79 typedef void mood_cleanup_function(void *);
82 * Used for scoring and to determine whether a file is admissible.
85 /* The name of the method. */
87 /** Pointer to the mood parser. */
89 /** Pointer to the score function */
90 mood_score_function *score_function;
91 /** Optional cleanup function. */
92 mood_cleanup_function *cleanup;
96 * Each line of the current mood corresponds to a mood_item.
99 /** The method this line is referring to. */
100 const struct mood_method *method;
101 /** The data structure computed by the mood parser. */
103 /** The given score value, or zero if none was given. */
105 /** Non-zero if random scoring was requested. */
107 /** Whether the "not" keyword was given in the mood line. */
109 /** The position in the list of items. */
110 struct list_head mood_item_node;
114 * Created from the mood definition by mood_open().
116 * When a mood is opened, each line of its definition is investigated, and a
117 * corresponding mood item is produced. Each mood line starts with \p accept,
118 * \p deny, or \p score which determins the type of the mood line. For each
119 * such type a linked list is maintained whose entries are the mood items.
121 * \sa mood_item, mood_open().
124 /** The name of this mood. */
126 /** The list of mood items of type \p accept. */
127 struct list_head accept_list;
128 /** The list of mood items of type \p deny. */
129 struct list_head deny_list;
130 /** The list of mood items of type \p score. */
131 struct list_head score_list;
134 static struct mood *current_mood;
137 * Rough approximation to sqrt.
139 * \param x Integer of which to calculate the sqrt.
141 * \return An integer res with res * res <= x.
143 static uint64_t int_sqrt(uint64_t x)
145 uint64_t op, res, one = 1;
154 if (op >= res + one) {
155 op = op - (res + one);
161 // PARA_NOTICE_LOG("sqrt(%llu) = %llu\n", x, res);
165 static int mm_played_rarely_score_function(const struct osl_row *row,
166 __a_unused void *ignored)
168 struct afs_info afsi;
170 int ret = get_afsi_of_row(row, &afsi);
174 ret = get_num_admissible_files(&num);
177 if (statistics.num_played_sum - num * afsi.num_played
178 > int_sqrt(statistics.num_played_qd * num))
183 static int mm_played_rarely_parser(const char *arg, __a_unused void **ignored)
186 PARA_WARNING_LOG("ignored junk at eol: %s\n", arg);
190 static int mm_name_like_score_function(const struct osl_row *row, void *preg)
193 int ret = get_audio_file_path_of_row(row, &path);
197 ret = regexec((regex_t *)preg, path, 42, NULL, 0);
198 return (ret == REG_NOMATCH)? -100 : 100;
201 static int mm_name_like_parser(const char *arg, void **regex)
203 regex_t *preg = para_malloc(sizeof(*preg));
204 int ret = regcomp(preg, arg, REG_NOSUB);
208 return -E_MOOD_REGEX;
214 static void mm_name_like_cleanup(void *preg)
220 static int mm_is_set_parser(const char *arg, void **bitnum)
222 unsigned char *c = para_malloc(1);
223 int ret = get_attribute_bitnum_by_name(arg, c);
232 static int mm_is_set_score_function(const struct osl_row *row, void *bitnum)
234 unsigned char *bn = bitnum;
235 struct afs_info afsi;
236 int ret = get_afsi_of_row(row, &afsi);
240 if (afsi.attributes & (1ULL << *bn))
245 /* returns 1 if row matches score item, -1 otherwise */
246 static int add_item_score(const struct osl_row *row, struct mood_item *item, long *score,
251 *score_arg_sum += item->random_score? 100 : PARA_ABS(item->score_arg);
253 ret = item->method->score_function(row, item->parser_data);
254 if ((ret < 0 && !item->logical_not) || (ret >= 0 && item->logical_not))
255 return -1; /* no match */
257 if (item->random_score)
258 *score += PARA_ABS(ret) * para_random(100);
260 *score += PARA_ABS(ret) * item->score_arg;
264 static int compute_mood_score(const struct osl_row *aft_row, struct mood *m,
267 struct mood_item *item;
269 long score_arg_sum = 0, score = 0;
273 /* reject audio file if it matches any entry in the deny list */
274 list_for_each_entry(item, &m->deny_list, mood_item_node)
275 if (add_item_score(aft_row, item, &score, &score_arg_sum) > 0)
276 return -E_NOT_ADMISSIBLE;
277 list_for_each_entry(item, &m->accept_list, mood_item_node)
278 if (add_item_score(aft_row, item, &score, &score_arg_sum) > 0)
280 /* reject if there is no matching entry in the accept list */
281 if (!match && !list_empty(&m->accept_list))
282 return -E_NOT_ADMISSIBLE;
283 list_for_each_entry(item, &m->score_list, mood_item_node)
284 add_item_score(aft_row, item, &score, &score_arg_sum);
286 score /= score_arg_sum;
291 static const struct mood_method mood_methods[] = {
293 .parser = mm_played_rarely_parser,
294 .score_function = mm_played_rarely_score_function,
295 .name = "played_rarely"
298 .parser = mm_is_set_parser,
299 .score_function = mm_is_set_score_function,
303 .parser = mm_name_like_parser,
304 .score_function = mm_name_like_score_function,
305 .cleanup = mm_name_like_cleanup,
313 static void cleanup_list_entry(struct mood_item *item)
315 if (item->method && item->method->cleanup)
316 item->method->cleanup(item->parser_data);
318 free(item->parser_data);
319 list_del(&item->mood_item_node);
323 static void destroy_mood(struct mood *m)
325 struct mood_item *tmp, *item;
329 list_for_each_entry_safe(item, tmp, &m->accept_list, mood_item_node)
330 cleanup_list_entry(item);
331 list_for_each_entry_safe(item, tmp, &m->deny_list, mood_item_node)
332 cleanup_list_entry(item);
333 list_for_each_entry_safe(item, tmp, &m->score_list, mood_item_node)
334 cleanup_list_entry(item);
339 static struct mood *alloc_new_mood(const char *name)
341 struct mood *m = para_calloc(sizeof(struct mood));
342 m->name = para_strdup(name);
343 INIT_LIST_HEAD(&m->accept_list);
344 INIT_LIST_HEAD(&m->deny_list);
345 INIT_LIST_HEAD(&m->score_list);
349 /** The different types of a mood line. */
350 enum mood_line_type {
362 * <accept [with score <score>] | deny [with score <score>] | score <score>>
363 * [if] [not] <mood_method> [options]
364 * <score> is either an integer or "random" which assigns a random score to
368 static int parse_mood_line(char *mood_line, void *data)
370 struct mood *m = data;
376 enum mood_line_type mlt = ML_INVALID;
377 struct mood_item *mi = NULL;
378 char *buf = para_strdup(mood_line);
380 num_words = split_args(buf, &argv, delim);
382 if (!num_words) /* empty line */
385 if (**w == '#') /* comment */
387 if (!strcmp(*w, "accept"))
389 else if (!strcmp(*w, "deny"))
391 else if (!strcmp(*w, "score"))
393 ret = -E_MOOD_SYNTAX;
394 if (mlt == ML_INVALID)
396 mi = para_calloc(sizeof(struct mood_item));
397 if (mlt != ML_SCORE) {
398 ret = -E_MOOD_SYNTAX;
402 if (!strcmp(*w, "with")) {
408 if (mlt == ML_SCORE || !strcmp(*w, "score")) {
409 ret = -E_MOOD_SYNTAX;
413 if (strcmp(*w, "random")) {
414 mi->random_score = 0;
415 ret = para_atol(*w, &mi->score_arg);
419 mi->random_score = 1;
421 goto success; /* the line "score random" is valid */
425 ret = -E_MOOD_SYNTAX;
429 if (!strcmp(*w, "if")) {
430 ret = -E_MOOD_SYNTAX;
435 if (!strcmp(*w, "not")) {
436 ret = -E_MOOD_SYNTAX;
443 for (i = 0; mood_methods[i].parser; i++) {
444 if (strcmp(*w, mood_methods[i].name))
448 ret = -E_MOOD_SYNTAX;
449 if (!mood_methods[i].parser)
452 ret = mood_methods[i].parser(*w, &mi->parser_data);
455 mi->method = &mood_methods[i];
457 if (mlt == ML_ACCEPT)
458 para_list_add(&mi->mood_item_node, &m->accept_list);
459 else if (mlt == ML_DENY)
460 para_list_add(&mi->mood_item_node, &m->deny_list);
462 para_list_add(&mi->mood_item_node, &m->score_list);
463 PARA_DEBUG_LOG("%s entry added, method: %p\n", mlt == ML_ACCEPT? "accept" :
464 (mlt == ML_DENY? "deny" : "score"), mi->method);
472 free(mi->parser_data);
478 static int load_mood(const struct osl_row *mood_row, struct mood **m)
481 struct osl_object objs[NUM_BLOB_COLUMNS];
483 ret = osl_get_object(moods_table, mood_row, BLOBCOL_NAME, &objs[BLOBCOL_NAME]);
486 if (objs[BLOBCOL_NAME].size <= 1)
488 ret = osl_open_disk_object(moods_table, mood_row, BLOBCOL_DEF, &objs[BLOBCOL_DEF]);
491 *m = alloc_new_mood((char*)objs[BLOBCOL_NAME].data);
492 ret = for_each_line_ro(objs[BLOBCOL_DEF].data, objs[BLOBCOL_DEF].size,
493 parse_mood_line, *m);
494 osl_close_disk_object(&objs[BLOBCOL_DEF]);
496 PARA_ERROR_LOG("unable to load mood %s: %s\n", (*m)->name,
497 PARA_STRERROR(-ret));
501 PARA_INFO_LOG("loaded mood %s\n", (*m)->name);
505 /* returns -E_MOOD_LOADED on _success_ to terminate the loop */
506 static int mood_loop(struct osl_row *mood_row, void *data)
508 struct mood **m = data;
509 int ret = load_mood(mood_row, m);
511 if (ret != -E_DUMMY_ROW)
512 PARA_NOTICE_LOG("invalid mood (%d), trying next mood\n", ret);
515 return -E_MOOD_LOADED;
518 static int load_first_available_mood(struct mood **m)
520 int ret = osl_rbtree_loop(moods_table, BLOBCOL_NAME, m,
522 if (ret == -E_MOOD_LOADED) /* success */
525 return ret; /* error */
526 PARA_NOTICE_LOG("no valid mood found\n");
531 static unsigned int_log2(uint64_t x)
543 static int64_t normalized_value(int64_t x, int64_t n, int64_t sum, int64_t qd)
547 return 100 * (n * x - sum) / (int64_t)int_sqrt(n * qd);
550 static long compute_num_played_score(struct afs_info *afsi)
552 return -normalized_value(afsi->num_played, statistics.num,
553 statistics.num_played_sum, statistics.num_played_qd);
556 static long compute_last_played_score(struct afs_info *afsi)
558 return -normalized_value(afsi->last_played, statistics.num,
559 statistics.last_played_sum, statistics.last_played_qd);
562 static long compute_dynamic_score(const struct osl_row *aft_row)
564 struct afs_info afsi;
565 int64_t score, nscore = 0, lscore = 0;
568 ret = get_afsi_of_row(aft_row, &afsi);
571 nscore = compute_num_played_score(&afsi);
572 lscore = compute_last_played_score(&afsi);
573 score = nscore + lscore;
577 static int add_afs_statistics(const struct osl_row *row)
580 struct afs_info afsi;
583 ret = get_afsi_of_row(row, &afsi);
587 x = afsi.last_played;
588 s = statistics.last_played_sum;
590 statistics.last_played_qd += (x - s / n) * (x - s / n) * n / (n + 1);
591 statistics.last_played_sum += x;
594 s = statistics.num_played_sum;
596 statistics.num_played_qd += (x - s / n) * (x - s / n) * n / (n + 1);
597 statistics.num_played_sum += x;
602 static int del_afs_statistics(const struct osl_row *row)
604 uint64_t n, s, q, a, new_s;
605 struct afs_info afsi;
607 ret = get_afsi_of_row(row, &afsi);
613 memset(&statistics, 0, sizeof(statistics));
617 s = statistics.last_played_sum;
618 q = statistics.last_played_qd;
619 a = afsi.last_played;
621 statistics.last_played_sum = new_s;
622 statistics.last_played_qd = q + s * s / n - a * a
623 - new_s * new_s / (n - 1);
625 s = statistics.num_played_sum;
626 q = statistics.num_played_qd;
629 statistics.num_played_sum = new_s;
630 statistics.num_played_qd = q + s * s / n - a * a
631 - new_s * new_s / (n - 1);
638 * Structure used during mood_open().
640 * At mood open time, we look at each file in the audio file table in order to
641 * determine whether it is admissible. If a file happens to be admissible, its
642 * mood score is computed by calling each relevant mood_score_function. Next,
643 * we update the afs_statistics and add a struct admissible_file_info to a
646 * If all files have been processed that way, the final score of each
647 * admissible file is computed by adding the dynamic score (which depends on
648 * the afs_statistics) to the mood score. Finally, all audio files in the
649 * array are added to the score table and the admissible array is freed.
651 * \sa mood_method, admissible_array.
653 struct admissible_file_info
655 /** The admissible audio file. */
656 struct osl_row *aft_row;
661 /** The temporary array of admissible files. */
662 struct admissible_array {
663 /** Files are admissible wrt. this mood. */
665 /** The size of the array */
667 /** Pointer to the array of admissible files. */
668 struct admissible_file_info *array;
672 * Add an entry to the array of admissible files.
674 * \param aft_row The audio file to be added.
675 * \param private_data Pointer to a struct admissible_file_info.
677 * \return Negative on errors, positive on success.
679 static int add_if_admissible(struct osl_row *aft_row, void *data)
681 struct admissible_array *aa = data;
685 ret = compute_mood_score(aft_row, aa->m, &score);
687 return (ret == -E_NOT_ADMISSIBLE)? 1 : ret;
688 if (statistics.num >= aa->size) {
691 aa->array = para_realloc(aa->array,
692 aa->size * sizeof(struct admissible_file_info));
694 aa->array[statistics.num].aft_row = aft_row;
695 aa->array[statistics.num].score = score;
696 ret = add_afs_statistics(aft_row);
703 * Compute the new quadratic deviation in case one element changes.
705 * \param n Number of elements.
706 * \param old_qd The quadratic deviation before the change.
707 * \param old_val The value that was repaced.
708 * \param new_val The replacement value.
709 * \param old_sum The sum of all elements before the update.
711 * \return The new quadratic deviation resulting from replacing old_val
714 * Given n real numbers a_1, ..., a_n, their sum S = a_1 + ... + a_n,
715 * their quadratic deviation
717 * q = (a_1 - S/n)^2 + ... + (a_n - S/n)^2,
719 * and a real number b, the quadratic deviation q' of a_1,...a_{n-1}, b (ie.
720 * the last number a_n was replaced by b) may be computed in O(1) time in terms
721 * of n, q, a_n, b, and S as
723 * q' = q + d * s - (2 * S + d) * d / n,
725 * where d = b - a_n, and s = b + a_n.
727 * Example: n = 3, a_1 = 3, a_2 = 5, a_3 = 7, b = 10. Then S = 15, q = 8, d = 3,
730 * q + d * s - (2 * S + d) * d / n = 8 + 51 - 33 = 26,
732 * which equals q' = (3 - 6)^2 + (5 - 6)^2 + (10 - 6)^2.
735 _static_inline_ int64_t update_quadratic_deviation(int64_t n, int64_t old_qd,
736 int64_t old_val, int64_t new_val, int64_t old_sum)
738 int64_t delta = new_val - old_val;
739 int64_t sigma = new_val + old_val;
740 return old_qd + delta * sigma - (2 * old_sum + delta) * delta / n;
743 static int update_afs_statistics(struct afs_info *old_afsi, struct afs_info *new_afsi)
746 int ret = get_num_admissible_files(&n);
752 statistics.last_played_qd = update_quadratic_deviation(n,
753 statistics.last_played_qd, old_afsi->last_played,
754 new_afsi->last_played, statistics.last_played_sum);
755 statistics.last_played_sum += new_afsi->last_played - old_afsi->last_played;
757 statistics.num_played_qd = update_quadratic_deviation(n,
758 statistics.num_played_qd, old_afsi->num_played,
759 new_afsi->num_played, statistics.num_played_sum);
760 statistics.num_played_sum += new_afsi->num_played - old_afsi->num_played;
764 static int add_to_score_table(const struct osl_row *aft_row, long mood_score)
766 long score = (compute_dynamic_score(aft_row) + mood_score) / 3;
767 return score_add(aft_row, score);
770 static int delete_from_statistics_and_score_table(const struct osl_row *aft_row)
772 int ret = del_afs_statistics(aft_row);
775 return score_delete(aft_row);
779 * Delete one entry from the statitics and from the score table.
781 * \param aft_row The audio file which is no longer admissible.
783 * \return Positive on success, negative on errors.
785 * \sa score_delete(), mood_update_audio_file().
787 int mood_delete_audio_file(const struct osl_row *aft_row)
791 ret = row_belongs_to_score_table(aft_row);
794 if (!ret) /* not admissible, nothing to do */
796 return delete_from_statistics_and_score_table(aft_row);
800 * Compute the new score of an audio file wrt. the current mood.
802 * \param aft_row Determines the audio file.
803 * \param old_afsi The audio file selector info before updating.
805 * The \a old_afsi argument may be \p NULL which indicates that no changes to
806 * the audio file info were made.
808 * \return Positive on success, negative on errors.
810 int mood_update_audio_file(const struct osl_row *aft_row, struct afs_info *old_afsi)
813 int ret, is_admissible, was_admissible = 0;
814 struct afs_info afsi;
817 return 1; /* nothing to do */
818 ret = row_belongs_to_score_table(aft_row);
821 was_admissible = ret;
822 ret = compute_mood_score(aft_row, current_mood, &score);
823 is_admissible = (ret > 0);
824 if (!was_admissible && !is_admissible)
826 if (was_admissible && !is_admissible)
827 return delete_from_statistics_and_score_table(aft_row);
828 if (!was_admissible && is_admissible) {
829 ret = add_afs_statistics(aft_row);
832 return add_to_score_table(aft_row, score);
835 ret = get_afsi_of_row(aft_row, &afsi);
839 ret = update_afs_statistics(old_afsi, &afsi);
843 score += compute_num_played_score(&afsi);
844 score += compute_last_played_score(&afsi);
846 PARA_DEBUG_LOG("score: %li\n", score);
847 percent = (score + 100) / 3;
850 else if (percent < 0)
852 PARA_DEBUG_LOG("re-inserting at %lu%%\n", percent);
853 return score_update(aft_row, percent);
856 static void log_statistics(void)
858 unsigned n = statistics.num;
861 PARA_NOTICE_LOG("no admissible files\n");
864 PARA_NOTICE_LOG("last_played mean: %lli, last_played sigma: %llu\n",
865 (long long int)(statistics.last_played_sum / n),
866 (long long unsigned)int_sqrt(statistics.last_played_qd / n));
867 PARA_NOTICE_LOG("num_played mean: %lli, num_played sigma: %llu\n",
868 (long long int)statistics.num_played_sum / n,
869 (long long unsigned)int_sqrt(statistics.num_played_qd / n));
873 * Change the current mood.
875 * \param mood_name The name of the mood to open.
877 * There are two special cases: If \a mood_name is \a NULL, load the
878 * first available mood. If \a mood_name is the empty string "", load
879 * the dummy mood that accepts every audio file and uses a scoring method
880 * based only on the \a last_played information.
882 * If there is already an open mood, it will be closed first.
884 * \return Positive on success, negative on errors. Loading the dummy mood
887 * \sa struct admissible_file_info, struct admissible_array, struct
888 * afs_info::last_played, mood_close().
890 int change_current_mood(char *mood_name)
893 struct admissible_array aa = {
900 ret = load_first_available_mood(&m);
903 destroy_mood(current_mood);
905 } else if (*mood_name) {
908 struct osl_object obj = {
910 .size = strlen(mood_name) + 1
912 ret = osl_get_row(moods_table, BLOBCOL_NAME, &obj, &row);
914 PARA_NOTICE_LOG("no such mood: %s\n", mood_name);
917 ret = load_mood(row, &m);
920 destroy_mood(current_mood);
923 destroy_mood(current_mood);
924 current_mood = alloc_new_mood("dummy");
927 PARA_NOTICE_LOG("loaded mood %s\n", current_mood->name);
928 PARA_INFO_LOG("%s\n", "computing statistics of admissible files");
929 ret = audio_file_loop(&aa, add_if_admissible);
933 PARA_NOTICE_LOG("%d admissible files \n", statistics.num);
934 for (i = 0; i < statistics.num; i++) {
935 struct admissible_file_info *a = aa.array + i;
936 ret = add_to_score_table(a->aft_row, a->score);
940 PARA_NOTICE_LOG("score add complete\n");
948 * Close the current mood.
950 * Free all resources of the current mood which were allocated during
953 void close_current_mood(void)
955 destroy_mood(current_mood);
957 memset(&statistics, 0, sizeof(statistics));
961 * Close and re-open the current mood.
963 * This function is used if changes to the audio file table or the
964 * attribute table were made that render the current list of admissible
965 * files useless. For example, if an attribute is removed from the
966 * attribute table, this function is called.
968 * \return Positive on success, negative on errors. If no mood is currently
969 * open, the function returns success.
971 * \sa mood_open(), mood_close().
973 int reload_current_mood(void)
981 mood_name = para_strdup(current_mood->name);
982 close_current_mood();
983 ret = change_current_mood(mood_name);