]> git.tuebingen.mpg.de Git - paraslash.git/blob - mood.c
Merge branch 'refs/heads/t/sqrt'
[paraslash.git] / mood.c
1 /*
2  * Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file mood.c Paraslash's mood handling functions. */
8
9 #include <regex.h>
10 #include <osl.h>
11 #include <lopsub.h>
12
13 #include "para.h"
14 #include "error.h"
15 #include "string.h"
16 #include "afh.h"
17 #include "afs.h"
18 #include "list.h"
19 #include "mm.h"
20 #include "mood.h"
21
22 /**
23  * Contains statistical data of the currently admissible audio files.
24  *
25  * It is used to assign normalized score values to each admissible audio file.
26  */
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 */
37         unsigned num;
38 };
39 static struct afs_statistics statistics;
40
41 /**
42  * Each line of the current mood corresponds to a mood_item.
43  */
44 struct 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. */
48         void *parser_data;
49         /** The given score value, or zero if none was given. */
50         int32_t score_arg;
51         /** Non-zero if random scoring was requested. */
52         int random_score;
53         /** Whether the "not" keyword was given in the mood line. */
54         int logical_not;
55         /** The position in the list of items. */
56         struct list_head mood_item_node;
57 };
58
59 /*
60  * Created from the mood definition by \ref change_current_mood().
61  *
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.
66  */
67 struct mood {
68         /** The name of this mood. */
69         char *name;
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;
76 };
77
78 /*
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.
81  */
82 static struct mood *current_mood;
83
84 /*
85  * Find the position of the most-significant set bit.
86  *
87  * Copied and slightly adapted from the linux source tree, version 4.9.39
88  * (2017-07).
89  */
90 __a_const static uint32_t fls64(uint64_t v)
91 {
92         int n = 63;
93         const uint64_t ones = ~(uint64_t)0U;
94
95         if ((v & (ones << 32)) == 0) {
96                 n -= 32;
97                 v <<= 32;
98         }
99         if ((v & (ones << (64 - 16))) == 0) {
100                 n -= 16;
101                 v <<= 16;
102         }
103         if ((v & (ones << (64 - 8))) == 0) {
104                 n -= 8;
105                 v <<= 8;
106         }
107         if ((v & (ones << (64 - 4))) == 0) {
108                 n -= 4;
109                 v <<= 4;
110         }
111         if ((v & (ones << (64 - 2))) == 0) {
112                 n -= 2;
113                 v <<= 2;
114         }
115         if ((v & (ones << (64 - 1))) == 0)
116                 n -= 1;
117         return n;
118 }
119
120 /*
121  * Compute the integer square root floor(sqrt(x)).
122  *
123  * Taken 2007 from the linux source tree.
124  */
125 __a_const static uint64_t int_sqrt(uint64_t x)
126 {
127         uint64_t op = x, res = 0, one = 1;
128
129         one = one << (fls64(x) & ~one);
130         while (one != 0) {
131                 if (op >= res + one) {
132                         op = op - (res + one);
133                         res = res + 2 * one;
134                 }
135                 res /= 2;
136                 one /= 4;
137         }
138         return res;
139 }
140
141 /*
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.
144  */
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,
147                 long *score_arg_sum)
148 {
149         int ret;
150         bool match = true;
151
152         *score_arg_sum += item->random_score? 100 : PARA_ABS(item->score_arg);
153         ret = 100;
154         if (item->method) {
155                 ret = item->method->score_function(path, afsi, afhi,
156                         item->parser_data);
157                 if ((ret < 0 && !item->logical_not) || (ret >= 0 && item->logical_not))
158                         match = false;
159         }
160         if (item->random_score)
161                 *score = PARA_ABS(ret) * para_random(100);
162         else
163                 *score = PARA_ABS(ret) * item->score_arg;
164         return match;
165 }
166
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,
169                 long *scorep)
170 {
171         struct mood_item *item;
172         int ret;
173         bool match;
174         long score_arg_sum = 0, score = 0, item_score;
175         struct afs_info afsi;
176         struct afh_info afhi;
177         char *path;
178
179         if (!m)
180                 return -E_NO_MOOD;
181         ret = get_afsi_of_row(aft_row, &afsi);
182         if (ret < 0)
183                 return ret;
184         ret = get_afhi_of_row(aft_row, &afhi);
185         if (ret < 0)
186                 return ret;
187         ret = get_audio_file_path_of_row(aft_row, &path);
188         if (ret < 0)
189                 return ret;
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,
193                         &score_arg_sum);
194                 if (match) /* not admissible */
195                         return 0;
196                 score += item_score;
197         }
198         match = false;
199         list_for_each_entry(item, &m->accept_list, mood_item_node) {
200                 ret = get_item_score(item, &afsi, &afhi, path, &item_score,
201                         &score_arg_sum);
202                 if (ret == 0)
203                         continue;
204                 match = true;
205                 score += item_score;
206         }
207         /* reject if there is no matching entry in the accept list */
208         if (!match && !list_empty(&m->accept_list))
209                 return 0;
210         list_for_each_entry(item, &m->score_list, mood_item_node) {
211                 match = get_item_score(item, &afsi, &afhi, path, &item_score,
212                         &score_arg_sum);
213                 if (match)
214                         score += item_score;
215         }
216         if (score_arg_sum)
217                 score /= score_arg_sum;
218         *scorep = score;
219         return 1;
220 }
221
222 static void cleanup_list_entry(struct mood_item *item)
223 {
224         if (item->method && item->method->cleanup)
225                 item->method->cleanup(item->parser_data);
226         else
227                 free(item->parser_data);
228         list_del(&item->mood_item_node);
229         free(item);
230 }
231
232 static void destroy_mood(struct mood *m)
233 {
234         struct mood_item *tmp, *item;
235
236         if (!m)
237                 return;
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);
244         free(m->name);
245         free(m);
246 }
247
248 static struct mood *alloc_new_mood(const char *name)
249 {
250         struct mood *m = para_calloc(sizeof(struct mood));
251         if (name)
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);
256         return m;
257 }
258
259 /** The different types of a mood line. */
260 enum mood_line_type {
261         /** Invalid. */
262         ML_INVALID,
263         /** Accept line. */
264         ML_ACCEPT,
265         /** Deny line. */
266         ML_DENY,
267         /** Score line. */
268         ML_SCORE
269 };
270
271 /** Data passed to the parser of a mood line. */
272 struct mood_line_parser_data {
273         /** The mood this mood line belongs to. */
274         struct mood *m;
275         /** The line number in the mood definition. */
276         unsigned line_num;
277 };
278
279 /*
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
283  * all matching files
284  */
285 static int parse_mood_line(char *mood_line, void *data)
286 {
287         struct mood_line_parser_data *mlpd = data;
288         char **argv;
289         unsigned num_words;
290         char **w;
291         int i, ret;
292         enum mood_line_type mlt = ML_INVALID;
293         struct mood_item *mi = NULL;
294
295         mlpd->line_num++;
296         ret = create_argv(mood_line, " \t", &argv);
297         if (ret < 0)
298                 return ret;
299         num_words = ret;
300         if (!num_words) /* empty line */
301                 goto out;
302         w = argv;
303         if (**w == '#') /* comment */
304                 goto out;
305         if (!strcmp(*w, "accept"))
306                 mlt = ML_ACCEPT;
307         else if (!strcmp(*w, "deny"))
308                 mlt = ML_DENY;
309         else if (!strcmp(*w, "score"))
310                 mlt = ML_SCORE;
311         ret = -E_MOOD_SYNTAX;
312         if (mlt == ML_INVALID)
313                 goto out;
314         mi = para_calloc(sizeof(struct mood_item));
315         if (mlt != ML_SCORE) {
316                 ret = -E_MOOD_SYNTAX;
317                 w++;
318                 if (!*w)
319                         goto out;
320                 if (strcmp(*w, "with"))
321                         goto check_for_if;
322                 w++;
323                 if (!*w)
324                         goto out;
325                 if (strcmp(*w, "score"))
326                         goto out;
327         }
328         if (mlt == ML_SCORE || !strcmp(*w, "score")) {
329                 ret = -E_MOOD_SYNTAX;
330                 w++;
331                 if (!*w)
332                         goto out;
333                 if (strcmp(*w, "random")) {
334                         mi->random_score = 0;
335                         ret = para_atoi32(*w, &mi->score_arg);
336                         if (ret < 0)
337                                 goto out;
338                 } else {
339                         mi->random_score = 1;
340                         if (!*(w + 1))
341                         goto success; /* the line "score random" is valid */
342                 }
343         } else
344                 mi->score_arg = 0;
345         ret = -E_MOOD_SYNTAX;
346         w++;
347         if (!*w)
348                 goto out;
349 check_for_if:
350         if (!strcmp(*w, "if")) {
351                 ret = -E_MOOD_SYNTAX;
352                 w++;
353                 if (!*w)
354                         goto out;
355         }
356         if (!strcmp(*w, "not")) {
357                 ret = -E_MOOD_SYNTAX;
358                 w++;
359                 if (!*w)
360                         goto out;
361                 mi->logical_not = 1;
362         } else
363                 mi->logical_not = 0;
364         for (i = 0; mood_methods[i].parser; i++) {
365                 if (strcmp(*w, mood_methods[i].name))
366                         continue;
367                 break;
368         }
369         ret = -E_MOOD_SYNTAX;
370         if (!mood_methods[i].parser)
371                 goto out;
372         ret = mood_methods[i].parser(num_words - 1 - (w - argv), w,
373                 &mi->parser_data);
374         if (ret < 0)
375                 goto out;
376         mi->method = &mood_methods[i];
377 success:
378         if (mlpd->m) {
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);
383                 else
384                         para_list_add(&mi->mood_item_node, &mlpd->m->score_list);
385         }
386         PARA_DEBUG_LOG("%s entry added, method: %p\n", mlt == ML_ACCEPT? "accept" :
387                 (mlt == ML_DENY? "deny" : "score"), mi->method);
388         ret = 1;
389 out:
390         free_argv(argv);
391         if (mi && (ret < 0 || !mlpd->m)) { /* mi was not added to any list */
392                 free(mi->parser_data);
393                 free(mi);
394         }
395         return ret;
396 }
397
398 static int load_mood(const struct osl_row *mood_row, struct mood **m)
399 {
400         char *mood_name;
401         struct osl_object mood_def;
402         struct mood_line_parser_data mlpd = {.line_num = 0};
403         int ret;
404
405         *m = NULL;
406         ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
407         if (ret < 0)
408                 return ret;
409         if (!*mood_name)
410                 return -E_DUMMY_ROW;
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);
415         if (ret < 0) {
416                 PARA_ERROR_LOG("unable to load mood %s: %s\n", mlpd.m->name,
417                         para_strerror(-ret));
418                 destroy_mood(mlpd.m);
419                 return ret;
420         }
421         *m = mlpd.m;
422         return 1;
423 }
424
425 static int check_mood(struct osl_row *mood_row, void *data)
426 {
427         struct para_buffer *pb = data;
428         char *mood_name;
429         struct osl_object mood_def;
430         struct mood_line_parser_data mlpd = {.line_num = 0};
431
432         int ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
433
434         if (ret < 0) {
435                 para_printf(pb, "cannot read mood\n");
436                 return ret;
437         }
438         if (!*mood_name) /* ignore dummy row */
439                 goto out;
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);
443         if (ret < 0)
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 */
447 out:
448         osl_close_disk_object(&mood_def);
449         return ret;
450 }
451
452 /**
453  * Check all moods for syntax errors.
454  *
455  * \param aca Only ->pbout is used for diagnostics.
456  *
457  * \return Negative on fatal errors. Inconsistent mood definitions are not
458  * considered an error.
459  */
460 int mood_check_callback(struct afs_callback_arg *aca)
461 {
462         para_printf(&aca->pbout, "checking moods...\n");
463         return osl(osl_rbtree_loop(moods_table, BLOBCOL_ID, &aca->pbout,
464                 check_mood));
465 }
466
467 static int64_t normalized_value(int64_t x, int64_t n, int64_t sum, int64_t qd)
468 {
469         if (!n || !qd)
470                 return 0;
471         return 100 * (n * x - sum) / (int64_t)int_sqrt(n) / (int64_t)int_sqrt(qd);
472 }
473
474 static long compute_score(struct afs_info *afsi, long mood_score)
475 {
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;
481 }
482
483 static int add_afs_statistics(const struct osl_row *row)
484 {
485         uint64_t n, x, s, q;
486         struct afs_info afsi;
487         int ret;
488
489         ret = get_afsi_of_row(row, &afsi);
490         if (ret < 0)
491                 return ret;
492         n = statistics.num;
493         x = afsi.last_played;
494         s = statistics.last_played_sum;
495         if (n > 0) {
496                 q = (x > s / n)? x - s / n : s / n - x;
497                 statistics.last_played_qd += q * q * n / (n + 1);
498         }
499         statistics.last_played_sum += x;
500
501         x = afsi.num_played;
502         s = statistics.num_played_sum;
503         if (n > 0) {
504                 q = (x > s / n)? x - s / n : s / n - x;
505                 statistics.num_played_qd += q * q * n / (n + 1);
506         }
507         statistics.num_played_sum += x;
508         statistics.num++;
509         return 1;
510 }
511
512 static int del_afs_statistics(const struct osl_row *row)
513 {
514         uint64_t n, s, q, a, new_s;
515         struct afs_info afsi;
516         int ret;
517         ret = get_afsi_of_row(row, &afsi);
518         if (ret < 0)
519                 return ret;
520         n = statistics.num;
521         assert(n);
522         if (n == 1) {
523                 memset(&statistics, 0, sizeof(statistics));
524                 return 1;
525         }
526
527         s = statistics.last_played_sum;
528         q = statistics.last_played_qd;
529         a = afsi.last_played;
530         new_s = s - a;
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);
534
535         s = statistics.num_played_sum;
536         q = statistics.num_played_qd;
537         a = afsi.num_played;
538         new_s = s - a;
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);
542
543         statistics.num--;
544         return 1;
545 }
546
547 /*
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.
552  *
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
557  * array is freed.
558  */
559 struct admissible_file_info
560 {
561         /** The admissible audio file. */
562         struct osl_row *aft_row;
563         /** Its score. */
564         long score;
565 };
566
567 /** The temporary array of admissible files. */
568 struct admissible_array {
569         /** Files are admissible wrt. this mood. */
570         struct mood *m;
571         /** The size of the array */
572         unsigned size;
573         /** Pointer to the array of admissible files. */
574         struct admissible_file_info *array;
575 };
576
577 /**
578  * Add an entry to the array of admissible files.
579  *
580  * \param aft_row The audio file to be added.
581  * \param private_data Pointer to a struct admissible_file_info.
582  *
583  * \return 1 if row admissible, 0 if not, negative on errors.
584  */
585 static int add_if_admissible(struct osl_row *aft_row, void *data)
586 {
587         struct admissible_array *aa = data;
588         int ret;
589         long score = 0;
590
591         ret = row_is_admissible(aft_row, aa->m, &score);
592         if (ret <= 0)
593                 return ret;
594         if (statistics.num >= aa->size) {
595                 aa->size *= 2;
596                 aa->size += 100;
597                 aa->array = para_realloc(aa->array,
598                         aa->size * sizeof(struct admissible_file_info));
599         }
600         aa->array[statistics.num].aft_row = aft_row;
601         aa->array[statistics.num].score = score;
602         ret = add_afs_statistics(aft_row);
603         if (ret < 0)
604                 return ret;
605         return 1;
606 }
607
608 /**
609  * Compute the new quadratic deviation in case one element changes.
610  *
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.
616  *
617  * \return The new quadratic deviation resulting from replacing old_val
618  * by new_val.
619  *
620  * Given n real numbers a_1, ..., a_n, their sum S = a_1 + ... + a_n,
621  * their quadratic deviation
622  *
623  * q = (a_1 - S/n)^2 + ... + (a_n - S/n)^2,
624  *
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
628  *
629  *      q' = q + d * s - (2 * S + d) * d / n
630  *         = q + d * (s - 2 * S / n - d /n),
631  *
632  * where d = b - a_n, and s = b + a_n.
633  *
634  * Example: n = 3, a_1 = 3, a_2 = 5, a_3 = 7, b = 10. Then S = 15, q = 8, d = 3,
635  * s = 17, so
636  *
637  *      q + d * s - (2 * S + d) * d / n = 8 + 51 - 33 = 26,
638  *
639  * which equals q' = (3 - 6)^2 + (5 - 6)^2 + (10 - 6)^2.
640  *
641  */
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)
644 {
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);
648 }
649
650 static int update_afs_statistics(struct afs_info *old_afsi,
651                 struct afs_info *new_afsi)
652 {
653         unsigned n;
654         int ret = get_num_admissible_files(&n);
655
656         if (ret < 0)
657                 return ret;
658         assert(n);
659
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;
664
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;
669         return 1;
670 }
671
672 static int add_to_score_table(const struct osl_row *aft_row, long mood_score)
673 {
674         long score;
675         struct afs_info afsi;
676         int ret = get_afsi_of_row(aft_row, &afsi);
677
678         if (ret < 0)
679                 return ret;
680         score = compute_score(&afsi, mood_score);
681         return score_add(aft_row, score);
682 }
683
684 static int delete_from_statistics_and_score_table(const struct osl_row *aft_row)
685 {
686         int ret = del_afs_statistics(aft_row);
687         if (ret < 0)
688                 return ret;
689         return score_delete(aft_row);
690 }
691
692 /**
693  * Delete one entry from the statistics and from the score table.
694  *
695  * \param aft_row The audio file which is no longer admissible.
696  *
697  * \return Positive on success, negative on errors.
698  *
699  * \sa \ref score_delete().
700  */
701 static int mood_delete_audio_file(const struct osl_row *aft_row)
702 {
703         int ret;
704
705         ret = row_belongs_to_score_table(aft_row, NULL);
706         if (ret < 0)
707                 return ret;
708         if (!ret) /* not admissible, nothing to do */
709                 return 1;
710         return delete_from_statistics_and_score_table(aft_row);
711 }
712
713 /**
714  * Compute the new score of an audio file wrt. the current mood.
715  *
716  * \param aft_row Determines the audio file.
717  * \param old_afsi The audio file selector info before updating.
718  *
719  * The \a old_afsi argument may be \p NULL which indicates that no changes to
720  * the audio file info were made.
721  *
722  * \return Positive on success, negative on errors.
723  */
724 static int mood_update_audio_file(const struct osl_row *aft_row,
725                 struct afs_info *old_afsi)
726 {
727         long score, percent;
728         int ret, is_admissible, was_admissible = 0;
729         struct afs_info afsi;
730         unsigned rank;
731
732         if (!current_mood)
733                 return 1; /* nothing to do */
734         ret = row_belongs_to_score_table(aft_row, &rank);
735         if (ret < 0)
736                 return ret;
737         was_admissible = ret;
738         ret = row_is_admissible(aft_row, current_mood, &score);
739         if (ret < 0)
740                 return ret;
741         is_admissible = (ret > 0);
742         if (!was_admissible && !is_admissible)
743                 return 1;
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);
748                 if (ret < 0)
749                         return ret;
750                 return add_to_score_table(aft_row, score);
751         }
752         /* update score */
753         ret = get_afsi_of_row(aft_row, &afsi);
754         if (ret < 0)
755                 return ret;
756         if (old_afsi) {
757                 ret = update_afs_statistics(old_afsi, &afsi);
758                 if (ret < 0)
759                         return ret;
760         }
761         score = compute_score(&afsi, score);
762         PARA_DEBUG_LOG("score: %li\n", score);
763         percent = (score + 100) / 3;
764         if (percent > 100)
765                 percent = 100;
766         else if (percent < 0)
767                 percent = 0;
768         PARA_DEBUG_LOG("moving from rank %u to %li%%\n", rank, percent);
769         return score_update(aft_row, percent);
770 }
771
772 static void log_statistics(void)
773 {
774         unsigned n = statistics.num;
775         int mean_days, sigma_days;
776         /*
777          * We can not use the "now" pointer from sched.c here because we are
778          * called before schedule(), which initializes "now".
779          */
780         struct timeval rnow;
781
782         assert(current_mood);
783         PARA_NOTICE_LOG("loaded mood %s\n", current_mood->name?
784                 current_mood->name : "(dummy)");
785         if (!n) {
786                 PARA_WARNING_LOG("no admissible files\n");
787                 return;
788         }
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));
797 }
798
799 /**
800  * Close the current mood.
801  *
802  * Frees all resources of the current mood.
803  */
804 void close_current_mood(void)
805 {
806         destroy_mood(current_mood);
807         current_mood = NULL;
808         memset(&statistics, 0, sizeof(statistics));
809 }
810
811 /**
812  * Change the current mood.
813  *
814  * \param mood_name The name of the mood to open.
815  *
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.
818  *
819  * If there is already an open mood, it will be closed first.
820  *
821  * \return Positive on success, negative on errors. Loading the dummy mood
822  * always succeeds.
823  *
824  * \sa struct \ref afs_info::last_played.
825  */
826 int change_current_mood(const char *mood_name)
827 {
828         int i, ret;
829         struct admissible_array aa = {
830                 .size = 0,
831                 .array = NULL
832         };
833
834         if (mood_name) {
835                 struct mood *m;
836                 struct osl_row *row;
837                 struct osl_object obj = {
838                         .data = (char *)mood_name,
839                         .size = strlen(mood_name) + 1
840                 };
841                 ret = osl(osl_get_row(moods_table, BLOBCOL_NAME, &obj, &row));
842                 if (ret < 0) {
843                         PARA_NOTICE_LOG("no such mood: %s\n", mood_name);
844                         return ret;
845                 }
846                 ret = load_mood(row, &m);
847                 if (ret < 0)
848                         return ret;
849                 close_current_mood();
850                 current_mood = m;
851         } else { /* load dummy mood */
852                 close_current_mood();
853                 current_mood = alloc_new_mood(NULL);
854         }
855         aa.m = current_mood;
856         PARA_NOTICE_LOG("computing statistics of admissible files\n");
857         ret = audio_file_loop(&aa, add_if_admissible);
858         if (ret < 0)
859                 return ret;
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);
863                 if (ret < 0)
864                         goto out;
865         }
866         log_statistics();
867         ret = statistics.num;
868 out:
869         free(aa.array);
870         return ret;
871 }
872
873 /*
874  * Close and re-open the current mood.
875  *
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
878  * attribute table.
879  *
880  * If no mood is currently open, the function returns success.
881  */
882 static int reload_current_mood(void)
883 {
884         int ret;
885         char *mood_name = NULL;
886
887         ret = clear_score_table();
888         if (ret < 0)
889                 return ret;
890         if (!current_mood)
891                 return 1;
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);
898         free(mood_name);
899         return ret;
900 }
901
902 /**
903  * Notification callback for the moods table.
904  *
905  * \param event Type of the event just occurred.
906  * \param pb Unused.
907  * \param data Its type depends on the event.
908  *
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.
912  *
913  * \return Standard.
914  */
915 int moods_event_handler(enum afs_events event, __a_unused struct para_buffer *pb,
916                 void *data)
917 {
918         if (!current_mood)
919                 return 0;
920         switch (event) {
921         /*
922          * The three blob events might change the set of admissible files,
923          * so we must reload the score list.
924          */
925         case BLOB_RENAME:
926         case BLOB_REMOVE:
927         case BLOB_ADD:
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 */
932         case ATTRIBUTE_ADD:
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 */
937         case AFSI_CHANGE: {
938                 struct afsi_change_event_data *aced = data;
939                 return mood_update_audio_file(aced->aft_row, aced->old_afsi);
940                 }
941         case AFHI_CHANGE:
942         case AUDIO_FILE_RENAME:
943         case AUDIO_FILE_ADD:
944                 return mood_update_audio_file(data, NULL);
945         case AUDIO_FILE_REMOVE:
946                 return mood_delete_audio_file(data);
947         default:
948                 return 1;
949         }
950 }