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