2 * Copyright (C) 2012-2013 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file play.c Paraslash's standalone player. */
16 #include "play.cmdline.h"
17 #include "filter.cmdline.h"
20 #include "buffer_tree.h"
28 #include "write_common.h"
32 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
33 * para_play creates two further tasks: The play task and the i9e task. It is
34 * important whether a function can be called in the context of para_play or
35 * i9e or both. As a rule, all command handlers are called only in i9e context via
36 * the line handler (input mode) or the key handler (command mode) below.
38 * Playlist handling is done exclusively in play context.
42 * Describes a request to change the state of para_play.
44 * There is only one variable of this type: \a rq of the global play task
45 * structure. Command handlers only set this variable and the post_select()
46 * function of the play task investigates its value during each iteration of
47 * the scheduler run and performs the actual work.
49 enum state_change_request_type {
50 /** Everybody is happy. */
52 /** Stream must be repositioned (com_jmp(), com_ff()). */
54 /** New file should be loaded (com_next()). */
56 /** Someone wants us for dead (com_quit()). */
62 /* A bit array of invalid files (those will be skipped). */
64 /* The file which is currently open. */
65 unsigned current_file;
66 /* When to update the status again. */
67 struct timeval next_update;
69 /* Root of the buffer tree for command and status output. */
70 struct btr_node *btrn;
72 /* The decoding machinery. */
73 struct receiver_node rn;
74 struct filter_node fn;
75 struct writer_node wn;
77 /* See comment to enum state_change_request_type above */
78 enum state_change_request_type rq;
79 /* only relevant if rq == CRT_FILE_CHANGE */
82 bg: read lines at prompt, fg: display status and wait
87 /* We have the *intention* to play. Set by com_play(). */
90 /* as returned by afh_recv->open() */
93 /* retrieved via the btr exec mechanism */
94 long unsigned start_chunk;
95 long unsigned seconds;
96 long unsigned num_chunks;
100 /** Initialize the array of errors for para_play. */
103 /* Activate the afh receiver. */
104 extern void afh_recv_init(struct receiver *r);
106 /** Initialization code for a receiver struct. */
107 #define AFH_RECEIVER {.name = "afh", .init = afh_recv_init},
108 /** This expands to the array of all receivers. */
109 DEFINE_RECEIVER_ARRAY;
111 static int loglevel = LL_WARNING;
113 /** The log function which writes log messages to stderr. */
114 INIT_STDERR_LOGGING(loglevel);
116 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
118 /** Iterate over all files in the playlist. */
119 #define FOR_EACH_PLAYLIST_FILE(i) for (i = 0; i < conf.inputs_num; i++)
120 static struct play_args_info conf;
122 static struct sched sched = {.max_fileno = 0};
123 static struct play_task play_task;
124 static struct receiver *afh_recv;
126 static void check_afh_receiver_or_die(void)
130 FOR_EACH_RECEIVER(i) {
131 struct receiver *r = receivers + i;
132 if (strcmp(r->name, "afh"))
137 PARA_EMERG_LOG("fatal: afh receiver not found\n");
141 /** Description to be included in the --detailed-help output. */
143 "para_play is a command line audio player.\n" \
145 "It operates either in command mode or in insert mode. In insert mode it\n" \
146 "presents a prompt and allows to enter para_play commands like stop, play, pause\n" \
147 "etc. In command mode, the current audio file is shown and the program reads\n" \
148 "single key strokes from stdin. Keys may be mapped to para_play commands.\n" \
149 "Whenever a mapped key is pressed, the associated command is executed.\n" \
151 __noreturn static void print_help_and_die(void)
153 int d = conf.detailed_help_given;
154 const char **p = d? play_args_info_detailed_help
155 : play_args_info_help;
157 // printf_or_die("%s\n\n", PLAY_CMDLINE_PARSER_PACKAGE "-"
158 // PLAY_CMDLINE_PARSER_VERSION);
160 printf_or_die("%s\n\n", play_args_info_usage);
162 printf_or_die("%s\n", PP_DESC);
164 printf_or_die("%s\n", *p);
168 static void parse_config_or_die(int argc, char *argv[])
172 struct play_cmdline_parser_params params = {
176 .check_ambiguity = 0,
180 if (play_cmdline_parser_ext(argc, argv, &conf, ¶ms))
182 HANDLE_VERSION_FLAG("play", conf);
183 if (conf.help_given || conf.detailed_help_given)
184 print_help_and_die();
185 loglevel = get_loglevel_by_name(conf.loglevel_arg);
186 if (conf.config_file_given)
187 config_file = para_strdup(conf.config_file_arg);
189 char *home = para_homedir();
190 config_file = make_message("%s/.paraslash/play.conf", home);
193 ret = file_exists(config_file);
194 if (conf.config_file_given && !ret) {
195 PARA_EMERG_LOG("can not read config file %s\n", config_file);
199 params.initialize = 0;
200 params.check_required = 1;
201 play_cmdline_parser_config_file(config_file, &conf, ¶ms);
203 for (i = 0; i < conf.key_map_given; i++) {
204 char *s = strchr(conf.key_map_arg[i] + 1, ':');
207 PARA_EMERG_LOG("invalid key map arg: %s\n", conf.key_map_arg[i]);
217 static char get_playback_state(struct play_task *pt)
220 case CRT_NONE: return pt->playing? 'P' : 'U';
221 case CRT_REPOS: return 'R';
222 case CRT_FILE_CHANGE: return 'F';
223 case CRT_TERM_RQ: return 'X';
228 static long unsigned get_play_time(struct play_task *pt)
230 char state = get_playback_state(pt);
231 long unsigned result;
233 if (state != 'P' && state != 'U')
235 if (pt->num_chunks == 0 || pt->seconds == 0)
237 /* where the stream started (in seconds) */
238 result = pt->start_chunk * pt->seconds / pt->num_chunks;
239 if (pt->wn.btrn) { /* Add the uptime of the writer node */
240 struct timeval diff = {.tv_sec = 0}, wstime;
241 btr_get_node_start(pt->wn.btrn, &wstime);
242 if (wstime.tv_sec > 0)
243 tv_diff(now, &wstime, &diff);
244 result += diff.tv_sec;
246 result = PARA_MIN(result, pt->seconds);
247 result = PARA_MAX(result, 0UL);
251 static void wipe_receiver_node(struct play_task *pt)
253 PARA_NOTICE_LOG("cleaning up receiver node\n");
254 btr_remove_node(&pt->rn.btrn);
255 afh_recv->close(&pt->rn);
256 afh_recv->free_config(pt->rn.conf);
257 memset(&pt->rn, 0, sizeof(struct receiver_node));
260 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
261 static int get_playback_error(struct play_task *pt)
263 int err = pt->wn.task.error;
267 if (pt->fn.task.error >= 0)
269 if (pt->rn.task.error >= 0)
271 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
272 || err == -E_WRITE_COMMON_EOF)
277 static int eof_cleanup(struct play_task *pt)
279 struct writer *w = writers + DEFAULT_WRITER;
280 struct filter *decoder = filters + pt->fn.filter_num;
283 ret = get_playback_error(pt);
286 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
288 btr_remove_node(&pt->wn.btrn);
289 w->free_config(pt->wn.conf);
290 memset(&pt->wn, 0, sizeof(struct writer_node));
292 decoder->close(&pt->fn);
293 btr_remove_node(&pt->fn.btrn);
295 memset(&pt->fn, 0, sizeof(struct filter_node));
297 btr_remove_node(&pt->rn.btrn);
299 * On eof (ret > 0), we do not wipe the receiver node struct until a
300 * new file is loaded because we still need it for jumping around when
304 wipe_receiver_node(pt);
308 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
310 return para_random(100) - 50;
313 static void shuffle(char **base, size_t num)
315 srandom(now->tv_sec);
316 qsort(base, num, sizeof(char *), shuffle_compare);
319 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
321 return btr_new_node(&(struct btr_node_description)
322 EMBRACE(.name = afh_recv->name, .context = rn,
323 .handler = afh_recv->execute));
326 static int open_new_file(struct play_task *pt)
329 char *tmp, *path = conf.inputs[pt->next_file], *afh_recv_conf[] =
330 {"play", "-f", path, "-b", "0", NULL};
332 PARA_NOTICE_LOG("next file: %s\n", path);
333 wipe_receiver_node(pt);
335 pt->rn.btrn = new_recv_btrn(&pt->rn);
336 pt->rn.conf = afh_recv->parse_config(ARRAY_SIZE(afh_recv_conf) - 1,
339 pt->rn.receiver = afh_recv;
340 ret = afh_recv->open(&pt->rn);
342 PARA_ERROR_LOG("could not open %s: %s\n", path,
343 para_strerror(-ret));
346 pt->audio_format_num = ret;
348 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
350 pt->afhi_txt = make_message("[afhi command failed]\n");
351 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
356 ret = para_atoi32(tmp, &x);
357 pt->seconds = ret < 0? 1 : x;
361 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
366 ret = para_atoi32(tmp, &x);
367 pt->num_chunks = ret < 0? 1 : x;
371 pt->rn.task.pre_select = afh_recv->pre_select;
372 pt->rn.task.post_select = afh_recv->post_select;
373 sprintf(pt->rn.task.status, "%s receiver node", afh_recv->name);
376 wipe_receiver_node(pt);
380 static int load_file(struct play_task *pt)
385 struct filter *decoder;
387 btr_remove_node(&pt->rn.btrn);
388 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
389 ret = open_new_file(pt);
394 pt->rn.btrn = new_recv_btrn(&pt->rn);
395 sprintf(buf, "repos %lu", pt->start_chunk);
396 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
398 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
403 /* set up decoding filter */
404 af = audio_format_name(pt->audio_format_num);
405 tmp = make_message("%sdec", af);
406 ret = check_filter_arg(tmp, &pt->fn.conf);
410 pt->fn.filter_num = ret;
411 decoder = filters + ret;
412 pt->fn.task.pre_select = decoder->pre_select;
413 pt->fn.task.post_select = decoder->post_select;
414 sprintf(pt->fn.task.status, "%s decoder", af);
415 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
416 EMBRACE(.name = decoder->name, .parent = pt->rn.btrn,
417 .handler = decoder->execute, .context = &pt->fn));
418 decoder->open(&pt->fn);
420 /* setup default writer */
421 pt->wn.conf = check_writer_arg_or_die(NULL, &pt->wn.writer_num);
422 pt->wn.task.error = 0;
424 /* success, register tasks */
425 register_task(&sched, &pt->rn.task);
426 register_task(&sched, &pt->fn.task);
427 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
430 wipe_receiver_node(pt);
434 static int next_valid_file(struct play_task *pt)
436 int i, j = pt->current_file;
438 FOR_EACH_PLAYLIST_FILE(i) {
439 j = (j + 1) % conf.inputs_num;
443 return -E_NO_VALID_FILES;
446 static int load_next_file(struct play_task *pt)
451 if (pt->rq == CRT_NONE || pt->rq == CRT_FILE_CHANGE) {
453 ret = next_valid_file(pt);
457 } else if (pt->rq == CRT_REPOS)
458 pt->next_file = pt->current_file;
461 pt->invalid[pt->next_file] = true;
465 pt->current_file = pt->next_file;
470 static void kill_stream(struct play_task *pt)
472 task_notify(&pt->wn.task, E_EOF);
477 /* only called from com_prev(), nec. only if we have readline */
478 static int previous_valid_file(struct play_task *pt)
480 int i, j = pt->current_file;
482 FOR_EACH_PLAYLIST_FILE(i) {
485 j = conf.inputs_num - 1;
489 return -E_NO_VALID_FILES;
492 #include "interactive.h"
495 * Define the default (internal) key mappings and helper functions to get the
496 * key sequence or the command from a key id, which is what we obtain from
497 * i9e/readline when the key is pressed.
499 * In some of these helper functions we could return pointers to the constant
500 * arrays defined below. However, for others we can not, so let's better be
501 * consistent and allocate all returned strings on the heap.
504 #define INTERNAL_KEYMAP_ENTRIES \
505 KEYMAP_ENTRY("^", "jmp 0"), \
506 KEYMAP_ENTRY("1", "jmp 10"), \
507 KEYMAP_ENTRY("2", "jmp 21"), \
508 KEYMAP_ENTRY("3", "jmp 32"), \
509 KEYMAP_ENTRY("4", "jmp 43"), \
510 KEYMAP_ENTRY("5", "jmp 54"), \
511 KEYMAP_ENTRY("6", "jmp 65"), \
512 KEYMAP_ENTRY("7", "jmp 76"), \
513 KEYMAP_ENTRY("8", "jmp 87"), \
514 KEYMAP_ENTRY("9", "jmp 98"), \
515 KEYMAP_ENTRY("+", "next"), \
516 KEYMAP_ENTRY("-", "prev"), \
517 KEYMAP_ENTRY(":", "bg"), \
518 KEYMAP_ENTRY("i", "info"), \
519 KEYMAP_ENTRY("l", "ls"), \
520 KEYMAP_ENTRY("s", "play"), \
521 KEYMAP_ENTRY("p", "pause"), \
522 KEYMAP_ENTRY("q", "quit"), \
523 KEYMAP_ENTRY("?", "help"), \
524 KEYMAP_ENTRY("\033[D", "ff -10"), \
525 KEYMAP_ENTRY("\033[C", "ff 10"), \
526 KEYMAP_ENTRY("\033[A", "ff 60"), \
527 KEYMAP_ENTRY("\033[B", "ff -60"), \
529 #define KEYMAP_ENTRY(a, b) a
530 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
532 #define KEYMAP_ENTRY(a, b) b
533 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
535 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
536 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + conf.key_map_given)
537 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
539 static inline bool is_internal_key(int key)
541 return key < NUM_INTERNALLY_MAPPED_KEYS;
544 /* for internal keys, the key id is just the array index. */
545 static inline int get_internal_key_map_idx(int key)
547 assert(is_internal_key(key));
552 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
553 * difference is the index to the array of user defined key maps.
555 static inline int get_user_key_map_idx(int key)
557 assert(!is_internal_key(key));
558 return key - NUM_INTERNALLY_MAPPED_KEYS;
561 static inline int get_key_map_idx(int key)
563 return is_internal_key(key)?
564 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
567 static inline char *get_user_key_map_arg(int key)
569 return conf.key_map_arg[get_user_key_map_idx(key)];
572 static inline char *get_internal_key_map_seq(int key)
574 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
577 static char *get_user_key_map_seq(int key)
579 const char *kma = get_user_key_map_arg(key);
580 const char *p = strchr(kma + 1, ':');
587 result = para_malloc(len + 1);
588 memcpy(result, kma, len);
593 static char *get_key_map_seq(int key)
595 return is_internal_key(key)?
596 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
599 static inline char *get_internal_key_map_cmd(int key)
601 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
604 static char *get_user_key_map_cmd(int key)
606 const char *kma = get_user_key_map_arg(key);
607 const char *p = strchr(kma + 1, ':');
611 return para_strdup(p + 1);
614 static char *get_key_map_cmd(int key)
616 return is_internal_key(key)?
617 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
620 static char **get_mapped_keyseqs(void)
625 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
626 FOR_EACH_MAPPED_KEY(i) {
627 int idx = get_key_map_idx(i);
628 char *seq = get_key_map_seq(i);
629 char *cmd = get_key_map_cmd(i);
630 bool internal = is_internal_key(i);
631 PARA_DEBUG_LOG("%s key sequence #%d: %s -> %s\n",
632 internal? "internal" : "user-defined",
641 #include "play_completion.h"
644 /* defines one command of para_play */
647 int (*handler)(struct play_task *, int, char**);
648 const char *description;
653 #include "play_command_list.h"
654 static struct pp_command pp_cmds[] = {DEFINE_PLAY_CMD_ARRAY};
655 #define FOR_EACH_COMMAND(c) for (c = 0; pp_cmds[c].name; c++)
657 #include "play_completion.h"
658 static struct i9e_completer pp_completers[];
660 I9E_DUMMY_COMPLETER(jmp);
661 I9E_DUMMY_COMPLETER(next);
662 I9E_DUMMY_COMPLETER(prev);
663 I9E_DUMMY_COMPLETER(fg);
664 I9E_DUMMY_COMPLETER(bg);
665 I9E_DUMMY_COMPLETER(ls);
666 I9E_DUMMY_COMPLETER(info);
667 I9E_DUMMY_COMPLETER(play);
668 I9E_DUMMY_COMPLETER(pause);
669 I9E_DUMMY_COMPLETER(stop);
670 I9E_DUMMY_COMPLETER(tasks);
671 I9E_DUMMY_COMPLETER(quit);
672 I9E_DUMMY_COMPLETER(ff);
674 static void help_completer(struct i9e_completion_info *ci,
675 struct i9e_completion_result *result)
677 result->matches = i9e_complete_commands(ci->word, pp_completers);
680 static struct i9e_completer pp_completers[] = {PLAY_COMPLETERS {.name = NULL}};
682 static void attach_stdout(struct play_task *pt, const char *name)
686 pt->btrn = btr_new_node(&(struct btr_node_description)
687 EMBRACE(.name = name));
688 i9e_attach_to_stdout(pt->btrn);
691 static void detach_stdout(struct play_task *pt)
693 btr_remove_node(&pt->btrn);
696 static int com_quit(struct play_task *pt, int argc, __a_unused char **argv)
699 return -E_PLAY_SYNTAX;
700 pt->rq = CRT_TERM_RQ;
704 static int com_help(struct play_task *pt, int argc, char **argv)
711 return -E_PLAY_SYNTAX;
714 FOR_EACH_COMMAND(i) {
715 sz = xasprintf(&buf, "%s\t%s\n", pp_cmds[i].name,
716 pp_cmds[i].description);
717 btr_add_output(buf, sz, pt->btrn);
720 FOR_EACH_MAPPED_KEY(i) {
721 bool internal = is_internal_key(i);
722 int idx = get_key_map_idx(i);
723 char *seq = get_key_map_seq(i);
724 char *cmd = get_key_map_cmd(i);
726 "%s key #%d: %s -> %s\n",
727 internal? "internal" : "user-defined",
729 btr_add_output(buf, sz, pt->btrn);
736 FOR_EACH_COMMAND(i) {
737 if (strcmp(pp_cmds[i].name, argv[1]))
744 pp_cmds[i].description,
748 btr_add_output(buf, sz, pt->btrn);
751 return -E_BAD_PLAY_CMD;
754 static int com_info(struct play_task *pt, int argc, __a_unused char **argv)
758 static char dflt[] = "[no information available]";
761 return -E_PLAY_SYNTAX;
762 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
763 pt->current_file, conf.inputs[pt->current_file]);
764 btr_add_output(buf, sz, pt->btrn);
765 buf = pt->afhi_txt? pt->afhi_txt : dflt;
766 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
770 static void list_file(struct play_task *pt, int num)
775 sz = xasprintf(&buf, "%s %4u %s\n", num == pt->current_file?
776 "*" : " ", num, conf.inputs[num]);
777 btr_add_output(buf, sz, pt->btrn);
780 static int com_tasks(struct play_task *pt, int argc, __a_unused char **argv)
787 return -E_PLAY_SYNTAX;
789 buf = get_task_list(&sched);
790 btr_add_output(buf, strlen(buf), pt->btrn);
791 state = get_playback_state(pt);
792 sz = xasprintf(&buf, "state: %c\n", state);
793 btr_add_output(buf, sz, pt->btrn);
797 static int com_ls(struct play_task *pt, int argc, char **argv)
802 FOR_EACH_PLAYLIST_FILE(i)
806 for (j = 1; j < argc; j++) {
807 FOR_EACH_PLAYLIST_FILE(i) {
808 ret = fnmatch(argv[j], conf.inputs[i], 0);
809 if (ret == 0) /* match */
816 static int com_play(struct play_task *pt, int argc, char **argv)
823 return -E_PLAY_SYNTAX;
824 state = get_playback_state(pt);
828 pt->next_file = pt->current_file;
833 ret = para_atoi32(argv[1], &x);
836 if (x < 0 || x >= conf.inputs_num)
837 return -ERRNO_TO_PARA_ERROR(EINVAL);
840 pt->rq = CRT_FILE_CHANGE;
844 static int com_pause(struct play_task *pt, int argc, __a_unused char **argv)
847 long unsigned seconds, ss;
850 return -E_PLAY_SYNTAX;
851 state = get_playback_state(pt);
855 seconds = get_play_time(pt);
859 ss = seconds * pt->num_chunks / pt->seconds + 1;
860 ss = PARA_MAX(ss, 0UL);
861 ss = PARA_MIN(ss, pt->num_chunks);
862 pt->start_chunk = ss;
867 static int com_prev(struct play_task *pt, int argc, __a_unused char **argv)
873 return -E_PLAY_SYNTAX;
874 ret = previous_valid_file(pt);
879 pt->rq = CRT_FILE_CHANGE;
883 static int com_next(struct play_task *pt, int argc, __a_unused char **argv)
888 return -E_PLAY_SYNTAX;
889 ret = next_valid_file(pt);
894 pt->rq = CRT_FILE_CHANGE;
898 static int com_fg(struct play_task *pt, int argc, __a_unused char **argv)
901 return -E_PLAY_SYNTAX;
902 pt->background = false;
906 static int com_bg(struct play_task *pt, int argc, __a_unused char **argv)
909 return -E_PLAY_SYNTAX;
910 pt->background = true;
914 static int com_jmp(struct play_task *pt, int argc, char **argv)
920 return -E_PLAY_SYNTAX;
921 ret = para_atoi32(argv[1], &percent);
924 if (percent < 0 || percent > 100)
925 return -ERRNO_TO_PARA_ERROR(EINVAL);
926 if (pt->playing && !pt->fn.btrn)
928 pt->start_chunk = percent * pt->num_chunks / 100;
936 static int com_ff(struct play_task *pt, int argc, char **argv)
942 return -E_PLAY_SYNTAX;
943 ret = para_atoi32(argv[1], &seconds);
946 if (pt->playing && !pt->fn.btrn)
948 seconds += get_play_time(pt);
949 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
950 seconds = PARA_MAX(seconds, 0);
951 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
952 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
953 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
961 static int run_command(char *line, struct play_task *pt)
966 attach_stdout(pt, __FUNCTION__);
967 ret = create_argv(line, " ", &argv);
969 PARA_ERROR_LOG("parse error: %s\n", para_strerror(-ret));
975 FOR_EACH_COMMAND(i) {
976 if (strcmp(pp_cmds[i].name, argv[0]))
978 ret = pp_cmds[i].handler(pt, argc, argv);
980 PARA_WARNING_LOG("%s: %s\n", pt->background?
981 "" : argv[0], para_strerror(-ret));
985 PARA_WARNING_LOG("invalid command: %s\n", argv[0]);
992 static int play_i9e_line_handler(char *line)
994 struct play_task *pt = &play_task;
997 if (line == NULL || !*line)
999 ret = run_command(line, pt);
1005 static int play_i9e_key_handler(int key)
1007 struct play_task *pt = &play_task;
1008 int idx = get_key_map_idx(key);
1009 char *seq = get_key_map_seq(key);
1010 char *cmd = get_key_map_cmd(key);
1011 bool internal = is_internal_key(key);
1013 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1014 key, internal? "internal" : "user-defined",
1016 run_command(cmd, pt);
1019 pt->next_update = *now;
1023 static struct i9e_client_info ici = {
1025 .prompt = "para_play> ",
1026 .line_handler = play_i9e_line_handler,
1027 .key_handler = play_i9e_key_handler,
1028 .completers = pp_completers,
1031 static void sigint_handler(int sig)
1033 play_task.background = true;
1034 i9e_signal_dispatch(sig);
1038 * We start with para_log() set to the standard log function which writes to
1039 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1042 static void session_open(__a_unused struct play_task *pt)
1046 struct sigaction act;
1048 PARA_NOTICE_LOG("\n%s\n", VERSION_TEXT("play"));
1049 if (conf.history_file_given)
1050 history_file = para_strdup(conf.history_file_arg);
1052 char *home = para_homedir();
1053 history_file = make_message("%s/.paraslash/play.history",
1057 ici.history_file = history_file;
1058 ici.loglevel = loglevel;
1060 act.sa_handler = sigint_handler;
1061 sigemptyset(&act.sa_mask);
1063 sigaction(SIGINT, &act, NULL);
1064 act.sa_handler = i9e_signal_dispatch;
1065 sigemptyset(&act.sa_mask);
1067 sigaction(SIGWINCH, &act, NULL);
1068 sched.select_function = i9e_select;
1070 ici.bound_keyseqs = get_mapped_keyseqs();
1071 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1072 EMBRACE(.name = __FUNCTION__));
1073 ret = i9e_open(&ici, &sched);
1082 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1086 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1091 if (btr_get_output_queue_size(pt->btrn) > 0)
1093 if (btr_get_input_queue_size(pt->btrn) > 0)
1096 ie9_print_status_bar(str, len);
1100 * If we are about to die we must call i9e_close() to reset the terminal.
1101 * However, i9e_close() must be called in *this* context, i.e. from
1102 * play_task.post_select() rather than from i9e_post_select(), because
1103 * otherwise i9e would access freed memory upon return. So the play task must
1104 * stay alive until the i9e task terminates.
1106 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1107 * and reschedule. In the next iteration, i9e->post_select returns an error and
1108 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1109 * are allowed to call i9e_close() and terminate as well.
1111 static int session_post_select(__a_unused struct sched *s, struct task *t)
1113 struct play_task *pt = container_of(t, struct play_task, task);
1119 attach_stdout(pt, __FUNCTION__);
1120 ret = i9e_get_error();
1124 para_log = stderr_log;
1125 free(ici.history_file);
1128 if (get_playback_state(pt) == 'X')
1129 i9e_signal_dispatch(SIGTERM);
1133 #else /* HAVE_READLINE */
1135 static int session_post_select(struct sched *s, struct task *t)
1137 struct play_task *pt = container_of(t, struct play_task, task);
1140 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1142 if (read(STDIN_FILENO, &c, 1))
1148 static void session_open(__a_unused struct play_task *pt)
1152 static void session_update_time_string(__a_unused struct play_task *pt,
1153 char *str, __a_unused unsigned len)
1155 printf("\r%s ", str);
1158 #endif /* HAVE_READLINE */
1160 static void play_pre_select(struct sched *s, struct task *t)
1162 struct play_task *pt = container_of(t, struct play_task, task);
1165 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1166 state = get_playback_state(pt);
1167 if (state == 'R' || state == 'F' || state == 'X')
1168 return sched_min_delay(s);
1169 sched_request_barrier_or_min_delay(&pt->next_update, s);
1172 static unsigned get_time_string(struct play_task *pt, char **result)
1174 int seconds, length;
1175 char state = get_playback_state(pt);
1177 /* do not return anything if things are about to change */
1178 if (state != 'P' && state != 'U') {
1182 length = pt->seconds;
1184 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1185 seconds = get_play_time(pt);
1186 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1190 (length - seconds) / 60,
1191 (length - seconds) % 60,
1192 length? (seconds * 100 + length / 2) / length : 0,
1195 conf.inputs[pt->current_file]
1199 static void play_post_select(struct sched *s, struct task *t)
1201 struct play_task *pt = container_of(t, struct play_task, task);
1204 ret = eof_cleanup(pt);
1206 pt->rq = CRT_TERM_RQ;
1209 ret = session_post_select(s, t);
1212 if (!pt->wn.btrn && !pt->fn.btrn) {
1213 char state = get_playback_state(pt);
1214 if (state == 'P' || state == 'R' || state == 'F') {
1215 PARA_NOTICE_LOG("state: %c\n", state);
1216 ret = load_next_file(pt);
1218 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1219 pt->rq = CRT_TERM_RQ;
1223 pt->next_update = *now;
1226 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1228 unsigned len = get_time_string(pt, &str);
1229 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1231 session_update_time_string(pt, str, len);
1233 tv_add(now, &delay, &pt->next_update);
1241 * The main function of para_play.
1243 * \param argc Standard.
1244 * \param argv Standard.
1246 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1248 int main(int argc, char *argv[])
1251 struct play_task *pt = &play_task;
1253 /* needed this early to make help work */
1258 gettimeofday(now, NULL);
1259 sched.default_timeout.tv_sec = 5;
1261 parse_config_or_die(argc, argv);
1262 if (conf.inputs_num == 0)
1263 print_help_and_die();
1264 check_afh_receiver_or_die();
1267 if (conf.randomize_given)
1268 shuffle(conf.inputs, conf.inputs_num);
1269 pt->invalid = para_calloc(sizeof(*pt->invalid) * conf.inputs_num);
1270 pt->rq = CRT_FILE_CHANGE;
1271 pt->current_file = conf.inputs_num - 1;
1273 pt->task.pre_select = play_pre_select;
1274 pt->task.post_select = play_post_select;
1275 sprintf(pt->task.status, "play task");
1276 register_task(&sched, &pt->task);
1277 ret = schedule(&sched);
1279 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1280 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;