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