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