2 * Copyright (C) 2012 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file play.c Paraslash's standalone player. */
15 #include "play.cmdline.h"
16 #include "filter.cmdline.h"
19 #include "buffer_tree.h"
27 #include "write_common.h"
31 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
32 * para_play creates two further tasks: The play task and the i9e task. It is
33 * important whether a function can be called in the context of para_play or
34 * i9e or both. As a rule, all command handlers are called only in i9e context via
35 * the line handler (input mode) or the key handler (command mode) below.
37 * Playlist handling is done exclusively in play context.
41 * Describes a request to change the state of para_play.
43 * There is only one variable of this type: \a rq of the global play task
44 * structure. Command handlers only set this variable and the post_select()
45 * function of the play task investigates its value during each iteration of
46 * the scheduler run and performs the actual work.
48 enum state_change_request_type {
49 /** Everybody is happy. */
51 /** Stream must be repositioned (com_jmp(), com_ff()). */
53 /** New file should be loaded (com_next()). */
55 /** Someone wants us for dead (com_quit()). */
61 /* A bit array of invalid files (those will be skipped). */
63 /* The file which is currently open. */
64 unsigned current_file;
65 /* When to update the status again. */
66 struct timeval next_update;
68 /* Root of the buffer tree for command and status output. */
69 struct btr_node *btrn;
71 /* The decoding machinery. */
72 struct receiver_node rn;
73 struct filter_node fn;
74 struct writer_node wn;
76 /* See comment to enum state_change_request_type above */
77 enum state_change_request_type rq;
78 /* only relevant if rq == CRT_FILE_CHANGE */
81 bg: read lines at prompt, fg: display status and wait
86 /* We have the *intention* to play. Set by com_play(). */
89 /* as returned by afh_recv->open() */
92 /* retrieved via the btr exec mechanism */
93 long unsigned start_chunk;
94 long unsigned seconds;
95 long unsigned num_chunks;
99 /** Initialize the array of errors for para_play. */
102 /* Activate the afh receiver. */
103 extern void afh_recv_init(struct receiver *r);
105 /** Initialization code for a receiver struct. */
106 #define AFH_RECEIVER {.name = "afh", .init = afh_recv_init},
107 /** This expands to the array of all receivers. */
108 DEFINE_RECEIVER_ARRAY;
110 static int loglevel = LL_WARNING;
112 /** The log function which writes log messages to stderr. */
113 INIT_STDERR_LOGGING(loglevel);
115 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
117 /** Iterate over all files in the playlist. */
118 #define FOR_EACH_PLAYLIST_FILE(i) for (i = 0; i < conf.inputs_num; i++)
119 static struct play_args_info conf;
121 static struct sched sched = {.max_fileno = 0};
122 static struct play_task play_task;
123 static struct receiver *afh_recv;
125 static void check_afh_receiver_or_die(void)
129 FOR_EACH_RECEIVER(i) {
130 struct receiver *r = receivers + i;
131 if (strcmp(r->name, "afh"))
136 PARA_EMERG_LOG("fatal: afh receiver not found\n");
140 __noreturn static void print_help_and_die(void)
142 struct ggo_help help = DEFINE_GGO_HELP(play);
143 unsigned flags = conf.detailed_help_given?
144 GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
146 ggo_print_help(&help, flags);
147 printf("supported audio formats: %s\n", AUDIO_FORMAT_HANDLERS);
151 static void parse_config_or_die(int argc, char *argv[])
155 struct play_cmdline_parser_params params = {
159 .check_ambiguity = 0,
163 play_cmdline_parser_ext(argc, argv, &conf, ¶ms);
164 loglevel = get_loglevel_by_name(conf.loglevel_arg);
165 version_handle_flag("play", conf.version_given);
166 if (conf.help_given || conf.detailed_help_given)
167 print_help_and_die();
168 if (conf.config_file_given)
169 config_file = para_strdup(conf.config_file_arg);
171 char *home = para_homedir();
172 config_file = make_message("%s/.paraslash/play.conf", home);
175 ret = file_exists(config_file);
176 if (conf.config_file_given && !ret) {
177 PARA_EMERG_LOG("can not read config file %s\n", config_file);
181 params.initialize = 0;
182 params.check_required = 1;
183 play_cmdline_parser_config_file(config_file, &conf, ¶ms);
184 loglevel = get_loglevel_by_name(conf.loglevel_arg);
186 for (i = 0; i < conf.key_map_given; i++) {
187 char *s = strchr(conf.key_map_arg[i] + 1, ':');
190 PARA_EMERG_LOG("invalid key map arg: %s\n", conf.key_map_arg[i]);
200 static char get_playback_state(struct play_task *pt)
203 case CRT_NONE: return pt->playing? 'P' : 'U';
204 case CRT_REPOS: return 'R';
205 case CRT_FILE_CHANGE: return 'F';
206 case CRT_TERM_RQ: return 'X';
211 static long unsigned get_play_time(struct play_task *pt)
213 char state = get_playback_state(pt);
214 long unsigned result;
216 if (state != 'P' && state != 'U')
218 if (pt->num_chunks == 0 || pt->seconds == 0)
220 /* where the stream started (in seconds) */
221 result = pt->start_chunk * pt->seconds / pt->num_chunks;
222 if (pt->wn.btrn) { /* Add the uptime of the writer node */
223 struct timeval diff = {.tv_sec = 0}, wstime;
224 btr_get_node_start(pt->wn.btrn, &wstime);
225 if (wstime.tv_sec > 0)
226 tv_diff(now, &wstime, &diff);
227 result += diff.tv_sec;
229 result = PARA_MIN(result, pt->seconds);
230 result = PARA_MAX(result, 0UL);
234 static void wipe_receiver_node(struct play_task *pt)
236 PARA_NOTICE_LOG("cleaning up receiver node\n");
237 btr_remove_node(&pt->rn.btrn);
238 afh_recv->close(&pt->rn);
239 afh_recv->free_config(pt->rn.conf);
240 memset(&pt->rn, 0, sizeof(struct receiver_node));
243 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
244 static int get_playback_error(struct play_task *pt)
250 err = task_status(pt->wn.task);
253 if (task_status(pt->fn.task) >= 0)
255 if (task_status(pt->rn.task) >= 0)
257 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
258 || err == -E_WRITE_COMMON_EOF)
263 static int eof_cleanup(struct play_task *pt)
265 struct writer *w = writers + DEFAULT_WRITER;
266 struct filter *decoder = filters + pt->fn.filter_num;
269 ret = get_playback_error(pt);
272 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
273 task_reap(&pt->wn.task);
275 btr_remove_node(&pt->wn.btrn);
276 w->free_config(pt->wn.conf);
277 memset(&pt->wn, 0, sizeof(struct writer_node));
279 task_reap(&pt->fn.task);
280 decoder->close(&pt->fn);
281 btr_remove_node(&pt->fn.btrn);
283 memset(&pt->fn, 0, sizeof(struct filter_node));
285 task_reap(&pt->rn.task);
286 btr_remove_node(&pt->rn.btrn);
288 * On eof (ret > 0), we do not wipe the receiver node struct until a
289 * new file is loaded because we still need it for jumping around when
293 wipe_receiver_node(pt);
297 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
299 return para_random(100) - 50;
302 static void shuffle(char **base, size_t num)
305 qsort(base, num, sizeof(char *), shuffle_compare);
308 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
310 return btr_new_node(&(struct btr_node_description)
311 EMBRACE(.name = afh_recv->name, .context = rn,
312 .handler = afh_recv->execute));
315 static int open_new_file(struct play_task *pt)
318 char *tmp, *path = conf.inputs[pt->next_file], *afh_recv_conf[] =
319 {"play", "-f", path, "-b", "0", NULL};
321 PARA_NOTICE_LOG("next file: %s\n", path);
322 wipe_receiver_node(pt);
324 pt->rn.btrn = new_recv_btrn(&pt->rn);
325 pt->rn.conf = afh_recv->parse_config(ARRAY_SIZE(afh_recv_conf) - 1,
328 pt->rn.receiver = afh_recv;
329 ret = afh_recv->open(&pt->rn);
331 PARA_ERROR_LOG("could not open %s: %s\n", path,
332 para_strerror(-ret));
335 pt->audio_format_num = ret;
337 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
339 pt->afhi_txt = make_message("[afhi command failed]\n");
340 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
345 ret = para_atoi32(tmp, &x);
346 pt->seconds = ret < 0? 1 : x;
350 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
355 ret = para_atoi32(tmp, &x);
356 pt->num_chunks = ret < 0? 1 : x;
362 wipe_receiver_node(pt);
366 static int load_file(struct play_task *pt)
371 struct filter *decoder;
373 btr_remove_node(&pt->rn.btrn);
374 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
375 ret = open_new_file(pt);
379 pt->rn.btrn = new_recv_btrn(&pt->rn);
380 sprintf(buf, "repos %lu", pt->start_chunk);
381 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
383 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
388 /* set up decoding filter */
389 af = audio_format_name(pt->audio_format_num);
390 tmp = make_message("%sdec", af);
391 ret = check_filter_arg(tmp, &pt->fn.conf);
395 pt->fn.filter_num = ret;
396 decoder = filters + ret;
397 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
398 EMBRACE(.name = decoder->name, .parent = pt->rn.btrn,
399 .handler = decoder->execute, .context = &pt->fn));
400 decoder->open(&pt->fn);
402 /* setup default writer */
403 pt->wn.conf = check_writer_arg_or_die(NULL, &pt->wn.writer_num);
405 /* success, register tasks */
406 pt->rn.task = task_register(
407 &(struct task_info) {
408 .name = afh_recv->name,
409 .pre_select = afh_recv->pre_select,
410 .post_select = afh_recv->post_select,
413 sprintf(buf, "%s decoder", af);
414 pt->fn.task = task_register(
415 &(struct task_info) {
417 .pre_select = decoder->pre_select,
418 .post_select = decoder->post_select,
421 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
424 wipe_receiver_node(pt);
428 static int next_valid_file(struct play_task *pt)
430 int i, j = pt->current_file;
432 FOR_EACH_PLAYLIST_FILE(i) {
433 j = (j + 1) % conf.inputs_num;
437 return -E_NO_VALID_FILES;
440 static int load_next_file(struct play_task *pt)
445 if (pt->rq == CRT_NONE) {
447 ret = next_valid_file(pt);
451 } else if (pt->rq == CRT_REPOS)
452 pt->next_file = pt->current_file;
455 pt->invalid[pt->next_file] = true;
459 pt->current_file = pt->next_file;
464 static void kill_stream(struct play_task *pt)
467 task_notify(pt->wn.task, E_EOF);
472 /* only called from com_prev(), nec. only if we have readline */
473 static int previous_valid_file(struct play_task *pt)
475 int i, j = pt->current_file;
477 FOR_EACH_PLAYLIST_FILE(i) {
480 j = conf.inputs_num - 1;
484 return -E_NO_VALID_FILES;
487 #include "interactive.h"
490 * Define the default (internal) key mappings and helper functions to get the
491 * key sequence or the command from a key id, which is what we obtain from
492 * i9e/readline when the key is pressed.
494 * In some of these helper functions we could return pointers to the constant
495 * arrays defined below. However, for others we can not, so let's better be
496 * consistent and allocate all returned strings on the heap.
499 #define INTERNAL_KEYMAP_ENTRIES \
500 KEYMAP_ENTRY("^", "jmp 0"), \
501 KEYMAP_ENTRY("1", "jmp 10"), \
502 KEYMAP_ENTRY("2", "jmp 21"), \
503 KEYMAP_ENTRY("3", "jmp 32"), \
504 KEYMAP_ENTRY("4", "jmp 43"), \
505 KEYMAP_ENTRY("5", "jmp 54"), \
506 KEYMAP_ENTRY("6", "jmp 65"), \
507 KEYMAP_ENTRY("7", "jmp 76"), \
508 KEYMAP_ENTRY("8", "jmp 87"), \
509 KEYMAP_ENTRY("9", "jmp 98"), \
510 KEYMAP_ENTRY("+", "next"), \
511 KEYMAP_ENTRY("-", "prev"), \
512 KEYMAP_ENTRY(":", "bg"), \
513 KEYMAP_ENTRY("i", "info"), \
514 KEYMAP_ENTRY("l", "ls"), \
515 KEYMAP_ENTRY("s", "play"), \
516 KEYMAP_ENTRY("p", "pause"), \
517 KEYMAP_ENTRY("q", "quit"), \
518 KEYMAP_ENTRY("?", "help"), \
519 KEYMAP_ENTRY("\033[D", "ff -10"), \
520 KEYMAP_ENTRY("\033[C", "ff 10"), \
521 KEYMAP_ENTRY("\033[A", "ff 60"), \
522 KEYMAP_ENTRY("\033[B", "ff -60"), \
524 #define KEYMAP_ENTRY(a, b) a
525 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
527 #define KEYMAP_ENTRY(a, b) b
528 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
530 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
531 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + conf.key_map_given)
532 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
534 static inline bool is_internal_key(int key)
536 return key < NUM_INTERNALLY_MAPPED_KEYS;
539 /* for internal keys, the key id is just the array index. */
540 static inline int get_internal_key_map_idx(int key)
542 assert(is_internal_key(key));
547 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
548 * difference is the index to the array of user defined key maps.
550 static inline int get_user_key_map_idx(int key)
552 assert(!is_internal_key(key));
553 return key - NUM_INTERNALLY_MAPPED_KEYS;
556 static inline int get_key_map_idx(int key)
558 return is_internal_key(key)?
559 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
562 static inline char *get_user_key_map_arg(int key)
564 return conf.key_map_arg[get_user_key_map_idx(key)];
567 static inline char *get_internal_key_map_seq(int key)
569 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
572 static char *get_user_key_map_seq(int key)
574 const char *kma = get_user_key_map_arg(key);
575 const char *p = strchr(kma + 1, ':');
582 result = para_malloc(len + 1);
583 memcpy(result, kma, len);
588 static char *get_key_map_seq(int key)
590 return is_internal_key(key)?
591 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
594 static inline char *get_internal_key_map_cmd(int key)
596 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
599 static char *get_user_key_map_cmd(int key)
601 const char *kma = get_user_key_map_arg(key);
602 const char *p = strchr(kma + 1, ':');
606 return para_strdup(p + 1);
609 static char *get_key_map_cmd(int key)
611 return is_internal_key(key)?
612 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
615 static char **get_mapped_keyseqs(void)
620 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
621 FOR_EACH_MAPPED_KEY(i) {
622 int idx = get_key_map_idx(i);
623 char *seq = get_key_map_seq(i);
624 char *cmd = get_key_map_cmd(i);
625 bool internal = is_internal_key(i);
626 PARA_DEBUG_LOG("%s key sequence #%d: %s -> %s\n",
627 internal? "internal" : "user-defined",
636 #include "play.command_list.h"
638 typedef int play_command_handler_t(struct play_task *, int, char**);
639 static play_command_handler_t PLAY_COMMAND_HANDLERS;
641 /* defines one command of para_play */
644 play_command_handler_t *handler;
645 const char *description;
650 static struct pp_command pp_cmds[] = {DEFINE_PLAY_CMD_ARRAY};
651 #define FOR_EACH_COMMAND(c) for (c = 0; pp_cmds[c].name; c++)
653 #include "play.completion.h"
654 static struct i9e_completer pp_completers[];
656 I9E_DUMMY_COMPLETER(jmp);
657 I9E_DUMMY_COMPLETER(next);
658 I9E_DUMMY_COMPLETER(prev);
659 I9E_DUMMY_COMPLETER(fg);
660 I9E_DUMMY_COMPLETER(bg);
661 I9E_DUMMY_COMPLETER(ls);
662 I9E_DUMMY_COMPLETER(info);
663 I9E_DUMMY_COMPLETER(play);
664 I9E_DUMMY_COMPLETER(pause);
665 I9E_DUMMY_COMPLETER(stop);
666 I9E_DUMMY_COMPLETER(tasks);
667 I9E_DUMMY_COMPLETER(quit);
668 I9E_DUMMY_COMPLETER(ff);
670 static void help_completer(struct i9e_completion_info *ci,
671 struct i9e_completion_result *result)
673 result->matches = i9e_complete_commands(ci->word, pp_completers);
676 static struct i9e_completer pp_completers[] = {PLAY_COMPLETERS {.name = NULL}};
678 static void attach_stdout(struct play_task *pt, const char *name)
682 pt->btrn = btr_new_node(&(struct btr_node_description)
683 EMBRACE(.name = name));
684 i9e_attach_to_stdout(pt->btrn);
687 static void detach_stdout(struct play_task *pt)
689 btr_remove_node(&pt->btrn);
692 static int com_quit(struct play_task *pt, int argc, __a_unused char **argv)
695 return -E_PLAY_SYNTAX;
696 pt->rq = CRT_TERM_RQ;
700 static int com_help(struct play_task *pt, int argc, char **argv)
707 return -E_PLAY_SYNTAX;
710 FOR_EACH_COMMAND(i) {
711 sz = xasprintf(&buf, "%s\t%s\n", pp_cmds[i].name,
712 pp_cmds[i].description);
713 btr_add_output(buf, sz, pt->btrn);
716 FOR_EACH_MAPPED_KEY(i) {
717 bool internal = is_internal_key(i);
718 int idx = get_key_map_idx(i);
719 char *seq = get_key_map_seq(i);
720 char *cmd = get_key_map_cmd(i);
722 "%s key #%d: %s -> %s\n",
723 internal? "internal" : "user-defined",
725 btr_add_output(buf, sz, pt->btrn);
732 FOR_EACH_COMMAND(i) {
733 if (strcmp(pp_cmds[i].name, argv[1]))
740 pp_cmds[i].description,
744 btr_add_output(buf, sz, pt->btrn);
747 return -E_BAD_PLAY_CMD;
750 static int com_info(struct play_task *pt, int argc, __a_unused char **argv)
754 static char dflt[] = "[no information available]";
757 return -E_PLAY_SYNTAX;
758 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
759 pt->current_file, conf.inputs[pt->current_file]);
760 btr_add_output(buf, sz, pt->btrn);
761 buf = pt->afhi_txt? pt->afhi_txt : dflt;
762 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
766 static void list_file(struct play_task *pt, int num)
771 sz = xasprintf(&buf, "%s %4u %s\n", num == pt->current_file?
772 "*" : " ", num, conf.inputs[num]);
773 btr_add_output(buf, sz, pt->btrn);
776 static int com_tasks(struct play_task *pt, int argc, __a_unused char **argv)
783 return -E_PLAY_SYNTAX;
785 buf = get_task_list(&sched);
786 btr_add_output(buf, strlen(buf), pt->btrn);
787 state = get_playback_state(pt);
788 sz = xasprintf(&buf, "state: %c\n", state);
789 btr_add_output(buf, sz, pt->btrn);
793 static int com_ls(struct play_task *pt, int argc, char **argv)
798 FOR_EACH_PLAYLIST_FILE(i)
802 for (j = 1; j < argc; j++) {
803 FOR_EACH_PLAYLIST_FILE(i) {
804 ret = fnmatch(argv[j], conf.inputs[i], 0);
805 if (ret == 0) /* match */
812 static int com_play(struct play_task *pt, int argc, char **argv)
819 return -E_PLAY_SYNTAX;
820 state = get_playback_state(pt);
824 pt->next_file = pt->current_file;
829 ret = para_atoi32(argv[1], &x);
832 if (x < 0 || x >= conf.inputs_num)
833 return -ERRNO_TO_PARA_ERROR(EINVAL);
836 pt->rq = CRT_FILE_CHANGE;
840 static int com_pause(struct play_task *pt, int argc, __a_unused char **argv)
843 long unsigned seconds, ss;
846 return -E_PLAY_SYNTAX;
847 state = get_playback_state(pt);
851 seconds = get_play_time(pt);
855 ss = seconds * pt->num_chunks / pt->seconds + 1;
856 ss = PARA_MAX(ss, 0UL);
857 ss = PARA_MIN(ss, pt->num_chunks);
858 pt->start_chunk = ss;
863 static int com_prev(struct play_task *pt, int argc, __a_unused char **argv)
869 return -E_PLAY_SYNTAX;
870 ret = previous_valid_file(pt);
875 pt->rq = CRT_FILE_CHANGE;
880 static int com_next(struct play_task *pt, int argc, __a_unused char **argv)
885 return -E_PLAY_SYNTAX;
886 ret = next_valid_file(pt);
891 pt->rq = CRT_FILE_CHANGE;
896 static int com_fg(struct play_task *pt, int argc, __a_unused char **argv)
899 return -E_PLAY_SYNTAX;
900 pt->background = false;
904 static int com_bg(struct play_task *pt, int argc, __a_unused char **argv)
907 return -E_PLAY_SYNTAX;
908 pt->background = true;
912 static int com_jmp(struct play_task *pt, int argc, char **argv)
918 return -E_PLAY_SYNTAX;
919 ret = para_atoi32(argv[1], &percent);
922 if (percent < 0 || percent > 100)
923 return -ERRNO_TO_PARA_ERROR(EINVAL);
924 if (pt->playing && !pt->fn.btrn)
926 pt->start_chunk = percent * pt->num_chunks / 100;
934 static int com_ff(struct play_task *pt, int argc, char **argv)
940 return -E_PLAY_SYNTAX;
941 ret = para_atoi32(argv[1], &seconds);
944 if (pt->playing && !pt->fn.btrn)
946 seconds += get_play_time(pt);
947 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
948 seconds = PARA_MAX(seconds, 0);
949 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
950 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
951 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
959 static int run_command(char *line, struct play_task *pt)
964 attach_stdout(pt, __FUNCTION__);
965 ret = create_argv(line, " ", &argv);
967 PARA_ERROR_LOG("parse error: %s\n", para_strerror(-ret));
973 FOR_EACH_COMMAND(i) {
974 if (strcmp(pp_cmds[i].name, argv[0]))
976 ret = pp_cmds[i].handler(pt, argc, argv);
978 PARA_WARNING_LOG("%s: %s\n", pt->background?
979 "" : argv[0], para_strerror(-ret));
983 PARA_WARNING_LOG("invalid command: %s\n", argv[0]);
990 static int play_i9e_line_handler(char *line)
992 return run_command(line, &play_task);
995 static int play_i9e_key_handler(int key)
997 struct play_task *pt = &play_task;
998 int idx = get_key_map_idx(key);
999 char *seq = get_key_map_seq(key);
1000 char *cmd = get_key_map_cmd(key);
1001 bool internal = is_internal_key(key);
1003 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1004 key, internal? "internal" : "user-defined",
1006 run_command(cmd, pt);
1009 pt->next_update = *now;
1013 static struct i9e_client_info ici = {
1015 .prompt = "para_play> ",
1016 .line_handler = play_i9e_line_handler,
1017 .key_handler = play_i9e_key_handler,
1018 .completers = pp_completers,
1021 static void sigint_handler(int sig)
1023 play_task.background = true;
1024 i9e_signal_dispatch(sig);
1028 * We start with para_log() set to the standard log function which writes to
1029 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1032 static void session_open(__a_unused struct play_task *pt)
1036 struct sigaction act;
1038 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1039 if (conf.history_file_given)
1040 history_file = para_strdup(conf.history_file_arg);
1042 char *home = para_homedir();
1043 history_file = make_message("%s/.paraslash/play.history",
1047 ici.history_file = history_file;
1048 ici.loglevel = loglevel;
1050 act.sa_handler = sigint_handler;
1051 sigemptyset(&act.sa_mask);
1053 sigaction(SIGINT, &act, NULL);
1054 act.sa_handler = i9e_signal_dispatch;
1055 sigemptyset(&act.sa_mask);
1057 sigaction(SIGWINCH, &act, NULL);
1058 sched.select_function = i9e_select;
1060 ici.bound_keyseqs = get_mapped_keyseqs();
1061 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1062 EMBRACE(.name = __FUNCTION__));
1063 ret = i9e_open(&ici, &sched);
1072 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1076 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1081 if (btr_get_output_queue_size(pt->btrn) > 0)
1083 if (btr_get_input_queue_size(pt->btrn) > 0)
1086 ie9_print_status_bar(str, len);
1090 * If we are about to die we must call i9e_close() to reset the terminal.
1091 * However, i9e_close() must be called in *this* context, i.e. from
1092 * play_task.post_select() rather than from i9e_post_select(), because
1093 * otherwise i9e would access freed memory upon return. So the play task must
1094 * stay alive until the i9e task terminates.
1096 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1097 * and reschedule. In the next iteration, i9e->post_select returns an error and
1098 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1099 * are allowed to call i9e_close() and terminate as well.
1101 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1108 attach_stdout(pt, __FUNCTION__);
1109 ret = i9e_get_error();
1113 para_log = stderr_log;
1114 free(ici.history_file);
1117 if (get_playback_state(pt) == 'X')
1118 i9e_signal_dispatch(SIGTERM);
1122 #else /* HAVE_READLINE */
1124 static int session_post_select(struct sched *s, struct play_task *pt)
1128 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1130 if (read(STDIN_FILENO, &c, 1))
1136 static void session_open(__a_unused struct play_task *pt)
1140 static void session_update_time_string(__a_unused struct play_task *pt,
1141 char *str, __a_unused unsigned len)
1143 printf("\r%s ", str);
1146 #endif /* HAVE_READLINE */
1148 static void play_pre_select(struct sched *s, void *context)
1150 struct play_task *pt = context;
1153 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1154 state = get_playback_state(pt);
1155 if (state == 'R' || state == 'F' || state == 'X')
1156 return sched_min_delay(s);
1157 sched_request_barrier_or_min_delay(&pt->next_update, s);
1160 static unsigned get_time_string(struct play_task *pt, char **result)
1162 int seconds, length;
1163 char state = get_playback_state(pt);
1165 /* do not return anything if things are about to change */
1166 if (state != 'P' && state != 'U') {
1170 length = pt->seconds;
1172 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1173 seconds = get_play_time(pt);
1174 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1178 (length - seconds) / 60,
1179 (length - seconds) % 60,
1180 length? (seconds * 100 + length / 2) / length : 0,
1183 conf.inputs[pt->current_file]
1187 static int play_post_select(struct sched *s, void *context)
1189 struct play_task *pt = context;
1192 ret = eof_cleanup(pt);
1194 pt->rq = CRT_TERM_RQ;
1197 ret = session_post_select(s, pt);
1200 if (!pt->wn.btrn && !pt->fn.btrn) {
1201 char state = get_playback_state(pt);
1202 if (state == 'P' || state == 'R' || state == 'F') {
1203 PARA_NOTICE_LOG("state: %c\n", state);
1204 ret = load_next_file(pt);
1206 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1207 pt->rq = CRT_TERM_RQ;
1211 pt->next_update = *now;
1214 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1216 unsigned len = get_time_string(pt, &str);
1217 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1219 session_update_time_string(pt, str, len);
1221 tv_add(now, &delay, &pt->next_update);
1229 * The main function of para_play.
1231 * \param argc Standard.
1232 * \param argv Standard.
1234 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1236 int main(int argc, char *argv[])
1239 struct play_task *pt = &play_task;
1241 /* needed this early to make help work */
1246 sched.default_timeout.tv_sec = 5;
1248 parse_config_or_die(argc, argv);
1249 if (conf.inputs_num == 0)
1250 print_help_and_die();
1251 check_afh_receiver_or_die();
1254 if (conf.randomize_given)
1255 shuffle(conf.inputs, conf.inputs_num);
1256 pt->invalid = para_calloc(sizeof(*pt->invalid) * conf.inputs_num);
1257 pt->rq = CRT_FILE_CHANGE;
1258 pt->current_file = conf.inputs_num - 1;
1260 pt->task = task_register(&(struct task_info){
1262 .pre_select = play_pre_select,
1263 .post_select = play_post_select,
1266 ret = schedule(&sched);
1267 sched_shutdown(&sched);
1269 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1270 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;