doc: Move filter examples to man page.
[paraslash.git] / play.c
1 /* Copyright (C) 2012 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file play.c Paraslash's standalone player. */
4
5 #include <regex.h>
6 #include <signal.h>
7 #include <lopsub.h>
8
9 #include "recv_cmd.lsg.h"
10 #include "play_cmd.lsg.h"
11 #include "write_cmd.lsg.h"
12 #include "play.lsg.h"
13 #include "para.h"
14 #include "list.h"
15 #include "error.h"
16 #include "buffer_tree.h"
17 #include "version.h"
18 #include "string.h"
19 #include "sched.h"
20 #include "filter.h"
21 #include "afh.h"
22 #include "recv.h"
23 #include "write.h"
24 #include "fd.h"
25
26 /**
27  * Besides playback tasks which correspond to the receiver/filter/writer nodes,
28  * para_play creates two further tasks: The play task and the i9e task. It is
29  * important whether a function can be called in the context of para_play or
30  * i9e or both. As a rule, all command handlers are called only in i9e context via
31  * the line handler (input mode) or the key handler (command mode) below.
32  *
33  * Playlist handling is done exclusively in play context.
34  */
35
36 /** Array of error strings. */
37 DEFINE_PARA_ERRLIST;
38
39 static struct lls_parse_result *play_lpr;
40
41 #define CMD_PTR (lls_cmd(0, play_suite))
42 #define OPT_RESULT(_name) \
43         (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
44 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
45 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
46 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
47
48 /**
49  * Describes a request to change the state of para_play.
50  *
51  * There is only one variable of this type: \a rq of the global play task
52  * structure. Command handlers only set this variable and the post_select()
53  * function of the play task investigates its value during each iteration of
54  * the scheduler run and performs the actual work.
55  */
56 enum state_change_request_type {
57         /** Everybody is happy. */
58         CRT_NONE,
59         /** Stream must be repositioned (com_jmp(), com_ff()). */
60         CRT_REPOS,
61         /** New file should be loaded (com_next()). */
62         CRT_FILE_CHANGE,
63         /** Someone wants us for dead (com_quit()). */
64         CRT_TERM_RQ
65 };
66
67 struct play_task {
68         struct task *task;
69         /* A bit array of invalid files (those will be skipped). */
70         bool *invalid;
71         /* The file which is currently open. */
72         unsigned current_file;
73         /* When to update the status again. */
74         struct timeval next_update;
75
76         /* Root of the buffer tree for command and status output. */
77         struct btr_node *btrn;
78
79         /* The decoding machinery.  */
80         struct receiver_node rn;
81         struct filter_node fn;
82         struct writer_node wn;
83
84         /* See comment to enum \ref state_change_request_type above. */
85         enum state_change_request_type rq;
86         /* only relevant if rq == CRT_FILE_CHANGE */
87         unsigned next_file;
88         /*
89                 bg: read lines at prompt, fg: display status and wait
90                 for keystroke.
91         */
92         bool background;
93
94         /* We have the *intention* to play. Set by com_play(). */
95         bool playing;
96
97         /* as returned by afh_recv->open() */
98         int audio_format_num;
99
100         /* retrieved via the btr exec mechanism */
101         long unsigned start_chunk;
102         long unsigned seconds;
103         long unsigned num_chunks;
104         char *afhi_txt;
105 };
106
107 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
108 struct play_command_info {
109         play_cmd_handler_t handler;
110 };
111 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
112         const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
113                 .handler = com_ ## _cmd \
114         };
115
116 static int loglevel = LL_WARNING;
117
118 /** The log function which writes log messages to stderr. */
119 INIT_STDERR_LOGGING(loglevel);
120
121 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
122
123 static struct sched sched = {.max_fileno = 0};
124 static struct play_task play_task, *pt = &play_task;
125
126 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
127 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
128
129 static unsigned *shuffle_map;
130
131 static const char *get_playlist_file(unsigned idx)
132 {
133         return lls_input(shuffle_map[idx], play_lpr);
134 }
135
136 static void handle_help_flags(void)
137 {
138         char *help;
139
140         if (OPT_GIVEN(DETAILED_HELP))
141                 help = lls_long_help(CMD_PTR);
142         else if (OPT_GIVEN(HELP))
143                 help = lls_short_help(CMD_PTR);
144         else
145                 return;
146         printf("%s\n", help);
147         free(help);
148         exit(EXIT_SUCCESS);
149 }
150
151 static void parse_config_or_die(int argc, char *argv[])
152 {
153         const struct lls_command *cmd = CMD_PTR;
154         int i, ret, cf_argc;
155         char *cf, *errctx, **cf_argv;
156         struct lls_parse_result *cf_lpr, *merged_lpr;
157         unsigned num_kmas;
158         void *map;
159         size_t sz;
160
161         ret = lls(lls_parse(argc, argv, cmd, &play_lpr, &errctx));
162         if (ret < 0)
163                 goto fail;
164         loglevel = OPT_UINT32_VAL(LOGLEVEL);
165         version_handle_flag("play", OPT_GIVEN(VERSION));
166         handle_help_flags();
167         if (OPT_GIVEN(CONFIG_FILE))
168                 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
169         else {
170                 char *home = para_homedir();
171                 cf = make_message("%s/.paraslash/play.conf", home);
172                 free(home);
173         }
174         ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
175         if (ret < 0) {
176                 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
177                         goto free_cf;
178                 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
179                         goto free_cf;
180                 ret = 0;
181                 goto free_cf;
182         }
183         ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
184         para_munmap(map, sz);
185         if (ret < 0)
186                 goto free_cf;
187         cf_argc = ret;
188         ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
189         lls_free_argv(cf_argv);
190         if (ret < 0)
191                 goto free_cf;
192         ret = lls(lls_merge(play_lpr, cf_lpr, cmd, &merged_lpr, &errctx));
193         lls_free_parse_result(cf_lpr, cmd);
194         if (ret < 0)
195                 goto free_cf;
196         lls_free_parse_result(play_lpr, cmd);
197         play_lpr = merged_lpr;
198         loglevel = OPT_UINT32_VAL(LOGLEVEL);
199
200         ret = lls(lls_check_arg_count(play_lpr, 1, INT_MAX, &errctx));
201         if (ret < 0)
202                 goto free_cf;
203         num_kmas = OPT_GIVEN(KEY_MAP);
204         for (i = 0; i < num_kmas; i++) {
205                 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
206                 if (*kma && strchr(kma + 1, ':'))
207                         continue;
208                 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
209                 goto free_cf;
210         }
211         ret = 1;
212 free_cf:
213         free(cf);
214         if (ret >= 0)
215                 return;
216         lls_free_parse_result(play_lpr, cmd);
217 fail:
218         if (errctx)
219                 PARA_EMERG_LOG("%s\n", errctx);
220         free(errctx);
221         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
222         exit(EXIT_FAILURE);
223 }
224
225 static char get_playback_state(void)
226 {
227         switch (pt->rq) {
228         case CRT_NONE: return pt->playing? 'P' : 'U';
229         case CRT_REPOS: return 'R';
230         case CRT_FILE_CHANGE: return 'F';
231         case CRT_TERM_RQ: return 'X';
232         }
233         assert(false);
234 };
235
236 static long unsigned get_play_time(void)
237 {
238         char state = get_playback_state();
239         long unsigned result;
240
241         if (state != 'P' && state != 'U')
242                 return 0;
243         if (pt->num_chunks == 0 || pt->seconds == 0)
244                 return 0;
245         /* where the stream started (in seconds) */
246         result = pt->start_chunk * pt->seconds / pt->num_chunks;
247         if (pt->wn.btrn) { /* Add the uptime of the writer node */
248                 struct timeval diff = {.tv_sec = 0}, wstime;
249                 btr_get_node_start(pt->wn.btrn, &wstime);
250                 if (wstime.tv_sec > 0)
251                         tv_diff(now, &wstime, &diff);
252                 result += diff.tv_sec;
253         }
254         result = PARA_MIN(result, pt->seconds);
255         result = PARA_MAX(result, 0UL);
256         return result;
257 }
258
259
260 static void wipe_receiver_node(void)
261 {
262         PARA_NOTICE_LOG("cleaning up receiver node\n");
263         btr_remove_node(&pt->rn.btrn);
264         AFH_RECV->close(&pt->rn);
265         lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
266         memset(&pt->rn, 0, sizeof(struct receiver_node));
267 }
268
269 /* returns: 0 not eof, 1: eof, < 0: fatal error.  */
270 static int get_playback_error(void)
271 {
272         int err;
273
274         if (!pt->wn.task)
275                 return 0;
276         err = task_status(pt->wn.task);
277         if (err >= 0)
278                 return 0;
279         if (task_status(pt->fn.task) >= 0)
280                 return 0;
281         if (task_status(pt->rn.task) >= 0)
282                 return 0;
283         if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
284                         || err == -E_WRITE_COMMON_EOF)
285                 return 1;
286         return err;
287 }
288
289 static int eof_cleanup(void)
290 {
291         const struct filter *decoder;
292         const struct writer *w = writer_get(-1); /* default writer */
293         int ret;
294
295         ret = get_playback_error();
296         if (ret == 0)
297                 return ret;
298         PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
299         task_reap(&pt->wn.task);
300         w->close(&pt->wn);
301         btr_remove_node(&pt->wn.btrn);
302         lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
303         memset(&pt->wn, 0, sizeof(struct writer_node));
304
305         decoder = filter_get(pt->fn.filter_num);
306         task_reap(&pt->fn.task);
307         if (decoder->close)
308                 decoder->close(&pt->fn);
309         btr_remove_node(&pt->fn.btrn);
310         free(pt->fn.conf);
311         memset(&pt->fn, 0, sizeof(struct filter_node));
312
313         task_reap(&pt->rn.task);
314         btr_remove_node(&pt->rn.btrn);
315         /*
316          * On eof (ret > 0), we do not wipe the receiver node struct until a
317          * new file is loaded because we still need it for jumping around when
318          * paused.
319          */
320         if (ret < 0)
321                 wipe_receiver_node();
322         return ret;
323 }
324
325 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
326 {
327         return para_random(100) - 50;
328 }
329
330 static void init_shuffle_map(void)
331 {
332         unsigned n, num_inputs = lls_num_inputs(play_lpr);
333         shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
334         for (n = 0; n < num_inputs; n++)
335                 shuffle_map[n] = n;
336         if (!OPT_GIVEN(RANDOMIZE))
337                 return;
338         srandom(time(NULL));
339         qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
340 }
341
342 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
343 {
344         return btr_new_node(&(struct btr_node_description)
345                 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
346                         .handler = AFH_RECV->execute));
347 }
348
349 static int open_new_file(void)
350 {
351         int ret;
352         const char *path = get_playlist_file(pt->next_file);
353         char *tmp = para_strdup(path), *errctx;
354         char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
355
356         PARA_NOTICE_LOG("next file: %s\n", path);
357         wipe_receiver_node();
358         pt->start_chunk = 0;
359         pt->rn.btrn = new_recv_btrn(&pt->rn);
360         ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
361                 &pt->rn.lpr, &errctx));
362         free(tmp);
363         assert(ret >= 0);
364         pt->rn.receiver = AFH_RECV;
365         ret = AFH_RECV->open(&pt->rn);
366         if (ret < 0) {
367                 PARA_ERROR_LOG("could not open %s\n", path);
368                 goto fail;
369         }
370         pt->audio_format_num = ret;
371         free(pt->afhi_txt);
372         ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
373         if (ret < 0)
374                 pt->afhi_txt = make_message("[afhi command failed]\n");
375         ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
376         if (ret < 0)
377                 pt->seconds = 1;
378         else {
379                 int32_t x;
380                 ret = para_atoi32(tmp, &x);
381                 pt->seconds = ret < 0? 1 : x;
382                 free(tmp);
383                 tmp = NULL;
384         }
385         ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
386         if (ret < 0)
387                 pt->num_chunks = 1;
388         else {
389                 int32_t x;
390                 ret = para_atoi32(tmp, &x);
391                 pt->num_chunks = ret < 0? 1 : x;
392                 free(tmp);
393                 tmp = NULL;
394         }
395         return 1;
396 fail:
397         wipe_receiver_node();
398         return ret;
399 }
400
401 static int load_file(void)
402 {
403         const char *af;
404         char *tmp, buf[20];
405         int ret;
406         const struct filter *decoder;
407         static struct lls_parse_result *filter_lpr, *writer_lpr;
408
409         btr_remove_node(&pt->rn.btrn);
410         if (!pt->rn.receiver || pt->next_file != pt->current_file) {
411                 ret = open_new_file();
412                 if (ret < 0)
413                         return ret;
414         } else {
415                 pt->rn.btrn = new_recv_btrn(&pt->rn);
416                 sprintf(buf, "repos %lu", pt->start_chunk);
417                 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
418                 if (ret < 0)
419                         PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
420                 freep(&tmp);
421         }
422         if (!pt->playing)
423                 return 0;
424         /* set up decoding filter */
425         af = audio_format_name(pt->audio_format_num);
426         tmp = make_message("%sdec", af);
427         ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
428         freep(&tmp);
429         if (ret < 0)
430                 goto fail;
431         pt->fn.filter_num = ret;
432         pt->fn.lpr = filter_lpr;
433         decoder = filter_get(ret);
434         pt->fn.btrn = btr_new_node(&(struct btr_node_description)
435                 EMBRACE(.name = filter_name(pt->fn.filter_num),
436                         .parent = pt->rn.btrn, .handler = decoder->execute,
437                         .context = &pt->fn));
438         if (decoder->open)
439                 decoder->open(&pt->fn);
440         PARA_INFO_LOG("buffer tree:\n");
441         btr_log_tree(pt->rn.btrn, LL_INFO);
442
443         /* setup default writer */
444         pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
445         pt->wn.lpr = writer_lpr;
446         /* success, register tasks */
447         pt->rn.task = task_register(
448                 &(struct task_info) {
449                         .name = lls_command_name(AFH_RECV_CMD),
450                         .pre_select = AFH_RECV->pre_select,
451                         .post_select = AFH_RECV->post_select,
452                         .context = &pt->rn
453                 }, &sched);
454         sprintf(buf, "%s decoder", af);
455         pt->fn.task = task_register(
456                 &(struct task_info) {
457                         .name = buf,
458                         .pre_select = decoder->pre_select,
459                         .post_select = decoder->post_select,
460                         .context = &pt->fn
461                 }, &sched);
462         register_writer_node(&pt->wn, pt->fn.btrn, &sched);
463         return 1;
464 fail:
465         wipe_receiver_node();
466         return ret;
467 }
468
469 static int next_valid_file(void)
470 {
471         int i, j = pt->current_file;
472         unsigned num_inputs = lls_num_inputs(play_lpr);
473
474         for (i = 0; i < num_inputs; i++) {
475                 j = (j + 1) % num_inputs;
476                 if (!pt->invalid[j])
477                         return j;
478         }
479         return -E_NO_VALID_FILES;
480 }
481
482 static int load_next_file(void)
483 {
484         int ret;
485
486 again:
487         if (pt->rq == CRT_NONE) {
488                 pt->start_chunk = 0;
489                 ret = next_valid_file();
490                 if (ret < 0)
491                         return ret;
492                 pt->next_file = ret;
493         } else if (pt->rq == CRT_REPOS)
494                 pt->next_file = pt->current_file;
495         ret = load_file();
496         if (ret < 0) {
497                 PARA_ERROR_LOG("%s: marking file as invalid\n",
498                         para_strerror(-ret));
499                 pt->invalid[pt->next_file] = true;
500                 pt->rq = CRT_NONE;
501                 goto again;
502         }
503         pt->current_file = pt->next_file;
504         pt->rq = CRT_NONE;
505         return ret;
506 }
507
508 static void kill_stream(void)
509 {
510         if (pt->wn.task)
511                 task_notify(pt->wn.task, E_EOF);
512 }
513
514 #ifdef HAVE_READLINE
515
516 /* only called from com_prev(), nec. only if we have readline */
517 static int previous_valid_file(void)
518 {
519         int i, j = pt->current_file;
520         unsigned num_inputs = lls_num_inputs(play_lpr);
521
522         for (i = 0; i < num_inputs; i++) {
523                 j--;
524                 if (j < 0)
525                         j = num_inputs - 1;
526                 if (!pt->invalid[j])
527                         return j;
528         }
529         return -E_NO_VALID_FILES;
530 }
531
532 #include "interactive.h"
533
534 /*
535  * Define the default (internal) key mappings and helper functions to get the
536  * key sequence or the command from a key id, which is what we obtain from
537  * i9e/readline when the key is pressed.
538  *
539  * In some of these helper functions we could return pointers to the constant
540  * arrays defined below. However, for others we can not, so let's better be
541  * consistent and allocate all returned strings on the heap.
542  */
543
544 #define INTERNAL_KEYMAP_ENTRIES \
545         KEYMAP_ENTRY("^", "jmp 0"), \
546         KEYMAP_ENTRY("1", "jmp 10"), \
547         KEYMAP_ENTRY("2", "jmp 21"), \
548         KEYMAP_ENTRY("3", "jmp 32"), \
549         KEYMAP_ENTRY("4", "jmp 43"), \
550         KEYMAP_ENTRY("5", "jmp 54"), \
551         KEYMAP_ENTRY("6", "jmp 65"), \
552         KEYMAP_ENTRY("7", "jmp 76"), \
553         KEYMAP_ENTRY("8", "jmp 87"), \
554         KEYMAP_ENTRY("9", "jmp 98"), \
555         KEYMAP_ENTRY("+", "next"), \
556         KEYMAP_ENTRY("-", "prev"), \
557         KEYMAP_ENTRY(":", "bg"), \
558         KEYMAP_ENTRY("i", "info"), \
559         KEYMAP_ENTRY("l", "ls"), \
560         KEYMAP_ENTRY("s", "play"), \
561         KEYMAP_ENTRY("p", "pause"), \
562         KEYMAP_ENTRY("q", "quit"), \
563         KEYMAP_ENTRY("?", "help"), \
564         KEYMAP_ENTRY("\033[D", "ff -10"), \
565         KEYMAP_ENTRY("\033[C", "ff 10"), \
566         KEYMAP_ENTRY("\033[A", "ff 60"), \
567         KEYMAP_ENTRY("\033[B", "ff -60"), \
568
569 #define KEYMAP_ENTRY(a, b) a
570 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
571 #undef KEYMAP_ENTRY
572 #define KEYMAP_ENTRY(a, b) b
573 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
574 #undef KEYMAP_ENTRY
575 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
576 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
577 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
578
579 static inline bool is_internal_key(int key)
580 {
581         return key < NUM_INTERNALLY_MAPPED_KEYS;
582 }
583
584 /* for internal keys, the key id is just the array index. */
585 static inline int get_internal_key_map_idx(int key)
586 {
587         assert(is_internal_key(key));
588         return key;
589 }
590
591 /*
592  * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
593  * difference is the index to the array of user defined key maps.
594  */
595 static inline int get_user_key_map_idx(int key)
596 {
597         assert(!is_internal_key(key));
598         return key - NUM_INTERNALLY_MAPPED_KEYS;
599 }
600
601 static inline int get_key_map_idx(int key)
602 {
603         return is_internal_key(key)?
604                 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
605 }
606
607 static inline const char *get_user_key_map_arg(int key)
608 {
609         return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
610 }
611
612 static inline char *get_internal_key_map_seq(int key)
613 {
614         return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
615 }
616
617 static char *get_user_key_map_seq(int key)
618 {
619         const char *kma = get_user_key_map_arg(key);
620         const char *p = strchr(kma + 1, ':');
621         char *result;
622         int len;
623
624         if (!p)
625                 return NULL;
626         len = p - kma;
627         result = para_malloc(len + 1);
628         memcpy(result, kma, len);
629         result[len] = '\0';
630         return result;
631 }
632
633 static char *get_key_map_seq(int key)
634 {
635         return is_internal_key(key)?
636                 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
637 }
638
639 static char *get_key_map_seq_safe(int key)
640 {
641         const char hex[] = "0123456789abcdef";
642         char *seq = get_key_map_seq(key), *sseq;
643         size_t n, len = strlen(seq);
644
645         if (len == 1 && isprint(*seq))
646                 return seq;
647         sseq = para_malloc(2 + 2 * len + 1);
648         sseq[0] = '0';
649         sseq[1] = 'x';
650         for (n = 0; n < len; n++) {
651                 uint8_t val = (seq[n] & 0xf0) >> 4;
652                 sseq[2 + 2 * n] = hex[val];
653                 val = seq[n] & 0xf;
654                 sseq[2 + 2 * n + 1] = hex[val];
655         }
656         free(seq);
657         sseq[2 + 2 * n] = '\0';
658         return sseq;
659 }
660
661 static inline char *get_internal_key_map_cmd(int key)
662 {
663         return para_strdup(default_commands[get_internal_key_map_idx(key)]);
664 }
665
666 static char *get_user_key_map_cmd(int key)
667 {
668         const char *kma = get_user_key_map_arg(key);
669         const char *p = strchr(kma + 1, ':');
670
671         if (!p)
672                 return NULL;
673         return para_strdup(p + 1);
674 }
675
676 static char *get_key_map_cmd(int key)
677 {
678         return is_internal_key(key)?
679                 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
680 }
681
682 static char **get_mapped_keyseqs(void)
683 {
684         char **result;
685         int i;
686
687         result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
688         FOR_EACH_MAPPED_KEY(i) {
689                 char *seq = get_key_map_seq(i);
690                 result[i] = seq;
691         }
692         result[i] = NULL;
693         return result;
694 }
695
696 static struct i9e_completer pp_completers[];
697
698 I9E_DUMMY_COMPLETER(jmp);
699 I9E_DUMMY_COMPLETER(next);
700 I9E_DUMMY_COMPLETER(prev);
701 I9E_DUMMY_COMPLETER(fg);
702 I9E_DUMMY_COMPLETER(bg);
703 I9E_DUMMY_COMPLETER(ls);
704 I9E_DUMMY_COMPLETER(info);
705 I9E_DUMMY_COMPLETER(play);
706 I9E_DUMMY_COMPLETER(pause);
707 I9E_DUMMY_COMPLETER(tasks);
708 I9E_DUMMY_COMPLETER(quit);
709 I9E_DUMMY_COMPLETER(ff);
710
711 static void help_completer(struct i9e_completion_info *ci,
712                 struct i9e_completion_result *result)
713 {
714         result->matches = i9e_complete_commands(ci->word, pp_completers);
715 }
716
717 static struct i9e_completer pp_completers[] = {
718 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
719         .completer = _name ## _completer}
720         LSG_PLAY_CMD_SUBCOMMANDS
721 #undef LSG_PLAY_CMD_CMD
722         {.name = NULL}
723 };
724
725 static void attach_stdout(const char *name)
726 {
727         if (pt->btrn)
728                 return;
729         pt->btrn = btr_new_node(&(struct btr_node_description)
730                 EMBRACE(.name = name));
731         i9e_attach_to_stdout(pt->btrn);
732 }
733
734 static void detach_stdout(void)
735 {
736         btr_remove_node(&pt->btrn);
737 }
738
739 static int com_quit(__a_unused struct lls_parse_result *lpr)
740 {
741         pt->rq = CRT_TERM_RQ;
742         return 0;
743 }
744 EXPORT_PLAY_CMD_HANDLER(quit);
745
746 static int com_help(struct lls_parse_result *lpr)
747 {
748         int i, ret;
749         char *buf, *errctx;
750         size_t sz;
751         const struct lls_command *cmd;
752
753         ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
754         if (ret < 0) {
755                 if (errctx)
756                         PARA_ERROR_LOG("%s\n", errctx);
757                 free(errctx);
758                 return ret;
759         }
760         if (lls_num_inputs(lpr) == 0) {
761                 if (pt->background) {
762                         for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
763                                 sz = xasprintf(&buf, "%s\t%s\n",
764                                         lls_command_name(cmd), lls_purpose(cmd));
765                                 btr_add_output(buf, sz, pt->btrn);
766                         }
767                         return 0;
768                 }
769                 FOR_EACH_MAPPED_KEY(i) {
770                         bool internal = is_internal_key(i);
771                         int idx = get_key_map_idx(i);
772                         char *seq = get_key_map_seq_safe(i);
773                         char *kmc = get_key_map_cmd(i);
774                         sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
775                                 internal? "internal" : "user-defined",
776                                 idx, seq, kmc);
777                         btr_add_output(buf, sz, pt->btrn);
778                         free(seq);
779                         free(kmc);
780                 }
781                 return 0;
782         }
783         ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
784                 &errctx));
785         if (ret < 0) {
786                 if (errctx)
787                         PARA_ERROR_LOG("%s\n", errctx);
788                 free(errctx);
789                 return ret;
790         }
791         cmd = lls_cmd(ret, play_cmd_suite);
792         buf = lls_long_help(cmd);
793         assert(buf);
794         btr_add_output(buf, strlen(buf), pt->btrn);
795         return 0;
796 }
797 EXPORT_PLAY_CMD_HANDLER(help);
798
799 static int com_info(__a_unused struct lls_parse_result *lpr)
800 {
801         char *buf;
802         size_t sz;
803         static char dflt[] = "[no information available]";
804
805         sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
806                 pt->current_file, get_playlist_file(pt->current_file));
807         btr_add_output(buf, sz, pt->btrn);
808         buf = pt->afhi_txt? pt->afhi_txt : dflt;
809         btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
810         return 0;
811 }
812 EXPORT_PLAY_CMD_HANDLER(info);
813
814 static void list_file(int num)
815 {
816         char *buf;
817         size_t sz;
818
819         sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
820                 "*" : " ", num, get_playlist_file(num));
821         btr_add_output(buf, sz, pt->btrn);
822 }
823
824 static int com_tasks(__a_unused struct lls_parse_result *lpr)
825 {
826         static char state;
827         char *buf;
828         size_t sz;
829
830         buf = get_task_list(&sched);
831         btr_add_output(buf, strlen(buf), pt->btrn);
832         state = get_playback_state();
833         sz = xasprintf(&buf, "state: %c\n", state);
834         btr_add_output(buf, sz, pt->btrn);
835         return 0;
836 }
837 EXPORT_PLAY_CMD_HANDLER(tasks);
838
839 static int com_ls(__a_unused struct lls_parse_result *lpr)
840 {
841         int i;
842         unsigned num_inputs = lls_num_inputs(play_lpr);
843
844         for (i = 0; i < num_inputs; i++)
845                 list_file(i);
846         return 0;
847 }
848 EXPORT_PLAY_CMD_HANDLER(ls);
849
850 static int com_play(struct lls_parse_result *lpr)
851 {
852         int32_t x;
853         int ret;
854         char state, *errctx;
855
856         ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
857         if (ret < 0) {
858                 if (errctx)
859                         PARA_ERROR_LOG("%s\n", errctx);
860                 free(errctx);
861                 return ret;
862         }
863         state = get_playback_state();
864         if (lls_num_inputs(lpr) == 0) {
865                 if (state == 'P')
866                         return 0;
867                 pt->next_file = pt->current_file;
868                 pt->rq = CRT_REPOS;
869                 pt->playing = true;
870                 return 0;
871         }
872         ret = para_atoi32(lls_input(0, lpr), &x);
873         if (ret < 0)
874                 return ret;
875         if (x < 0 || x >= lls_num_inputs(play_lpr))
876                 return -ERRNO_TO_PARA_ERROR(EINVAL);
877         kill_stream();
878         pt->next_file = x;
879         pt->rq = CRT_FILE_CHANGE;
880         return 0;
881 }
882 EXPORT_PLAY_CMD_HANDLER(play);
883
884 static int com_pause(__a_unused struct lls_parse_result *lpr)
885 {
886         char state;
887         long unsigned seconds, ss;
888
889         state = get_playback_state();
890         pt->playing = false;
891         if (state != 'P')
892                 return 0;
893         seconds = get_play_time();
894         pt->playing = false;
895         ss = 0;
896         if (pt->seconds > 0)
897                 ss = seconds * pt->num_chunks / pt->seconds + 1;
898         ss = PARA_MAX(ss, 0UL);
899         ss = PARA_MIN(ss, pt->num_chunks);
900         pt->start_chunk = ss;
901         kill_stream();
902         return 0;
903 }
904 EXPORT_PLAY_CMD_HANDLER(pause);
905
906 static int com_prev(__a_unused struct lls_parse_result *lpr)
907 {
908         int ret;
909
910         ret = previous_valid_file();
911         if (ret < 0)
912                 return ret;
913         kill_stream();
914         pt->next_file = ret;
915         pt->rq = CRT_FILE_CHANGE;
916         pt->start_chunk = 0;
917         return 0;
918 }
919 EXPORT_PLAY_CMD_HANDLER(prev);
920
921 static int com_next(__a_unused struct lls_parse_result *lpr)
922 {
923         int ret;
924
925         ret = next_valid_file();
926         if (ret < 0)
927                 return ret;
928         kill_stream();
929         pt->next_file = ret;
930         pt->rq = CRT_FILE_CHANGE;
931         pt->start_chunk = 0;
932         return 0;
933 }
934 EXPORT_PLAY_CMD_HANDLER(next);
935
936 static int com_fg(__a_unused struct lls_parse_result *lpr)
937 {
938         pt->background = false;
939         return 0;
940 }
941 EXPORT_PLAY_CMD_HANDLER(fg);
942
943 static int com_bg(__a_unused struct lls_parse_result *lpr)
944 {
945         pt->background = true;
946         return 0;
947 }
948 EXPORT_PLAY_CMD_HANDLER(bg);
949
950 static int com_jmp(struct lls_parse_result *lpr)
951 {
952         int32_t percent;
953         int ret;
954         char *errctx;
955
956         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
957         if (ret < 0) {
958                 if (errctx)
959                         PARA_ERROR_LOG("%s\n", errctx);
960                 free(errctx);
961                 return ret;
962         }
963         ret = para_atoi32(lls_input(0, lpr), &percent);
964         if (ret < 0)
965                 return ret;
966         if (percent < 0 || percent > 100)
967                 return -ERRNO_TO_PARA_ERROR(EINVAL);
968         if (percent == 100)
969                 return com_next(NULL);
970         if (pt->playing && !pt->fn.btrn)
971                 return 0;
972         pt->start_chunk = percent * pt->num_chunks / 100;
973         if (!pt->playing)
974                 return 0;
975         pt->rq = CRT_REPOS;
976         kill_stream();
977         return 0;
978 }
979 EXPORT_PLAY_CMD_HANDLER(jmp);
980
981 static int com_ff(struct lls_parse_result *lpr)
982 {
983         int32_t seconds;
984         char *errctx;
985         int ret;
986
987         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
988         if (ret < 0) {
989                 if (errctx)
990                         PARA_ERROR_LOG("%s\n", errctx);
991                 free(errctx);
992                 return ret;
993         }
994         ret = para_atoi32(lls_input(0, lpr), &seconds);
995         if (ret < 0)
996                 return ret;
997         if (pt->playing && !pt->fn.btrn)
998                 return 0;
999         seconds += get_play_time();
1000         seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
1001         seconds = PARA_MAX(seconds, 0);
1002         pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1003         pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1004         pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1005         if (!pt->playing)
1006                 return 0;
1007         pt->rq = CRT_REPOS;
1008         kill_stream();
1009         return 0;
1010 }
1011 EXPORT_PLAY_CMD_HANDLER(ff);
1012
1013 static int run_command(char *line)
1014 {
1015         int ret, argc;
1016         char **argv = NULL;
1017         char *errctx = NULL;
1018         const struct play_command_info *pci;
1019         struct lls_parse_result *lpr;
1020         const struct lls_command *cmd;
1021
1022         attach_stdout(__FUNCTION__);
1023         ret = create_argv(line, " ", &argv);
1024         if (ret < 0)
1025                 goto out;
1026         if (ret == 0)
1027                 goto out;
1028         argc = ret;
1029         ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1030         if (ret < 0)
1031                 goto out;
1032         cmd = lls_cmd(ret, play_cmd_suite);
1033         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1034         if (ret < 0)
1035                 goto out;
1036         pci = lls_user_data(cmd);
1037         ret = pci->handler(lpr);
1038         lls_free_parse_result(lpr, cmd);
1039 out:
1040         if (errctx)
1041                 PARA_ERROR_LOG("%s\n", errctx);
1042         free(errctx);
1043         free_argv(argv);
1044         return ret;
1045 }
1046
1047 static int play_i9e_line_handler(char *line)
1048 {
1049         return run_command(line);
1050 }
1051
1052 static int play_i9e_key_handler(int key)
1053 {
1054         int idx = get_key_map_idx(key);
1055         char *seq = get_key_map_seq(key);
1056         char *cmd = get_key_map_cmd(key);
1057         bool internal = is_internal_key(key);
1058
1059         PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1060                 key, internal? "internal" : "user-defined",
1061                 idx, seq, cmd);
1062         run_command(cmd);
1063         free(seq);
1064         free(cmd);
1065         pt->next_update = *now;
1066         return 0;
1067 }
1068
1069 static struct i9e_client_info ici = {
1070         .fds = {0, 1, 2},
1071         .prompt = "para_play> ",
1072         .line_handler = play_i9e_line_handler,
1073         .key_handler = play_i9e_key_handler,
1074         .completers = pp_completers,
1075 };
1076
1077 static void sigint_handler(int sig)
1078 {
1079         pt->background = true;
1080         i9e_signal_dispatch(sig);
1081 }
1082
1083 /*
1084  * We start with para_log() set to the standard log function which writes to
1085  * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1086  * log facility.
1087  */
1088 static void session_open(void)
1089 {
1090         int ret;
1091         char *history_file;
1092         struct sigaction act;
1093
1094         PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1095         if (OPT_GIVEN(HISTORY_FILE))
1096                 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1097         else {
1098                 char *home = para_homedir();
1099                 history_file = make_message("%s/.paraslash/play.history",
1100                         home);
1101                 free(home);
1102         }
1103         ici.history_file = history_file;
1104         ici.loglevel = loglevel;
1105
1106         act.sa_handler = sigint_handler;
1107         sigemptyset(&act.sa_mask);
1108         act.sa_flags = 0;
1109         sigaction(SIGINT, &act, NULL);
1110         act.sa_handler = i9e_signal_dispatch;
1111         sigemptyset(&act.sa_mask);
1112         act.sa_flags = 0;
1113         sigaction(SIGWINCH, &act, NULL);
1114         sched.select_function = i9e_select;
1115
1116         ici.bound_keyseqs = get_mapped_keyseqs();
1117         pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1118                 EMBRACE(.name = __FUNCTION__));
1119         ret = i9e_open(&ici, &sched);
1120         if (ret < 0)
1121                 goto out;
1122         para_log = i9e_log;
1123         return;
1124 out:
1125         free(history_file);
1126         if (ret >= 0)
1127                 return;
1128         PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1129         exit(EXIT_FAILURE);
1130 }
1131
1132 static void session_update_time_string(char *str, unsigned len)
1133 {
1134         if (pt->background)
1135                 return;
1136         if (pt->btrn) {
1137                 if (btr_get_output_queue_size(pt->btrn) > 0)
1138                         return;
1139                 if (btr_get_input_queue_size(pt->btrn) > 0)
1140                         return;
1141         }
1142         ie9_print_status_bar(str, len);
1143 }
1144
1145 /*
1146  * If we are about to die we must call i9e_close() to reset the terminal.
1147  * However, i9e_close() must be called in *this* context, i.e. from
1148  * play_task.post_select() rather than from i9e_post_select(), because
1149  * otherwise i9e would access freed memory upon return. So the play task must
1150  * stay alive until the i9e task terminates.
1151  *
1152  * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1153  * and reschedule. In the next iteration, i9e->post_select returns an error and
1154  * terminates. Subsequent calls to i9e_get_error() then return negative and we
1155  * are allowed to call i9e_close() and terminate as well.
1156  */
1157 static int session_post_select(__a_unused struct sched *s)
1158 {
1159         int ret;
1160
1161         if (pt->background)
1162                 detach_stdout();
1163         else
1164                 attach_stdout(__FUNCTION__);
1165         ret = i9e_get_error();
1166         if (ret < 0) {
1167                 kill_stream();
1168                 i9e_close();
1169                 para_log = stderr_log;
1170                 free(ici.history_file);
1171                 return ret;
1172         }
1173         if (get_playback_state() == 'X')
1174                 i9e_signal_dispatch(SIGTERM);
1175         return 0;
1176 }
1177
1178 #else /* HAVE_READLINE */
1179
1180 static int session_post_select(struct sched *s)
1181 {
1182         char c;
1183
1184         if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1185                 return 0;
1186         if (read(STDIN_FILENO, &c, 1))
1187                 do_nothing;
1188         kill_stream();
1189         return 1;
1190 }
1191
1192 static void session_open(void)
1193 {
1194 }
1195
1196 static void session_update_time_string(char *str, __a_unused unsigned len)
1197 {
1198         printf("\r%s     ", str);
1199         fflush(stdout);
1200 }
1201 #endif /* HAVE_READLINE */
1202
1203 static void play_pre_select(struct sched *s, __a_unused void *context)
1204 {
1205         char state;
1206
1207         para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1208         state = get_playback_state();
1209         if (state == 'R' || state == 'F' || state == 'X')
1210                 return sched_min_delay(s);
1211         sched_request_barrier_or_min_delay(&pt->next_update, s);
1212 }
1213
1214 static unsigned get_time_string(char **result)
1215 {
1216         int seconds, length;
1217         char state = get_playback_state();
1218
1219         /* do not return anything if things are about to change */
1220         if (state != 'P' && state != 'U') {
1221                 *result = NULL;
1222                 return 0;
1223         }
1224         length = pt->seconds;
1225         if (length == 0)
1226                 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1227         seconds = get_play_time();
1228         return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1229                 pt->current_file,
1230                 seconds / 60,
1231                 seconds % 60,
1232                 (length - seconds) / 60,
1233                 (length - seconds) % 60,
1234                 length? (seconds * 100 + length / 2) / length : 0,
1235                 length / 60,
1236                 length % 60,
1237                 get_playlist_file(pt->current_file)
1238         );
1239 }
1240
1241 static int play_post_select(struct sched *s, __a_unused void *context)
1242 {
1243         int ret;
1244
1245         ret = eof_cleanup();
1246         if (ret < 0) {
1247                 pt->rq = CRT_TERM_RQ;
1248                 return 0;
1249         }
1250         ret = session_post_select(s);
1251         if (ret < 0)
1252                 goto out;
1253         if (!pt->wn.btrn && !pt->fn.btrn) {
1254                 char state = get_playback_state();
1255                 if (state == 'P' || state == 'R' || state == 'F') {
1256                         PARA_NOTICE_LOG("state: %c\n", state);
1257                         ret = load_next_file();
1258                         if (ret < 0) {
1259                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1260                                 pt->rq = CRT_TERM_RQ;
1261                                 ret = 1;
1262                                 goto out;
1263                         }
1264                         pt->next_update = *now;
1265                 }
1266         }
1267         if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1268                 char *str;
1269                 unsigned len = get_time_string(&str);
1270                 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1271                 if (str && len > 0)
1272                         session_update_time_string(str, len);
1273                 free(str);
1274                 tv_add(now, &delay, &pt->next_update);
1275         }
1276         ret = 1;
1277 out:
1278         return ret;
1279 }
1280
1281 /**
1282  * The main function of para_play.
1283  *
1284  * \param argc Standard.
1285  * \param argv Standard.
1286  *
1287  * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1288  */
1289 int main(int argc, char *argv[])
1290 {
1291         int ret;
1292         unsigned num_inputs;
1293
1294         /* needed this early to make help work */
1295         recv_init();
1296
1297         sched.default_timeout.tv_sec = 5;
1298         parse_config_or_die(argc, argv);
1299         AFH_RECV->init();
1300         session_open();
1301         num_inputs = lls_num_inputs(play_lpr);
1302         init_shuffle_map();
1303         pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1304         pt->rq = CRT_FILE_CHANGE;
1305         pt->current_file = num_inputs - 1;
1306         pt->playing = true;
1307         pt->task = task_register(&(struct task_info){
1308                 .name = "play",
1309                 .pre_select = play_pre_select,
1310                 .post_select = play_post_select,
1311                 .context = pt,
1312         }, &sched);
1313         ret = schedule(&sched);
1314         sched_shutdown(&sched);
1315         if (ret < 0)
1316                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1317         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1318 }