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