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