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