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