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. */
14 #include "recv_cmd.lsg.h"
15 #include "play_cmd.lsg.h"
16 #include "write_cmd.lsg.h"
21 #include "buffer_tree.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.
41 /** Array of error strings. */
44 static struct lls_parse_result *play_lpr;
46 #define CMD_PTR (lls_cmd(0, play_suite))
47 #define OPT_RESULT(_name) \
48 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
49 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
50 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
51 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
54 * Describes a request to change the state of para_play.
56 * There is only one variable of this type: \a rq of the global play task
57 * structure. Command handlers only set this variable and the post_select()
58 * function of the play task investigates its value during each iteration of
59 * the scheduler run and performs the actual work.
61 enum state_change_request_type {
62 /** Everybody is happy. */
64 /** Stream must be repositioned (com_jmp(), com_ff()). */
66 /** New file should be loaded (com_next()). */
68 /** Someone wants us for dead (com_quit()). */
74 /* A bit array of invalid files (those will be skipped). */
76 /* The file which is currently open. */
77 unsigned current_file;
78 /* When to update the status again. */
79 struct timeval next_update;
81 /* Root of the buffer tree for command and status output. */
82 struct btr_node *btrn;
84 /* The decoding machinery. */
85 struct receiver_node rn;
86 struct filter_node fn;
87 struct writer_node wn;
89 /* See comment to enum \ref state_change_request_type above. */
90 enum state_change_request_type rq;
91 /* only relevant if rq == CRT_FILE_CHANGE */
94 bg: read lines at prompt, fg: display status and wait
99 /* We have the *intention* to play. Set by com_play(). */
102 /* as returned by afh_recv->open() */
103 int audio_format_num;
105 /* retrieved via the btr exec mechanism */
106 long unsigned start_chunk;
107 long unsigned seconds;
108 long unsigned num_chunks;
112 typedef int (*play_cmd_handler_t)(struct play_task *pt,
113 struct lls_parse_result *lpr);
114 struct play_command_info {
115 play_cmd_handler_t handler;
117 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
118 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
119 .handler = com_ ## _cmd \
122 static int loglevel = LL_WARNING;
124 /** The log function which writes log messages to stderr. */
125 INIT_STDERR_LOGGING(loglevel);
127 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
129 static struct sched sched = {.max_fileno = 0};
130 static struct play_task play_task;
132 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
133 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
135 static unsigned *shuffle_map;
137 static const char *get_playlist_file(unsigned idx)
139 return lls_input(shuffle_map[idx], play_lpr);
142 static void handle_help_flags(void)
146 if (OPT_GIVEN(DETAILED_HELP))
147 help = lls_long_help(CMD_PTR);
148 else if (OPT_GIVEN(HELP))
149 help = lls_short_help(CMD_PTR);
152 printf("%s\n", help);
157 static void parse_config_or_die(int argc, char *argv[])
159 const struct lls_command *cmd = CMD_PTR;
161 char *cf, *errctx, **cf_argv;
162 struct lls_parse_result *cf_lpr, *merged_lpr;
167 ret = lls(lls_parse(argc, argv, cmd, &play_lpr, &errctx));
170 loglevel = OPT_UINT32_VAL(LOGLEVEL);
171 version_handle_flag("play", OPT_GIVEN(VERSION));
173 if (OPT_GIVEN(CONFIG_FILE))
174 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
176 char *home = para_homedir();
177 cf = make_message("%s/.paraslash/play.conf", home);
180 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
182 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
184 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
189 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
190 para_munmap(map, sz);
194 ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
195 lls_free_argv(cf_argv);
198 ret = lls(lls_merge(play_lpr, cf_lpr, cmd, &merged_lpr, &errctx));
199 lls_free_parse_result(cf_lpr, cmd);
202 lls_free_parse_result(play_lpr, cmd);
203 play_lpr = merged_lpr;
204 loglevel = OPT_UINT32_VAL(LOGLEVEL);
206 ret = lls(lls_check_arg_count(play_lpr, 1, INT_MAX, &errctx));
209 num_kmas = OPT_GIVEN(KEY_MAP);
210 for (i = 0; i < num_kmas; i++) {
211 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
212 if (*kma && strchr(kma + 1, ':'))
214 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
222 lls_free_parse_result(play_lpr, cmd);
225 PARA_EMERG_LOG("%s\n", errctx);
227 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
231 static char get_playback_state(struct play_task *pt)
234 case CRT_NONE: return pt->playing? 'P' : 'U';
235 case CRT_REPOS: return 'R';
236 case CRT_FILE_CHANGE: return 'F';
237 case CRT_TERM_RQ: return 'X';
242 static long unsigned get_play_time(struct play_task *pt)
244 char state = get_playback_state(pt);
245 long unsigned result;
247 if (state != 'P' && state != 'U')
249 if (pt->num_chunks == 0 || pt->seconds == 0)
251 /* where the stream started (in seconds) */
252 result = pt->start_chunk * pt->seconds / pt->num_chunks;
253 if (pt->wn.btrn) { /* Add the uptime of the writer node */
254 struct timeval diff = {.tv_sec = 0}, wstime;
255 btr_get_node_start(pt->wn.btrn, &wstime);
256 if (wstime.tv_sec > 0)
257 tv_diff(now, &wstime, &diff);
258 result += diff.tv_sec;
260 result = PARA_MIN(result, pt->seconds);
261 result = PARA_MAX(result, 0UL);
266 static void wipe_receiver_node(struct play_task *pt)
268 PARA_NOTICE_LOG("cleaning up receiver node\n");
269 btr_remove_node(&pt->rn.btrn);
270 AFH_RECV->close(&pt->rn);
271 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
272 memset(&pt->rn, 0, sizeof(struct receiver_node));
275 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
276 static int get_playback_error(struct play_task *pt)
282 err = task_status(pt->wn.task);
285 if (task_status(pt->fn.task) >= 0)
287 if (task_status(pt->rn.task) >= 0)
289 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
290 || err == -E_WRITE_COMMON_EOF)
295 static int eof_cleanup(struct play_task *pt)
297 const struct filter *decoder;
298 const struct writer *w = writer_get(-1); /* default writer */
301 ret = get_playback_error(pt);
304 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
305 task_reap(&pt->wn.task);
307 btr_remove_node(&pt->wn.btrn);
308 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
309 memset(&pt->wn, 0, sizeof(struct writer_node));
311 decoder = filter_get(pt->fn.filter_num);
312 task_reap(&pt->fn.task);
314 decoder->close(&pt->fn);
315 btr_remove_node(&pt->fn.btrn);
317 memset(&pt->fn, 0, sizeof(struct filter_node));
319 task_reap(&pt->rn.task);
320 btr_remove_node(&pt->rn.btrn);
322 * On eof (ret > 0), we do not wipe the receiver node struct until a
323 * new file is loaded because we still need it for jumping around when
327 wipe_receiver_node(pt);
331 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
333 return para_random(100) - 50;
336 static void init_shuffle_map(void)
338 unsigned n, num_inputs = lls_num_inputs(play_lpr);
339 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
340 for (n = 0; n < num_inputs; n++)
342 if (!OPT_GIVEN(RANDOMIZE))
345 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
348 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
350 return btr_new_node(&(struct btr_node_description)
351 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
352 .handler = AFH_RECV->execute));
355 static int open_new_file(struct play_task *pt)
358 const char *path = get_playlist_file(pt->next_file);
359 char *tmp = para_strdup(path), *errctx;
360 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
362 PARA_NOTICE_LOG("next file: %s\n", path);
363 wipe_receiver_node(pt);
365 pt->rn.btrn = new_recv_btrn(&pt->rn);
366 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
367 &pt->rn.lpr, &errctx));
370 pt->rn.receiver = AFH_RECV;
371 ret = AFH_RECV->open(&pt->rn);
373 PARA_ERROR_LOG("could not open %s\n", path);
376 pt->audio_format_num = ret;
378 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
380 pt->afhi_txt = make_message("[afhi command failed]\n");
381 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
386 ret = para_atoi32(tmp, &x);
387 pt->seconds = ret < 0? 1 : x;
391 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
396 ret = para_atoi32(tmp, &x);
397 pt->num_chunks = ret < 0? 1 : x;
403 wipe_receiver_node(pt);
407 static int load_file(struct play_task *pt)
412 const struct filter *decoder;
413 static struct lls_parse_result *filter_lpr, *writer_lpr;
415 btr_remove_node(&pt->rn.btrn);
416 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
417 ret = open_new_file(pt);
421 pt->rn.btrn = new_recv_btrn(&pt->rn);
422 sprintf(buf, "repos %lu", pt->start_chunk);
423 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
425 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
430 /* set up decoding filter */
431 af = audio_format_name(pt->audio_format_num);
432 tmp = make_message("%sdec", af);
433 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
437 pt->fn.filter_num = ret;
438 pt->fn.lpr = filter_lpr;
439 decoder = filter_get(ret);
440 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
441 EMBRACE(.name = filter_name(pt->fn.filter_num),
442 .parent = pt->rn.btrn, .handler = decoder->execute,
443 .context = &pt->fn));
445 decoder->open(&pt->fn);
446 PARA_INFO_LOG("buffer tree:\n");
447 btr_log_tree(pt->rn.btrn, LL_INFO);
449 /* setup default writer */
450 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
451 pt->wn.lpr = writer_lpr;
452 /* success, register tasks */
453 pt->rn.task = task_register(
454 &(struct task_info) {
455 .name = lls_command_name(AFH_RECV_CMD),
456 .pre_select = AFH_RECV->pre_select,
457 .post_select = AFH_RECV->post_select,
460 sprintf(buf, "%s decoder", af);
461 pt->fn.task = task_register(
462 &(struct task_info) {
464 .pre_select = decoder->pre_select,
465 .post_select = decoder->post_select,
468 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
471 wipe_receiver_node(pt);
475 static int next_valid_file(struct play_task *pt)
477 int i, j = pt->current_file;
478 unsigned num_inputs = lls_num_inputs(play_lpr);
480 for (i = 0; i < num_inputs; i++) {
481 j = (j + 1) % num_inputs;
485 return -E_NO_VALID_FILES;
488 static int load_next_file(struct play_task *pt)
493 if (pt->rq == CRT_NONE) {
495 ret = next_valid_file(pt);
499 } else if (pt->rq == CRT_REPOS)
500 pt->next_file = pt->current_file;
503 PARA_ERROR_LOG("%s: marking file as invalid\n",
504 para_strerror(-ret));
505 pt->invalid[pt->next_file] = true;
509 pt->current_file = pt->next_file;
514 static void kill_stream(struct play_task *pt)
517 task_notify(pt->wn.task, E_EOF);
522 /* only called from com_prev(), nec. only if we have readline */
523 static int previous_valid_file(struct play_task *pt)
525 int i, j = pt->current_file;
526 unsigned num_inputs = lls_num_inputs(play_lpr);
528 for (i = 0; i < num_inputs; i++) {
535 return -E_NO_VALID_FILES;
538 #include "interactive.h"
541 * Define the default (internal) key mappings and helper functions to get the
542 * key sequence or the command from a key id, which is what we obtain from
543 * i9e/readline when the key is pressed.
545 * In some of these helper functions we could return pointers to the constant
546 * arrays defined below. However, for others we can not, so let's better be
547 * consistent and allocate all returned strings on the heap.
550 #define INTERNAL_KEYMAP_ENTRIES \
551 KEYMAP_ENTRY("^", "jmp 0"), \
552 KEYMAP_ENTRY("1", "jmp 10"), \
553 KEYMAP_ENTRY("2", "jmp 21"), \
554 KEYMAP_ENTRY("3", "jmp 32"), \
555 KEYMAP_ENTRY("4", "jmp 43"), \
556 KEYMAP_ENTRY("5", "jmp 54"), \
557 KEYMAP_ENTRY("6", "jmp 65"), \
558 KEYMAP_ENTRY("7", "jmp 76"), \
559 KEYMAP_ENTRY("8", "jmp 87"), \
560 KEYMAP_ENTRY("9", "jmp 98"), \
561 KEYMAP_ENTRY("+", "next"), \
562 KEYMAP_ENTRY("-", "prev"), \
563 KEYMAP_ENTRY(":", "bg"), \
564 KEYMAP_ENTRY("i", "info"), \
565 KEYMAP_ENTRY("l", "ls"), \
566 KEYMAP_ENTRY("s", "play"), \
567 KEYMAP_ENTRY("p", "pause"), \
568 KEYMAP_ENTRY("q", "quit"), \
569 KEYMAP_ENTRY("?", "help"), \
570 KEYMAP_ENTRY("\033[D", "ff -10"), \
571 KEYMAP_ENTRY("\033[C", "ff 10"), \
572 KEYMAP_ENTRY("\033[A", "ff 60"), \
573 KEYMAP_ENTRY("\033[B", "ff -60"), \
575 #define KEYMAP_ENTRY(a, b) a
576 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
578 #define KEYMAP_ENTRY(a, b) b
579 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
581 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
582 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
583 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
585 static inline bool is_internal_key(int key)
587 return key < NUM_INTERNALLY_MAPPED_KEYS;
590 /* for internal keys, the key id is just the array index. */
591 static inline int get_internal_key_map_idx(int key)
593 assert(is_internal_key(key));
598 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
599 * difference is the index to the array of user defined key maps.
601 static inline int get_user_key_map_idx(int key)
603 assert(!is_internal_key(key));
604 return key - NUM_INTERNALLY_MAPPED_KEYS;
607 static inline int get_key_map_idx(int key)
609 return is_internal_key(key)?
610 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
613 static inline const char *get_user_key_map_arg(int key)
615 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
618 static inline char *get_internal_key_map_seq(int key)
620 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
623 static char *get_user_key_map_seq(int key)
625 const char *kma = get_user_key_map_arg(key);
626 const char *p = strchr(kma + 1, ':');
633 result = para_malloc(len + 1);
634 memcpy(result, kma, len);
639 static char *get_key_map_seq(int key)
641 return is_internal_key(key)?
642 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
645 static char *get_key_map_seq_safe(int key)
647 const char hex[] = "0123456789abcdef";
648 char *seq = get_key_map_seq(key), *sseq;
649 size_t n, len = strlen(seq);
651 if (len == 1 && isprint(*seq))
653 sseq = para_malloc(2 + 2 * len + 1);
656 for (n = 0; n < len; n++) {
657 uint8_t val = (seq[n] & 0xf0) >> 4;
658 sseq[2 + 2 * n] = hex[val];
660 sseq[2 + 2 * n + 1] = hex[val];
663 sseq[2 + 2 * n] = '\0';
667 static inline char *get_internal_key_map_cmd(int key)
669 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
672 static char *get_user_key_map_cmd(int key)
674 const char *kma = get_user_key_map_arg(key);
675 const char *p = strchr(kma + 1, ':');
679 return para_strdup(p + 1);
682 static char *get_key_map_cmd(int key)
684 return is_internal_key(key)?
685 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
688 static char **get_mapped_keyseqs(void)
693 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
694 FOR_EACH_MAPPED_KEY(i) {
695 char *seq = get_key_map_seq(i);
702 static struct i9e_completer pp_completers[];
704 I9E_DUMMY_COMPLETER(jmp);
705 I9E_DUMMY_COMPLETER(next);
706 I9E_DUMMY_COMPLETER(prev);
707 I9E_DUMMY_COMPLETER(fg);
708 I9E_DUMMY_COMPLETER(bg);
709 I9E_DUMMY_COMPLETER(ls);
710 I9E_DUMMY_COMPLETER(info);
711 I9E_DUMMY_COMPLETER(play);
712 I9E_DUMMY_COMPLETER(pause);
713 I9E_DUMMY_COMPLETER(tasks);
714 I9E_DUMMY_COMPLETER(quit);
715 I9E_DUMMY_COMPLETER(ff);
717 static void help_completer(struct i9e_completion_info *ci,
718 struct i9e_completion_result *result)
720 result->matches = i9e_complete_commands(ci->word, pp_completers);
723 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
724 static struct i9e_completer pp_completers[] = {
725 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
726 .completer = _name ## _completer}
727 LSG_PLAY_CMD_SUBCOMMANDS
728 #undef LSG_PLAY_CMD_CMD
732 static void attach_stdout(struct play_task *pt, const char *name)
736 pt->btrn = btr_new_node(&(struct btr_node_description)
737 EMBRACE(.name = name));
738 i9e_attach_to_stdout(pt->btrn);
741 static void detach_stdout(struct play_task *pt)
743 btr_remove_node(&pt->btrn);
746 static int com_quit(struct play_task *pt,
747 __a_unused struct lls_parse_result *lpr)
749 pt->rq = CRT_TERM_RQ;
752 EXPORT_PLAY_CMD_HANDLER(quit);
754 static int com_help(struct play_task *pt, struct lls_parse_result *lpr)
759 const struct lls_command *cmd;
761 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
764 PARA_ERROR_LOG("%s\n", errctx);
768 if (lls_num_inputs(lpr) == 0) {
769 if (pt->background) {
770 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
771 sz = xasprintf(&buf, "%s\t%s\n",
772 lls_command_name(cmd), lls_purpose(cmd));
773 btr_add_output(buf, sz, pt->btrn);
777 FOR_EACH_MAPPED_KEY(i) {
778 bool internal = is_internal_key(i);
779 int idx = get_key_map_idx(i);
780 char *seq = get_key_map_seq_safe(i);
781 char *kmc = get_key_map_cmd(i);
782 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
783 internal? "internal" : "user-defined",
785 btr_add_output(buf, sz, pt->btrn);
791 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
795 PARA_ERROR_LOG("%s\n", errctx);
799 cmd = lls_cmd(ret, play_cmd_suite);
800 buf = lls_long_help(cmd);
802 btr_add_output(buf, strlen(buf), pt->btrn);
805 EXPORT_PLAY_CMD_HANDLER(help);
807 static int com_info(struct play_task *pt,
808 __a_unused struct lls_parse_result *lpr)
812 static char dflt[] = "[no information available]";
814 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
815 pt->current_file, get_playlist_file(pt->current_file));
816 btr_add_output(buf, sz, pt->btrn);
817 buf = pt->afhi_txt? pt->afhi_txt : dflt;
818 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
821 EXPORT_PLAY_CMD_HANDLER(info);
823 static void list_file(struct play_task *pt, int num)
828 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
829 "*" : " ", num, get_playlist_file(num));
830 btr_add_output(buf, sz, pt->btrn);
833 static int com_tasks(struct play_task *pt,
834 __a_unused struct lls_parse_result *lpr)
840 buf = get_task_list(&sched);
841 btr_add_output(buf, strlen(buf), pt->btrn);
842 state = get_playback_state(pt);
843 sz = xasprintf(&buf, "state: %c\n", state);
844 btr_add_output(buf, sz, pt->btrn);
847 EXPORT_PLAY_CMD_HANDLER(tasks);
849 static int com_ls(struct play_task *pt,
850 __a_unused struct lls_parse_result *lpr)
853 unsigned num_inputs = lls_num_inputs(play_lpr);
855 for (i = 0; i < num_inputs; i++)
859 EXPORT_PLAY_CMD_HANDLER(ls);
861 static int com_play(struct play_task *pt, struct lls_parse_result *lpr)
867 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
870 PARA_ERROR_LOG("%s\n", errctx);
874 state = get_playback_state(pt);
875 if (lls_num_inputs(lpr) == 0) {
878 pt->next_file = pt->current_file;
883 ret = para_atoi32(lls_input(0, lpr), &x);
886 if (x < 0 || x >= lls_num_inputs(play_lpr))
887 return -ERRNO_TO_PARA_ERROR(EINVAL);
890 pt->rq = CRT_FILE_CHANGE;
893 EXPORT_PLAY_CMD_HANDLER(play);
895 static int com_pause(struct play_task *pt,
896 __a_unused struct lls_parse_result *lpr)
899 long unsigned seconds, ss;
901 state = get_playback_state(pt);
905 seconds = get_play_time(pt);
909 ss = seconds * pt->num_chunks / pt->seconds + 1;
910 ss = PARA_MAX(ss, 0UL);
911 ss = PARA_MIN(ss, pt->num_chunks);
912 pt->start_chunk = ss;
916 EXPORT_PLAY_CMD_HANDLER(pause);
918 static int com_prev(struct play_task *pt,
919 __a_unused struct lls_parse_result *lpr)
923 ret = previous_valid_file(pt);
928 pt->rq = CRT_FILE_CHANGE;
932 EXPORT_PLAY_CMD_HANDLER(prev);
934 static int com_next(struct play_task *pt,
935 __a_unused struct lls_parse_result *lpr)
939 ret = next_valid_file(pt);
944 pt->rq = CRT_FILE_CHANGE;
948 EXPORT_PLAY_CMD_HANDLER(next);
950 static int com_fg(struct play_task *pt,
951 __a_unused struct lls_parse_result *lpr)
953 pt->background = false;
956 EXPORT_PLAY_CMD_HANDLER(fg);
958 static int com_bg(struct play_task *pt,
959 __a_unused struct lls_parse_result *lpr)
961 pt->background = true;
964 EXPORT_PLAY_CMD_HANDLER(bg);
966 static int com_jmp(struct play_task *pt, struct lls_parse_result *lpr)
972 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
975 PARA_ERROR_LOG("%s\n", errctx);
979 ret = para_atoi32(lls_input(0, lpr), &percent);
982 if (percent < 0 || percent > 100)
983 return -ERRNO_TO_PARA_ERROR(EINVAL);
985 return com_next(pt, NULL);
986 if (pt->playing && !pt->fn.btrn)
988 pt->start_chunk = percent * pt->num_chunks / 100;
995 EXPORT_PLAY_CMD_HANDLER(jmp);
997 static int com_ff(struct play_task *pt, struct lls_parse_result *lpr)
1003 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
1006 PARA_ERROR_LOG("%s\n", errctx);
1010 ret = para_atoi32(lls_input(0, lpr), &seconds);
1013 if (pt->playing && !pt->fn.btrn)
1015 seconds += get_play_time(pt);
1016 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
1017 seconds = PARA_MAX(seconds, 0);
1018 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1019 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1020 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1027 EXPORT_PLAY_CMD_HANDLER(ff);
1029 static int run_command(char *line, struct play_task *pt)
1033 char *errctx = NULL;
1034 const struct play_command_info *pci;
1035 struct lls_parse_result *lpr;
1036 const struct lls_command *cmd;
1038 attach_stdout(pt, __FUNCTION__);
1039 ret = create_argv(line, " ", &argv);
1045 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1048 cmd = lls_cmd(ret, play_cmd_suite);
1049 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1052 pci = lls_user_data(cmd);
1053 ret = pci->handler(pt, lpr);
1054 lls_free_parse_result(lpr, cmd);
1057 PARA_ERROR_LOG("%s\n", errctx);
1063 static int play_i9e_line_handler(char *line)
1065 return run_command(line, &play_task);
1068 static int play_i9e_key_handler(int key)
1070 struct play_task *pt = &play_task;
1071 int idx = get_key_map_idx(key);
1072 char *seq = get_key_map_seq(key);
1073 char *cmd = get_key_map_cmd(key);
1074 bool internal = is_internal_key(key);
1076 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1077 key, internal? "internal" : "user-defined",
1079 run_command(cmd, pt);
1082 pt->next_update = *now;
1086 static struct i9e_client_info ici = {
1088 .prompt = "para_play> ",
1089 .line_handler = play_i9e_line_handler,
1090 .key_handler = play_i9e_key_handler,
1091 .completers = pp_completers,
1094 static void sigint_handler(int sig)
1096 play_task.background = true;
1097 i9e_signal_dispatch(sig);
1101 * We start with para_log() set to the standard log function which writes to
1102 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1105 static void session_open(struct play_task *pt)
1109 struct sigaction act;
1111 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1112 if (OPT_GIVEN(HISTORY_FILE))
1113 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1115 char *home = para_homedir();
1116 history_file = make_message("%s/.paraslash/play.history",
1120 ici.history_file = history_file;
1121 ici.loglevel = loglevel;
1123 act.sa_handler = sigint_handler;
1124 sigemptyset(&act.sa_mask);
1126 sigaction(SIGINT, &act, NULL);
1127 act.sa_handler = i9e_signal_dispatch;
1128 sigemptyset(&act.sa_mask);
1130 sigaction(SIGWINCH, &act, NULL);
1131 sched.select_function = i9e_select;
1133 ici.bound_keyseqs = get_mapped_keyseqs();
1134 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1135 EMBRACE(.name = __FUNCTION__));
1136 ret = i9e_open(&ici, &sched);
1145 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1149 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1154 if (btr_get_output_queue_size(pt->btrn) > 0)
1156 if (btr_get_input_queue_size(pt->btrn) > 0)
1159 ie9_print_status_bar(str, len);
1163 * If we are about to die we must call i9e_close() to reset the terminal.
1164 * However, i9e_close() must be called in *this* context, i.e. from
1165 * play_task.post_select() rather than from i9e_post_select(), because
1166 * otherwise i9e would access freed memory upon return. So the play task must
1167 * stay alive until the i9e task terminates.
1169 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1170 * and reschedule. In the next iteration, i9e->post_select returns an error and
1171 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1172 * are allowed to call i9e_close() and terminate as well.
1174 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1181 attach_stdout(pt, __FUNCTION__);
1182 ret = i9e_get_error();
1186 para_log = stderr_log;
1187 free(ici.history_file);
1190 if (get_playback_state(pt) == 'X')
1191 i9e_signal_dispatch(SIGTERM);
1195 #else /* HAVE_READLINE */
1197 static int session_post_select(struct sched *s, struct play_task *pt)
1201 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1203 if (read(STDIN_FILENO, &c, 1))
1209 static void session_open(__a_unused struct play_task *pt)
1213 static void session_update_time_string(__a_unused struct play_task *pt,
1214 char *str, __a_unused unsigned len)
1216 printf("\r%s ", str);
1219 #endif /* HAVE_READLINE */
1221 static void play_pre_select(struct sched *s, void *context)
1223 struct play_task *pt = context;
1226 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1227 state = get_playback_state(pt);
1228 if (state == 'R' || state == 'F' || state == 'X')
1229 return sched_min_delay(s);
1230 sched_request_barrier_or_min_delay(&pt->next_update, s);
1233 static unsigned get_time_string(struct play_task *pt, char **result)
1235 int seconds, length;
1236 char state = get_playback_state(pt);
1238 /* do not return anything if things are about to change */
1239 if (state != 'P' && state != 'U') {
1243 length = pt->seconds;
1245 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1246 seconds = get_play_time(pt);
1247 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1251 (length - seconds) / 60,
1252 (length - seconds) % 60,
1253 length? (seconds * 100 + length / 2) / length : 0,
1256 get_playlist_file(pt->current_file)
1260 static int play_post_select(struct sched *s, void *context)
1262 struct play_task *pt = context;
1265 ret = eof_cleanup(pt);
1267 pt->rq = CRT_TERM_RQ;
1270 ret = session_post_select(s, pt);
1273 if (!pt->wn.btrn && !pt->fn.btrn) {
1274 char state = get_playback_state(pt);
1275 if (state == 'P' || state == 'R' || state == 'F') {
1276 PARA_NOTICE_LOG("state: %c\n", state);
1277 ret = load_next_file(pt);
1279 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1280 pt->rq = CRT_TERM_RQ;
1284 pt->next_update = *now;
1287 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1289 unsigned len = get_time_string(pt, &str);
1290 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1292 session_update_time_string(pt, str, len);
1294 tv_add(now, &delay, &pt->next_update);
1302 * The main function of para_play.
1304 * \param argc Standard.
1305 * \param argv Standard.
1307 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1309 int main(int argc, char *argv[])
1312 struct play_task *pt = &play_task;
1313 unsigned num_inputs;
1315 /* needed this early to make help work */
1318 sched.default_timeout.tv_sec = 5;
1319 parse_config_or_die(argc, argv);
1322 num_inputs = lls_num_inputs(play_lpr);
1324 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1325 pt->rq = CRT_FILE_CHANGE;
1326 pt->current_file = num_inputs - 1;
1328 pt->task = task_register(&(struct task_info){
1330 .pre_select = play_pre_select,
1331 .post_select = play_post_select,
1334 ret = schedule(&sched);
1335 sched_shutdown(&sched);
1337 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1338 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;