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