2 * Copyright (C) 2007-2009 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. */
22 * Contains statistical data of the currently admissible audio files.
24 * It is used to assign normalized score values to each admissible audio file.
26 struct afs_statistics {
27 /** Sum of num played over all admissible files. */
28 int64_t num_played_sum;
29 /** Sum of last played times over all admissible files. */
30 int64_t last_played_sum;
31 /** Quadratic deviation of num played time. */
32 int64_t num_played_qd;
33 /** Quadratic deviation of last played time. */
34 int64_t last_played_qd;
35 /** Number of admissible files */
38 struct afs_statistics statistics;
41 * Each line of the current mood corresponds to a mood_item.
44 /** The method this line is referring to. */
45 const struct mood_method *method;
46 /** The data structure computed by the mood parser. */
48 /** The given score value, or zero if none was given. */
50 /** Non-zero if random scoring was requested. */
52 /** Whether the "not" keyword was given in the mood line. */
54 /** The position in the list of items. */
55 struct list_head mood_item_node;
59 * Created from the mood definition by mood_open().
61 * When a mood is opened, each line of its definition is investigated, and a
62 * corresponding mood item is produced. Each mood line starts with \p accept,
63 * \p deny, or \p score which determines the type of the mood line. For each
64 * such type a linked list is maintained whose entries are the mood items.
66 * \sa mood_item, mood_open().
69 /** The name of this mood. */
71 /** The list of mood items of type \p accept. */
72 struct list_head accept_list;
73 /** The list of mood items of type \p deny. */
74 struct list_head deny_list;
75 /** The list of mood items of type \p score. */
76 struct list_head score_list;
79 static struct mood *current_mood;
82 * Rough approximation to sqrt.
84 * \param x Integer of which to calculate the sqrt.
86 * \return An integer res with res * res <= x.
88 static uint64_t int_sqrt(uint64_t x)
90 uint64_t op, res, one = 1;
99 if (op >= res + one) {
100 op = op - (res + one);
106 // PARA_NOTICE_LOG("sqrt(%llu) = %llu\n", x, res);
110 /* returns 1 if row matches score item, negative otherwise */
111 static int add_item_score(const struct osl_row *row, struct mood_item *item, long *score,
114 struct afs_info afsi;
115 struct afh_info afhi;
119 *score_arg_sum += item->random_score? 100 : PARA_ABS(item->score_arg);
122 ret = get_afsi_of_row(row, &afsi);
125 ret = get_afhi_of_row(row, &afhi);
128 ret = get_audio_file_path_of_row(row, &path);
131 ret = item->method->score_function(path, &afsi, &afhi,
133 if ((ret < 0 && !item->logical_not) || (ret >= 0 && item->logical_not))
134 return -1; /* no match */
136 if (item->random_score)
137 *score += PARA_ABS(ret) * para_random(100);
139 *score += PARA_ABS(ret) * item->score_arg;
143 static int compute_mood_score(const struct osl_row *aft_row, struct mood *m,
146 struct mood_item *item;
148 long score_arg_sum = 0, score = 0;
152 /* reject audio file if it matches any entry in the deny list */
153 list_for_each_entry(item, &m->deny_list, mood_item_node)
154 if (add_item_score(aft_row, item, &score, &score_arg_sum) > 0)
155 return -E_NOT_ADMISSIBLE;
156 list_for_each_entry(item, &m->accept_list, mood_item_node)
157 if (add_item_score(aft_row, item, &score, &score_arg_sum) > 0)
159 /* reject if there is no matching entry in the accept list */
160 if (!match && !list_empty(&m->accept_list))
161 return -E_NOT_ADMISSIBLE;
162 list_for_each_entry(item, &m->score_list, mood_item_node)
163 add_item_score(aft_row, item, &score, &score_arg_sum);
165 score /= score_arg_sum;
170 static void cleanup_list_entry(struct mood_item *item)
172 if (item->method && item->method->cleanup)
173 item->method->cleanup(item->parser_data);
175 free(item->parser_data);
176 list_del(&item->mood_item_node);
180 static void destroy_mood(struct mood *m)
182 struct mood_item *tmp, *item;
186 list_for_each_entry_safe(item, tmp, &m->accept_list, mood_item_node)
187 cleanup_list_entry(item);
188 list_for_each_entry_safe(item, tmp, &m->deny_list, mood_item_node)
189 cleanup_list_entry(item);
190 list_for_each_entry_safe(item, tmp, &m->score_list, mood_item_node)
191 cleanup_list_entry(item);
196 static struct mood *alloc_new_mood(const char *name)
198 struct mood *m = para_calloc(sizeof(struct mood));
199 m->name = para_strdup(name);
200 INIT_LIST_HEAD(&m->accept_list);
201 INIT_LIST_HEAD(&m->deny_list);
202 INIT_LIST_HEAD(&m->score_list);
206 /** The different types of a mood line. */
207 enum mood_line_type {
218 /** Data passed to the parser of a mood line. */
219 struct mood_line_parser_data {
220 /** The mood this mood line belongs to. */
222 /** The line number in the mood definition. */
227 * <accept [with score <score>] | deny [with score <score>] | score <score>>
228 * [if] [not] <mood_method> [options]
229 * <score> is either an integer or "random" which assigns a random score to
233 static int parse_mood_line(char *mood_line, void *data)
235 struct mood_line_parser_data *mlpd = data;
240 enum mood_line_type mlt = ML_INVALID;
241 struct mood_item *mi = NULL;
244 ret = create_argv(mood_line, " \t", &argv);
248 if (!num_words) /* empty line */
251 if (**w == '#') /* comment */
253 if (!strcmp(*w, "accept"))
255 else if (!strcmp(*w, "deny"))
257 else if (!strcmp(*w, "score"))
259 ret = -E_MOOD_SYNTAX;
260 if (mlt == ML_INVALID)
262 mi = para_calloc(sizeof(struct mood_item));
263 if (mlt != ML_SCORE) {
264 ret = -E_MOOD_SYNTAX;
268 if (strcmp(*w, "with"))
273 if (strcmp(*w, "score"))
276 if (mlt == ML_SCORE || !strcmp(*w, "score")) {
277 ret = -E_MOOD_SYNTAX;
281 if (strcmp(*w, "random")) {
282 mi->random_score = 0;
283 ret = para_atoi32(*w, &mi->score_arg);
287 mi->random_score = 1;
289 goto success; /* the line "score random" is valid */
293 ret = -E_MOOD_SYNTAX;
298 if (!strcmp(*w, "if")) {
299 ret = -E_MOOD_SYNTAX;
304 if (!strcmp(*w, "not")) {
305 ret = -E_MOOD_SYNTAX;
312 for (i = 0; mood_methods[i].parser; i++) {
313 if (strcmp(*w, mood_methods[i].name))
317 ret = -E_MOOD_SYNTAX;
318 if (!mood_methods[i].parser)
320 ret = mood_methods[i].parser(num_words - 1 - (w - argv), w,
324 mi->method = &mood_methods[i];
327 if (mlt == ML_ACCEPT)
328 para_list_add(&mi->mood_item_node, &mlpd->m->accept_list);
329 else if (mlt == ML_DENY)
330 para_list_add(&mi->mood_item_node, &mlpd->m->deny_list);
332 para_list_add(&mi->mood_item_node, &mlpd->m->score_list);
334 PARA_DEBUG_LOG("%s entry added, method: %p\n", mlt == ML_ACCEPT? "accept" :
335 (mlt == ML_DENY? "deny" : "score"), mi->method);
342 free(mi->parser_data);
348 static int load_mood(const struct osl_row *mood_row, struct mood **m)
351 struct osl_object mood_def;
352 struct mood_line_parser_data mlpd = {.line_num = 0};
353 int ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
359 mlpd.m = alloc_new_mood(mood_name);
360 ret = for_each_line_ro(mood_def.data, mood_def.size,
361 parse_mood_line, &mlpd);
362 osl_close_disk_object(&mood_def);
364 PARA_ERROR_LOG("unable to load mood %s: %s\n", mlpd.m->name,
365 para_strerror(-ret));
366 destroy_mood(mlpd.m);
373 static int check_mood(struct osl_row *mood_row, void *data)
375 struct para_buffer *pb = data;
377 struct osl_object mood_def;
378 struct mood_line_parser_data mlpd = {.line_num = 0};
380 int ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
383 para_printf(pb, "failed to get mood definition: %s\n",
384 para_strerror(-ret));
387 if (!*mood_name) /* ignore dummy row */
389 ret = para_printf(pb, "checking mood %s...\n", mood_name);
392 ret = for_each_line_ro(mood_def.data, mood_def.size,
393 parse_mood_line, &mlpd);
395 para_printf(pb, "%s line %u: %s\n", mood_name, mlpd.line_num,
396 para_strerror(-ret));
398 osl_close_disk_object(&mood_def);
403 * Check all moods for syntax errors.
405 * \param fd The afs socket.
406 * \param query Unused.
408 void mood_check_callback(int fd, __a_unused const struct osl_object *query)
410 struct para_buffer pb = {
413 .max_size_handler = pass_buffer_as_shm
416 int ret = para_printf(&pb, "checking moods...\n");
419 osl_rbtree_loop(moods_table, BLOBCOL_ID, &pb,
422 pass_buffer_as_shm(pb.buf, pb.offset, &fd);
427 static unsigned int_log2(uint64_t x)
439 static int64_t normalized_value(int64_t x, int64_t n, int64_t sum, int64_t qd)
443 return 100 * (n * x - sum) / (int64_t)int_sqrt(n * qd);
446 static long compute_num_played_score(struct afs_info *afsi)
448 return -normalized_value(afsi->num_played, statistics.num,
449 statistics.num_played_sum, statistics.num_played_qd);
452 static long compute_last_played_score(struct afs_info *afsi)
454 return -normalized_value(afsi->last_played, statistics.num,
455 statistics.last_played_sum, statistics.last_played_qd);
458 static long compute_dynamic_score(const struct osl_row *aft_row)
460 struct afs_info afsi;
461 int64_t score, nscore = 0, lscore = 0;
464 ret = get_afsi_of_row(aft_row, &afsi);
467 nscore = compute_num_played_score(&afsi);
468 lscore = compute_last_played_score(&afsi);
469 score = nscore + lscore;
473 static int add_afs_statistics(const struct osl_row *row)
476 struct afs_info afsi;
479 ret = get_afsi_of_row(row, &afsi);
483 x = afsi.last_played;
484 s = statistics.last_played_sum;
486 statistics.last_played_qd += (x - s / n) * (x - s / n) * n / (n + 1);
487 statistics.last_played_sum += x;
490 s = statistics.num_played_sum;
492 statistics.num_played_qd += (x - s / n) * (x - s / n) * n / (n + 1);
493 statistics.num_played_sum += x;
498 static int del_afs_statistics(const struct osl_row *row)
500 uint64_t n, s, q, a, new_s;
501 struct afs_info afsi;
503 ret = get_afsi_of_row(row, &afsi);
509 memset(&statistics, 0, sizeof(statistics));
513 s = statistics.last_played_sum;
514 q = statistics.last_played_qd;
515 a = afsi.last_played;
517 statistics.last_played_sum = new_s;
518 statistics.last_played_qd = q + s * s / n - a * a
519 - new_s * new_s / (n - 1);
521 s = statistics.num_played_sum;
522 q = statistics.num_played_qd;
525 statistics.num_played_sum = new_s;
526 statistics.num_played_qd = q + s * s / n - a * a
527 - new_s * new_s / (n - 1);
534 * Structure used during mood_open().
536 * At mood open time, we look at each file in the audio file table in order to
537 * determine whether it is admissible. If a file happens to be admissible, its
538 * mood score is computed by calling each relevant mood_score_function. Next,
539 * we update the afs_statistics and add a struct admissible_file_info to a
542 * If all files have been processed that way, the final score of each
543 * admissible file is computed by adding the dynamic score (which depends on
544 * the afs_statistics) to the mood score. Finally, all audio files in the
545 * array are added to the score table and the admissible array is freed.
547 * \sa mood_method, admissible_array.
549 struct admissible_file_info
551 /** The admissible audio file. */
552 struct osl_row *aft_row;
557 /** The temporary array of admissible files. */
558 struct admissible_array {
559 /** Files are admissible wrt. this mood. */
561 /** The size of the array */
563 /** Pointer to the array of admissible files. */
564 struct admissible_file_info *array;
568 * Add an entry to the array of admissible files.
570 * \param aft_row The audio file to be added.
571 * \param private_data Pointer to a struct admissible_file_info.
573 * \return Negative on errors, positive on success.
575 static int add_if_admissible(struct osl_row *aft_row, void *data)
577 struct admissible_array *aa = data;
581 ret = compute_mood_score(aft_row, aa->m, &score);
583 return (ret == -E_NOT_ADMISSIBLE)? 1 : ret;
584 if (statistics.num >= aa->size) {
587 aa->array = para_realloc(aa->array,
588 aa->size * sizeof(struct admissible_file_info));
590 aa->array[statistics.num].aft_row = aft_row;
591 aa->array[statistics.num].score = score;
592 ret = add_afs_statistics(aft_row);
599 * Compute the new quadratic deviation in case one element changes.
601 * \param n Number of elements.
602 * \param old_qd The quadratic deviation before the change.
603 * \param old_val The value that was replaced.
604 * \param new_val The replacement value.
605 * \param old_sum The sum of all elements before the update.
607 * \return The new quadratic deviation resulting from replacing old_val
610 * Given n real numbers a_1, ..., a_n, their sum S = a_1 + ... + a_n,
611 * their quadratic deviation
613 * q = (a_1 - S/n)^2 + ... + (a_n - S/n)^2,
615 * and a real number b, the quadratic deviation q' of a_1,...a_{n-1}, b (ie.
616 * the last number a_n was replaced by b) may be computed in O(1) time in terms
617 * of n, q, a_n, b, and S as
619 * q' = q + d * s - (2 * S + d) * d / n,
621 * where d = b - a_n, and s = b + a_n.
623 * Example: n = 3, a_1 = 3, a_2 = 5, a_3 = 7, b = 10. Then S = 15, q = 8, d = 3,
626 * q + d * s - (2 * S + d) * d / n = 8 + 51 - 33 = 26,
628 * which equals q' = (3 - 6)^2 + (5 - 6)^2 + (10 - 6)^2.
631 _static_inline_ int64_t update_quadratic_deviation(int64_t n, int64_t old_qd,
632 int64_t old_val, int64_t new_val, int64_t old_sum)
634 int64_t delta = new_val - old_val;
635 int64_t sigma = new_val + old_val;
636 return old_qd + delta * sigma - (2 * old_sum + delta) * delta / n;
639 static int update_afs_statistics(struct afs_info *old_afsi, struct afs_info *new_afsi)
642 int ret = get_num_admissible_files(&n);
648 statistics.last_played_qd = update_quadratic_deviation(n,
649 statistics.last_played_qd, old_afsi->last_played,
650 new_afsi->last_played, statistics.last_played_sum);
651 statistics.last_played_sum += new_afsi->last_played - old_afsi->last_played;
653 statistics.num_played_qd = update_quadratic_deviation(n,
654 statistics.num_played_qd, old_afsi->num_played,
655 new_afsi->num_played, statistics.num_played_sum);
656 statistics.num_played_sum += new_afsi->num_played - old_afsi->num_played;
660 static int add_to_score_table(const struct osl_row *aft_row, long mood_score)
662 long score = (compute_dynamic_score(aft_row) + mood_score) / 3;
663 return score_add(aft_row, score);
666 static int delete_from_statistics_and_score_table(const struct osl_row *aft_row)
668 int ret = del_afs_statistics(aft_row);
671 return score_delete(aft_row);
675 * Delete one entry from the statistics and from the score table.
677 * \param aft_row The audio file which is no longer admissible.
679 * \return Positive on success, negative on errors.
681 * \sa score_delete().
683 static int mood_delete_audio_file(const struct osl_row *aft_row)
687 ret = row_belongs_to_score_table(aft_row, NULL);
690 if (!ret) /* not admissible, nothing to do */
692 return delete_from_statistics_and_score_table(aft_row);
696 * Compute the new score of an audio file wrt. the current mood.
698 * \param aft_row Determines the audio file.
699 * \param old_afsi The audio file selector info before updating.
701 * The \a old_afsi argument may be \p NULL which indicates that no changes to
702 * the audio file info were made.
704 * \return Positive on success, negative on errors.
706 static int mood_update_audio_file(const struct osl_row *aft_row,
707 struct afs_info *old_afsi)
710 int ret, is_admissible, was_admissible = 0;
711 struct afs_info afsi;
715 return 1; /* nothing to do */
716 ret = row_belongs_to_score_table(aft_row, &rank);
719 was_admissible = ret;
720 ret = compute_mood_score(aft_row, current_mood, &score);
721 is_admissible = (ret > 0);
722 if (!was_admissible && !is_admissible)
724 if (was_admissible && !is_admissible)
725 return delete_from_statistics_and_score_table(aft_row);
726 if (!was_admissible && is_admissible) {
727 ret = add_afs_statistics(aft_row);
730 return add_to_score_table(aft_row, score);
733 ret = get_afsi_of_row(aft_row, &afsi);
737 ret = update_afs_statistics(old_afsi, &afsi);
741 score += compute_num_played_score(&afsi);
742 score += compute_last_played_score(&afsi);
744 PARA_DEBUG_LOG("score: %li\n", score);
745 percent = (score + 100) / 3;
748 else if (percent < 0)
750 PARA_DEBUG_LOG("moving from rank %u to %lu%%\n", rank, percent);
751 return score_update(aft_row, percent);
754 static void log_statistics(void)
756 unsigned n = statistics.num;
759 PARA_NOTICE_LOG("no admissible files\n");
762 PARA_INFO_LOG("last_played mean: %lli, last_played sigma: %llu\n",
763 (long long int)(statistics.last_played_sum / n),
764 (long long unsigned)int_sqrt(statistics.last_played_qd / n));
765 PARA_INFO_LOG("num_played mean: %lli, num_played sigma: %llu\n",
766 (long long int)statistics.num_played_sum / n,
767 (long long unsigned)int_sqrt(statistics.num_played_qd / n));
771 * Close the current mood.
773 * Free all resources of the current mood which were allocated during
776 void close_current_mood(void)
778 destroy_mood(current_mood);
780 memset(&statistics, 0, sizeof(statistics));
784 * Change the current mood.
786 * \param mood_name The name of the mood to open.
788 * If \a mood_name is \a NULL, load the dummy mood that accepts every audio file
789 * and uses a scoring method based only on the \a last_played information.
791 * If there is already an open mood, it will be closed first.
793 * \return Positive on success, negative on errors. Loading the dummy mood
796 * \sa struct admissible_file_info, struct admissible_array, struct
797 * afs_info::last_played, mood_close().
799 int change_current_mood(char *mood_name)
802 struct admissible_array aa = {
810 struct osl_object obj = {
812 .size = strlen(mood_name) + 1
814 ret = osl(osl_get_row(moods_table, BLOBCOL_NAME, &obj, &row));
816 PARA_NOTICE_LOG("no such mood: %s\n", mood_name);
819 ret = load_mood(row, &m);
822 close_current_mood();
825 close_current_mood();
826 current_mood = alloc_new_mood("dummy");
829 PARA_NOTICE_LOG("computing statistics of admissible files\n");
830 ret = audio_file_loop(&aa, add_if_admissible);
834 PARA_INFO_LOG("%d admissible files \n", statistics.num);
835 for (i = 0; i < statistics.num; i++) {
836 struct admissible_file_info *a = aa.array + i;
837 ret = add_to_score_table(a->aft_row, a->score);
841 PARA_NOTICE_LOG("loaded mood %s\n", current_mood->name);
842 ret = statistics.num;
848 * Close and re-open the current mood.
850 * This function is used if changes to the audio file table or the
851 * attribute table were made that render the current list of admissible
852 * files useless. For example, if an attribute is removed from the
853 * attribute table, this function is called.
855 * \return Positive on success, negative on errors. If no mood is currently
856 * open, the function returns success.
858 * \sa mood_open(), mood_close().
860 int reload_current_mood(void)
863 char *mood_name = NULL;
867 PARA_NOTICE_LOG("reloading %s\n", current_mood->name?
868 current_mood->name : "(dummy)");
869 if (current_mood->name)
870 mood_name = para_strdup(current_mood->name);
871 close_current_mood();
872 ret = change_current_mood(mood_name);
877 int moods_event_handler(enum afs_events event, __a_unused struct para_buffer *pb,
882 * The three blob events might change the set of admissible files,
883 * so we must reload the score list.
888 if (data == moods_table || data == playlists_table)
889 return 1; /* no reload necessary for these */
890 return reload_current_mood();
891 /* these also require reload of the score table */
893 case ATTRIBUTE_REMOVE:
894 case ATTRIBUTE_RENAME:
895 return reload_current_mood();
896 /* changes to the aft only require to re-examine the audio file */
898 struct afsi_change_event_data *aced = data;
899 return mood_update_audio_file(aced->aft_row, aced->old_afsi);
902 case AUDIO_FILE_RENAME:
904 return mood_update_audio_file(data, NULL);
905 case AUDIO_FILE_REMOVE:
906 return mood_delete_audio_file(data);