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