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