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