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