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