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