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