paraslash 0.6.4
[paraslash.git] / mood.c
1 /* Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file mood.c Paraslash's mood handling functions. */
4
5 #include <regex.h>
6 #include <osl.h>
7 #include <lopsub.h>
8
9 #include "para.h"
10 #include "error.h"
11 #include "string.h"
12 #include "afh.h"
13 #include "afs.h"
14 #include "list.h"
15 #include "mm.h"
16 #include "mood.h"
17
18 /*
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.
21  */
22 struct mp_context;
23 int mp_init(const char *definition, int nbytes, struct mp_context **result,
24                  char **errmsg);
25 bool mp_eval_row(const struct osl_row *aft_row, struct mp_context *ctx);
26 void mp_shutdown(struct mp_context *ctx);
27
28 /**
29  * Contains statistical data of the currently admissible audio files.
30  *
31  * It is used to assign normalized score values to each admissible audio file.
32  */
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 */
43         unsigned num;
44 };
45 static struct afs_statistics statistics;
46
47 /**
48  * Each line of the current mood corresponds to a mood_item.
49  */
50 struct 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. */
54         void *parser_data;
55         /** The given score value, or zero if none was given. */
56         int32_t score_arg;
57         /** Non-zero if random scoring was requested. */
58         int random_score;
59         /** Whether the "not" keyword was given in the mood line. */
60         int logical_not;
61         /** The position in the list of items. */
62         struct list_head mood_item_node;
63 };
64
65 /*
66  * Created from the mood definition by \ref change_current_mood().
67  *
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.
72  */
73 struct mood {
74         /** The name of this mood. */
75         char *name;
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;
84 };
85
86 /*
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.
89  */
90 static struct mood *current_mood;
91
92 /*
93  * Find the position of the most-significant set bit.
94  *
95  * Copied and slightly adapted from the linux source tree, version 4.9.39
96  * (2017-07).
97  */
98 __a_const static uint32_t fls64(uint64_t v)
99 {
100         int n = 63;
101         const uint64_t ones = ~(uint64_t)0U;
102
103         if ((v & (ones << 32)) == 0) {
104                 n -= 32;
105                 v <<= 32;
106         }
107         if ((v & (ones << (64 - 16))) == 0) {
108                 n -= 16;
109                 v <<= 16;
110         }
111         if ((v & (ones << (64 - 8))) == 0) {
112                 n -= 8;
113                 v <<= 8;
114         }
115         if ((v & (ones << (64 - 4))) == 0) {
116                 n -= 4;
117                 v <<= 4;
118         }
119         if ((v & (ones << (64 - 2))) == 0) {
120                 n -= 2;
121                 v <<= 2;
122         }
123         if ((v & (ones << (64 - 1))) == 0)
124                 n -= 1;
125         return n;
126 }
127
128 /*
129  * Compute the integer square root floor(sqrt(x)).
130  *
131  * Taken 2007 from the linux source tree.
132  */
133 __a_const static uint64_t int_sqrt(uint64_t x)
134 {
135         uint64_t op = x, res = 0, one = 1;
136
137         one = one << (fls64(x) & ~one);
138         while (one != 0) {
139                 if (op >= res + one) {
140                         op = op - (res + one);
141                         res = res + 2 * one;
142                 }
143                 res /= 2;
144                 one /= 4;
145         }
146         return res;
147 }
148
149 /*
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.
152  */
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,
155                 long *score_arg_sum)
156 {
157         int ret;
158         bool match = true;
159
160         *score_arg_sum += item->random_score? 100 : PARA_ABS(item->score_arg);
161         ret = 100;
162         if (item->method) {
163                 ret = item->method->score_function(path, afsi, afhi,
164                         item->parser_data);
165                 if ((ret < 0 && !item->logical_not) || (ret >= 0 && item->logical_not))
166                         match = false;
167         }
168         if (item->random_score)
169                 *score = PARA_ABS(ret) * para_random(100);
170         else
171                 *score = PARA_ABS(ret) * item->score_arg;
172         return match;
173 }
174
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,
177                 long *scorep)
178 {
179         struct mood_item *item;
180         int ret;
181         bool match;
182         long score_arg_sum = 0, score = 0, item_score;
183         struct afs_info afsi;
184         struct afh_info afhi;
185         char *path;
186
187         if (!m)
188                 return -E_NO_MOOD;
189         if (m->parser_context) {
190                 *scorep = 0;
191                 return mp_eval_row(aft_row, m->parser_context);
192         }
193         ret = get_afsi_of_row(aft_row, &afsi);
194         if (ret < 0)
195                 return ret;
196         ret = get_afhi_of_row(aft_row, &afhi);
197         if (ret < 0)
198                 return ret;
199         ret = get_audio_file_path_of_row(aft_row, &path);
200         if (ret < 0)
201                 return ret;
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,
205                         &score_arg_sum);
206                 if (match) /* not admissible */
207                         return 0;
208                 score += item_score;
209         }
210         match = false;
211         list_for_each_entry(item, &m->accept_list, mood_item_node) {
212                 ret = get_item_score(item, &afsi, &afhi, path, &item_score,
213                         &score_arg_sum);
214                 if (ret == 0)
215                         continue;
216                 match = true;
217                 score += item_score;
218         }
219         /* reject if there is no matching entry in the accept list */
220         if (!match && !list_empty(&m->accept_list))
221                 return 0;
222         list_for_each_entry(item, &m->score_list, mood_item_node) {
223                 match = get_item_score(item, &afsi, &afhi, path, &item_score,
224                         &score_arg_sum);
225                 if (match)
226                         score += item_score;
227         }
228         if (score_arg_sum)
229                 score /= score_arg_sum;
230         *scorep = score;
231         return 1;
232 }
233
234 static void cleanup_list_entry(struct mood_item *item)
235 {
236         if (item->method && item->method->cleanup)
237                 item->method->cleanup(item->parser_data);
238         else
239                 free(item->parser_data);
240         list_del(&item->mood_item_node);
241         free(item);
242 }
243
244 static void destroy_mood(struct mood *m)
245 {
246         struct mood_item *tmp, *item;
247
248         if (!m)
249                 return;
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);
256         free(m->name);
257         mp_shutdown(m->parser_context);
258         free(m);
259 }
260
261 static struct mood *alloc_new_mood(const char *name)
262 {
263         struct mood *m = para_calloc(sizeof(struct mood));
264         if (name)
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);
269         return m;
270 }
271
272 /** The different types of a mood line. */
273 enum mood_line_type {
274         /** Invalid. */
275         ML_INVALID,
276         /** Accept line. */
277         ML_ACCEPT,
278         /** Deny line. */
279         ML_DENY,
280         /** Score line. */
281         ML_SCORE
282 };
283
284 /** Data passed to the parser of a mood line. */
285 struct mood_line_parser_data {
286         /** The mood this mood line belongs to. */
287         struct mood *m;
288         /** The line number in the mood definition. */
289         unsigned line_num;
290 };
291
292 /*
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
296  * all matching files
297  */
298 static int parse_mood_line(char *mood_line, void *data)
299 {
300         struct mood_line_parser_data *mlpd = data;
301         char **argv;
302         unsigned num_words;
303         char **w;
304         int i, ret;
305         enum mood_line_type mlt = ML_INVALID;
306         struct mood_item *mi = NULL;
307
308         mlpd->line_num++;
309         ret = create_argv(mood_line, " \t", &argv);
310         if (ret < 0)
311                 return ret;
312         num_words = ret;
313         if (!num_words) /* empty line */
314                 goto out;
315         w = argv;
316         if (**w == '#') /* comment */
317                 goto out;
318         if (!strcmp(*w, "accept"))
319                 mlt = ML_ACCEPT;
320         else if (!strcmp(*w, "deny"))
321                 mlt = ML_DENY;
322         else if (!strcmp(*w, "score"))
323                 mlt = ML_SCORE;
324         ret = -E_MOOD_SYNTAX;
325         if (mlt == ML_INVALID)
326                 goto out;
327         mi = para_calloc(sizeof(struct mood_item));
328         if (mlt != ML_SCORE) {
329                 ret = -E_MOOD_SYNTAX;
330                 w++;
331                 if (!*w)
332                         goto out;
333                 if (strcmp(*w, "with"))
334                         goto check_for_if;
335                 w++;
336                 if (!*w)
337                         goto out;
338                 if (strcmp(*w, "score"))
339                         goto out;
340         }
341         if (mlt == ML_SCORE || !strcmp(*w, "score")) {
342                 ret = -E_MOOD_SYNTAX;
343                 w++;
344                 if (!*w)
345                         goto out;
346                 if (strcmp(*w, "random")) {
347                         mi->random_score = 0;
348                         ret = para_atoi32(*w, &mi->score_arg);
349                         if (ret < 0)
350                                 goto out;
351                 } else {
352                         mi->random_score = 1;
353                         if (!*(w + 1))
354                         goto success; /* the line "score random" is valid */
355                 }
356         } else
357                 mi->score_arg = 0;
358         ret = -E_MOOD_SYNTAX;
359         w++;
360         if (!*w)
361                 goto out;
362 check_for_if:
363         if (!strcmp(*w, "if")) {
364                 ret = -E_MOOD_SYNTAX;
365                 w++;
366                 if (!*w)
367                         goto out;
368         }
369         if (!strcmp(*w, "not")) {
370                 ret = -E_MOOD_SYNTAX;
371                 w++;
372                 if (!*w)
373                         goto out;
374                 mi->logical_not = 1;
375         } else
376                 mi->logical_not = 0;
377         for (i = 0; mood_methods[i].parser; i++) {
378                 if (strcmp(*w, mood_methods[i].name))
379                         continue;
380                 break;
381         }
382         ret = -E_MOOD_SYNTAX;
383         if (!mood_methods[i].parser)
384                 goto out;
385         ret = mood_methods[i].parser(num_words - 1 - (w - argv), w,
386                 &mi->parser_data);
387         if (ret < 0)
388                 goto out;
389         mi->method = &mood_methods[i];
390 success:
391         if (mlpd->m) {
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);
396                 else
397                         para_list_add(&mi->mood_item_node, &mlpd->m->score_list);
398         }
399         PARA_DEBUG_LOG("%s entry added, method: %p\n", mlt == ML_ACCEPT? "accept" :
400                 (mlt == ML_DENY? "deny" : "score"), mi->method);
401         ret = 1;
402 out:
403         free_argv(argv);
404         if (mi && (ret < 0 || !mlpd->m)) { /* mi was not added to any list */
405                 free(mi->parser_data);
406                 free(mi);
407         }
408         return ret;
409 }
410
411 static int load_mood(const struct osl_row *mood_row, struct mood **m,
412                 char **errmsg)
413 {
414         char *mood_name;
415         struct osl_object mood_def;
416         struct mood_line_parser_data mlpd = {.line_num = 0};
417         int ret;
418
419         *m = NULL;
420         ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
421         if (ret < 0) {
422                 if (errmsg)
423                         *errmsg = make_message(
424                                 "could not read mood definition");
425                 return ret;
426         }
427         assert(*mood_name);
428         mlpd.m = alloc_new_mood(mood_name);
429         ret = for_each_line(FELF_READ_ONLY, mood_def.data, mood_def.size,
430                 parse_mood_line, &mlpd);
431         if (ret < 0) {
432                 PARA_INFO_LOG("opening version 2 mood %s\n", mlpd.m->name);
433                 ret = mp_init(mood_def.data, mood_def.size, &mlpd.m->parser_context,
434                         errmsg);
435                 if (ret < 0)
436                         destroy_mood(mlpd.m);
437         } else {
438                 PARA_WARNING_LOG("loaded version 1 mood %s\n", mlpd.m->name);
439                 PARA_WARNING_LOG("please convert to version 2\n");
440                 ret = 1;
441         }
442         osl_close_disk_object(&mood_def);
443         if (ret >= 0)
444                 *m = mlpd.m;
445         return ret;
446 }
447
448 static int check_mood(struct osl_row *mood_row, void *data)
449 {
450         struct para_buffer *pb = data;
451         char *mood_name;
452         struct osl_object mood_def;
453         struct mood_line_parser_data mlpd = {.line_num = 0};
454
455         int ret = mood_get_name_and_def_by_row(mood_row, &mood_name, &mood_def);
456
457         if (ret < 0) {
458                 para_printf(pb, "cannot read mood\n");
459                 return ret;
460         }
461         if (!*mood_name) /* ignore dummy row */
462                 goto out;
463         ret = for_each_line(FELF_READ_ONLY, mood_def.data, mood_def.size,
464                 parse_mood_line, &mlpd);
465         if (ret < 0) {
466                 char *errmsg;
467                 struct mood *m = alloc_new_mood("check");
468                 ret = mp_init(mood_def.data, mood_def.size, &m->parser_context,
469                         &errmsg);
470                 if (ret < 0) {
471                         para_printf(pb, "%s: %s\n", mood_name, errmsg);
472                         free(errmsg);
473                         para_printf(pb, "%s\n", para_strerror(-ret));
474                 } else
475                         destroy_mood(m);
476         } else {
477                 para_printf(pb, "%s: v1 mood, please convert to v2\n",
478                         mood_name);
479
480         }
481         ret = 1; /* don't fail the loop on invalid mood definitions */
482 out:
483         osl_close_disk_object(&mood_def);
484         return ret;
485 }
486
487 /**
488  * Check all moods for syntax errors.
489  *
490  * \param aca Only ->pbout is used for diagnostics.
491  *
492  * \return Negative on fatal errors. Inconsistent mood definitions are not
493  * considered an error.
494  */
495 int mood_check_callback(struct afs_callback_arg *aca)
496 {
497         para_printf(&aca->pbout, "checking moods...\n");
498         return osl(osl_rbtree_loop(moods_table, BLOBCOL_ID, &aca->pbout,
499                 check_mood));
500 }
501
502 static int64_t normalized_value(int64_t x, int64_t n, int64_t sum, int64_t qd)
503 {
504         if (!n || !qd)
505                 return 0;
506         return 100 * (n * x - sum) / (int64_t)int_sqrt(n) / (int64_t)int_sqrt(qd);
507 }
508
509 static long compute_score(struct afs_info *afsi, long mood_score)
510 {
511         mood_score -= normalized_value(afsi->num_played, statistics.num,
512                 statistics.num_played_sum, statistics.num_played_qd);
513         mood_score -= normalized_value(afsi->last_played, statistics.num,
514                 statistics.last_played_sum, statistics.last_played_qd);
515         return mood_score / 3;
516 }
517
518 static int add_afs_statistics(const struct osl_row *row)
519 {
520         uint64_t n, x, s, q;
521         struct afs_info afsi;
522         int ret;
523
524         ret = get_afsi_of_row(row, &afsi);
525         if (ret < 0)
526                 return ret;
527         n = statistics.num;
528         x = afsi.last_played;
529         s = statistics.last_played_sum;
530         if (n > 0) {
531                 q = (x > s / n)? x - s / n : s / n - x;
532                 statistics.last_played_qd += q * q * n / (n + 1);
533         }
534         statistics.last_played_sum += x;
535
536         x = afsi.num_played;
537         s = statistics.num_played_sum;
538         if (n > 0) {
539                 q = (x > s / n)? x - s / n : s / n - x;
540                 statistics.num_played_qd += q * q * n / (n + 1);
541         }
542         statistics.num_played_sum += x;
543         statistics.num++;
544         return 1;
545 }
546
547 static int del_afs_statistics(const struct osl_row *row)
548 {
549         uint64_t n, s, q, a, new_s;
550         struct afs_info afsi;
551         int ret;
552         ret = get_afsi_of_row(row, &afsi);
553         if (ret < 0)
554                 return ret;
555         n = statistics.num;
556         assert(n);
557         if (n == 1) {
558                 memset(&statistics, 0, sizeof(statistics));
559                 return 1;
560         }
561
562         s = statistics.last_played_sum;
563         q = statistics.last_played_qd;
564         a = afsi.last_played;
565         new_s = s - a;
566         statistics.last_played_sum = new_s;
567         statistics.last_played_qd = q + s * s / n - a * a
568                 - new_s * new_s / (n - 1);
569
570         s = statistics.num_played_sum;
571         q = statistics.num_played_qd;
572         a = afsi.num_played;
573         new_s = s - a;
574         statistics.num_played_sum = new_s;
575         statistics.num_played_qd = q + s * s / n - a * a
576                 - new_s * new_s / (n - 1);
577
578         statistics.num--;
579         return 1;
580 }
581
582 /*
583  * At mood open time we determine the set of admissible files for the given
584  * mood. The mood score of each admissible file is computed by adding up all
585  * mood item scores. Next, we update the afs statistics and append a struct
586  * admissible_file_info to a temporary array.
587  *
588  * When all files have been processed in this way, the final score of each
589  * admissible file is computed by adding the dynamic score (which depends on
590  * the afs_statistics and the current time) to the mood score. Finally, all
591  * audio files in the temporary array are added to the score table and the
592  * array is freed.
593  */
594 struct admissible_file_info
595 {
596         /** The admissible audio file. */
597         struct osl_row *aft_row;
598         /** Its score. */
599         long score;
600 };
601
602 /** The temporary array of admissible files. */
603 struct admissible_array {
604         /** Files are admissible wrt. this mood. */
605         struct mood *m;
606         /** The size of the array */
607         unsigned size;
608         /** Pointer to the array of admissible files. */
609         struct admissible_file_info *array;
610 };
611
612 /**
613  * Add an entry to the array of admissible files.
614  *
615  * \param aft_row The audio file to be added.
616  * \param private_data Pointer to a struct admissible_file_info.
617  *
618  * \return 1 if row admissible, 0 if not, negative on errors.
619  */
620 static int add_if_admissible(struct osl_row *aft_row, void *data)
621 {
622         struct admissible_array *aa = data;
623         int ret;
624         long score = 0;
625
626         ret = row_is_admissible(aft_row, aa->m, &score);
627         if (ret <= 0)
628                 return ret;
629         if (statistics.num >= aa->size) {
630                 aa->size *= 2;
631                 aa->size += 100;
632                 aa->array = para_realloc(aa->array,
633                         aa->size * sizeof(struct admissible_file_info));
634         }
635         aa->array[statistics.num].aft_row = aft_row;
636         aa->array[statistics.num].score = score;
637         ret = add_afs_statistics(aft_row);
638         if (ret < 0)
639                 return ret;
640         return 1;
641 }
642
643 /**
644  * Compute the new quadratic deviation in case one element changes.
645  *
646  * \param n Number of elements.
647  * \param old_qd The quadratic deviation before the change.
648  * \param old_val The value that was replaced.
649  * \param new_val The replacement value.
650  * \param old_sum The sum of all elements before the update.
651  *
652  * \return The new quadratic deviation resulting from replacing old_val
653  * by new_val.
654  *
655  * Given n real numbers a_1, ..., a_n, their sum S = a_1 + ... + a_n,
656  * their quadratic deviation
657  *
658  * q = (a_1 - S/n)^2 + ... + (a_n - S/n)^2,
659  *
660  * and a real number b, the quadratic deviation q' of a_1,...a_{n-1}, b (ie.
661  * the last number a_n was replaced by b) may be computed in O(1) time in terms
662  * of n, q, a_n, b, and S as
663  *
664  *      q' = q + d * s - (2 * S + d) * d / n
665  *         = q + d * (s - 2 * S / n - d /n),
666  *
667  * where d = b - a_n, and s = b + a_n.
668  *
669  * Example: n = 3, a_1 = 3, a_2 = 5, a_3 = 7, b = 10. Then S = 15, q = 8, d = 3,
670  * s = 17, so
671  *
672  *      q + d * s - (2 * S + d) * d / n = 8 + 51 - 33 = 26,
673  *
674  * which equals q' = (3 - 6)^2 + (5 - 6)^2 + (10 - 6)^2.
675  *
676  */
677 _static_inline_ int64_t update_quadratic_deviation(int64_t n, int64_t old_qd,
678                 int64_t old_val, int64_t new_val, int64_t old_sum)
679 {
680         int64_t delta = new_val - old_val;
681         int64_t sigma = new_val + old_val;
682         return old_qd + delta * (sigma - 2 * old_sum / n - delta / n);
683 }
684
685 static int update_afs_statistics(struct afs_info *old_afsi,
686                 struct afs_info *new_afsi)
687 {
688         unsigned n;
689         int ret = get_num_admissible_files(&n);
690
691         if (ret < 0)
692                 return ret;
693         assert(n);
694
695         statistics.last_played_qd = update_quadratic_deviation(n,
696                 statistics.last_played_qd, old_afsi->last_played,
697                 new_afsi->last_played, statistics.last_played_sum);
698         statistics.last_played_sum += new_afsi->last_played - old_afsi->last_played;
699
700         statistics.num_played_qd = update_quadratic_deviation(n,
701                 statistics.num_played_qd, old_afsi->num_played,
702                 new_afsi->num_played, statistics.num_played_sum);
703         statistics.num_played_sum += new_afsi->num_played - old_afsi->num_played;
704         return 1;
705 }
706
707 static int add_to_score_table(const struct osl_row *aft_row, long mood_score)
708 {
709         long score;
710         struct afs_info afsi;
711         int ret = get_afsi_of_row(aft_row, &afsi);
712
713         if (ret < 0)
714                 return ret;
715         score = compute_score(&afsi, mood_score);
716         return score_add(aft_row, score);
717 }
718
719 static int delete_from_statistics_and_score_table(const struct osl_row *aft_row)
720 {
721         int ret = del_afs_statistics(aft_row);
722         if (ret < 0)
723                 return ret;
724         return score_delete(aft_row);
725 }
726
727 /**
728  * Delete one entry from the statistics and from the score table.
729  *
730  * \param aft_row The audio file which is no longer admissible.
731  *
732  * \return Positive on success, negative on errors.
733  *
734  * \sa \ref score_delete().
735  */
736 static int mood_delete_audio_file(const struct osl_row *aft_row)
737 {
738         int ret;
739
740         ret = row_belongs_to_score_table(aft_row, NULL);
741         if (ret < 0)
742                 return ret;
743         if (!ret) /* not admissible, nothing to do */
744                 return 1;
745         return delete_from_statistics_and_score_table(aft_row);
746 }
747
748 /**
749  * Compute the new score of an audio file wrt. the current mood.
750  *
751  * \param aft_row Determines the audio file.
752  * \param old_afsi The audio file selector info before updating.
753  *
754  * The \a old_afsi argument may be \p NULL which indicates that no changes to
755  * the audio file info were made.
756  *
757  * \return Positive on success, negative on errors.
758  */
759 static int mood_update_audio_file(const struct osl_row *aft_row,
760                 struct afs_info *old_afsi)
761 {
762         long score, percent;
763         int ret, is_admissible, was_admissible = 0;
764         struct afs_info afsi;
765         unsigned rank;
766
767         if (!current_mood)
768                 return 1; /* nothing to do */
769         ret = row_belongs_to_score_table(aft_row, &rank);
770         if (ret < 0)
771                 return ret;
772         was_admissible = ret;
773         ret = row_is_admissible(aft_row, current_mood, &score);
774         if (ret < 0)
775                 return ret;
776         is_admissible = (ret > 0);
777         if (!was_admissible && !is_admissible)
778                 return 1;
779         if (was_admissible && !is_admissible)
780                 return delete_from_statistics_and_score_table(aft_row);
781         if (!was_admissible && is_admissible) {
782                 ret = add_afs_statistics(aft_row);
783                 if (ret < 0)
784                         return ret;
785                 return add_to_score_table(aft_row, score);
786         }
787         /* update score */
788         ret = get_afsi_of_row(aft_row, &afsi);
789         if (ret < 0)
790                 return ret;
791         if (old_afsi) {
792                 ret = update_afs_statistics(old_afsi, &afsi);
793                 if (ret < 0)
794                         return ret;
795         }
796         score = compute_score(&afsi, score);
797         PARA_DEBUG_LOG("score: %li\n", score);
798         percent = (score + 100) / 3;
799         if (percent > 100)
800                 percent = 100;
801         else if (percent < 0)
802                 percent = 0;
803         PARA_DEBUG_LOG("moving from rank %u to %li%%\n", rank, percent);
804         return score_update(aft_row, percent);
805 }
806
807 static void log_statistics(void)
808 {
809         unsigned n = statistics.num;
810         int mean_days, sigma_days;
811         /*
812          * We can not use the "now" pointer from sched.c here because we are
813          * called before schedule(), which initializes "now".
814          */
815         struct timeval rnow;
816
817         assert(current_mood);
818         PARA_NOTICE_LOG("loaded mood %s\n", current_mood->name?
819                 current_mood->name : "(dummy)");
820         if (!n) {
821                 PARA_WARNING_LOG("no admissible files\n");
822                 return;
823         }
824         PARA_NOTICE_LOG("%u admissible files\n", statistics.num);
825         clock_get_realtime(&rnow);
826         mean_days = (rnow.tv_sec - statistics.last_played_sum / n) / 3600 / 24;
827         sigma_days = int_sqrt(statistics.last_played_qd / n) / 3600 / 24;
828         PARA_NOTICE_LOG("last_played mean/sigma: %d/%d days\n", mean_days, sigma_days);
829         PARA_NOTICE_LOG("num_played mean/sigma: %llu/%llu\n",
830                 (long long unsigned)statistics.num_played_sum / n,
831                 (long long unsigned)int_sqrt(statistics.num_played_qd / n));
832 }
833
834 /**
835  * Close the current mood.
836  *
837  * Frees all resources of the current mood.
838  */
839 void close_current_mood(void)
840 {
841         destroy_mood(current_mood);
842         current_mood = NULL;
843         memset(&statistics, 0, sizeof(statistics));
844 }
845
846 /**
847  * Change the current mood.
848  *
849  * \param mood_name The name of the mood to open.
850  * \param errmsg Error description is returned here.
851  *
852  * If \a mood_name is \a NULL, load the dummy mood that accepts every audio file
853  * and uses a scoring method based only on the \a last_played information.
854  *
855  * The errmsg pointer may be NULL, in which case no error message will be
856  * returned. If a non-NULL pointer is given, the caller must free *errmsg.
857  *
858  * If there is already an open mood, it will be closed first.
859  *
860  * \return Positive on success, negative on errors. Loading the dummy mood
861  * always succeeds.
862  *
863  * \sa struct \ref afs_info::last_played, \ref mp_eval_row().
864  */
865 int change_current_mood(const char *mood_name, char **errmsg)
866 {
867         int i, ret;
868         struct admissible_array aa = {
869                 .size = 0,
870                 .array = NULL
871         };
872
873         if (mood_name) {
874                 struct mood *m;
875                 struct osl_row *row;
876                 struct osl_object obj = {
877                         .data = (char *)mood_name,
878                         .size = strlen(mood_name) + 1
879                 };
880                 ret = osl(osl_get_row(moods_table, BLOBCOL_NAME, &obj, &row));
881                 if (ret < 0) {
882                         if (errmsg)
883                                 *errmsg = make_message("no such mood: %s",
884                                         mood_name);
885                         return ret;
886                 }
887                 ret = load_mood(row, &m, errmsg);
888                 if (ret < 0)
889                         return ret;
890                 close_current_mood();
891                 current_mood = m;
892         } else { /* load dummy mood */
893                 close_current_mood();
894                 current_mood = alloc_new_mood(NULL);
895         }
896         aa.m = current_mood;
897         PARA_NOTICE_LOG("computing statistics of admissible files\n");
898         ret = audio_file_loop(&aa, add_if_admissible);
899         if (ret < 0) {
900                 if (errmsg)
901                         *errmsg = make_message("audio file loop failed");
902                 return ret;
903         }
904         for (i = 0; i < statistics.num; i++) {
905                 struct admissible_file_info *a = aa.array + i;
906                 ret = add_to_score_table(a->aft_row, a->score);
907                 if (ret < 0) {
908                         if (errmsg)
909                                 *errmsg = make_message(
910                                         "could not add row to score table");
911                         goto out;
912                 }
913         }
914         log_statistics();
915         ret = statistics.num;
916 out:
917         free(aa.array);
918         return ret;
919 }
920
921 /*
922  * Close and re-open the current mood.
923  *
924  * This function is called on events which render the current list of
925  * admissible files useless, for example if an attribute is removed from the
926  * attribute table.
927  *
928  * If no mood is currently open, the function returns success.
929  */
930 static int reload_current_mood(void)
931 {
932         int ret;
933         char *mood_name = NULL;
934
935         ret = clear_score_table();
936         if (ret < 0)
937                 return ret;
938         if (!current_mood)
939                 return 1;
940         PARA_NOTICE_LOG("reloading %s\n", current_mood->name?
941                 current_mood->name : "(dummy)");
942         if (current_mood->name)
943                 mood_name = para_strdup(current_mood->name);
944         close_current_mood();
945         ret = change_current_mood(mood_name, NULL);
946         free(mood_name);
947         return ret;
948 }
949
950 /**
951  * Notification callback for the moods table.
952  *
953  * \param event Type of the event just occurred.
954  * \param pb Unused.
955  * \param data Its type depends on the event.
956  *
957  * This function performs actions required due to the occurrence of the given
958  * event. Possible actions include reload of the current mood and update of the
959  * score of an audio file.
960  *
961  * \return Standard.
962  */
963 int moods_event_handler(enum afs_events event, __a_unused struct para_buffer *pb,
964                 void *data)
965 {
966         if (!current_mood)
967                 return 0;
968         switch (event) {
969         /*
970          * The three blob events might change the set of admissible files,
971          * so we must reload the score list.
972          */
973         case BLOB_RENAME:
974         case BLOB_REMOVE:
975         case BLOB_ADD:
976                 if (data == moods_table || data == playlists_table)
977                         return 1; /* no reload necessary for these */
978                 return reload_current_mood();
979         /* these also require reload of the score table */
980         case ATTRIBUTE_ADD:
981         case ATTRIBUTE_REMOVE:
982         case ATTRIBUTE_RENAME:
983                 return reload_current_mood();
984         /* changes to the aft only require to re-examine the audio file */
985         case AFSI_CHANGE: {
986                 struct afsi_change_event_data *aced = data;
987                 return mood_update_audio_file(aced->aft_row, aced->old_afsi);
988                 }
989         case AFHI_CHANGE:
990         case AUDIO_FILE_RENAME:
991         case AUDIO_FILE_ADD:
992                 return mood_update_audio_file(data, NULL);
993         case AUDIO_FILE_REMOVE:
994                 return mood_delete_audio_file(data);
995         default:
996                 return 1;
997         }
998 }