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