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