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