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