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