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