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