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