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