filter: Make ->open() optional.
[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 /**
40  * Describes a request to change the state of para_play.
41  *
42  * There is only one variable of this type: \a rq of the global play task
43  * structure. Command handlers only set this variable and the post_select()
44  * function of the play task investigates its value during each iteration of
45  * the scheduler run and performs the actual work.
46  */
47 enum state_change_request_type {
48         /** Everybody is happy. */
49         CRT_NONE,
50         /** Stream must be repositioned (com_jmp(), com_ff()). */
51         CRT_REPOS,
52         /** New file should be loaded (com_next()). */
53         CRT_FILE_CHANGE,
54         /** Someone wants us for dead (com_quit()). */
55         CRT_TERM_RQ
56 };
57
58 struct play_task {
59         struct task *task;
60         /* A bit array of invalid files (those will be skipped). */
61         bool *invalid;
62         /* The file which is currently open. */
63         unsigned current_file;
64         /* When to update the status again. */
65         struct timeval next_update;
66
67         /* Root of the buffer tree for command and status output. */
68         struct btr_node *btrn;
69
70         /* The decoding machinery.  */
71         struct receiver_node rn;
72         struct filter_node fn;
73         struct writer_node wn;
74
75         /* See comment to enum state_change_request_type above */
76         enum state_change_request_type rq;
77         /* only relevant if rq == CRT_FILE_CHANGE */
78         unsigned next_file;
79         /*
80                 bg: read lines at prompt, fg: display status and wait
81                 for keystroke.
82         */
83         bool background;
84
85         /* We have the *intention* to play. Set by com_play(). */
86         bool playing;
87
88         /* as returned by afh_recv->open() */
89         int audio_format_num;
90
91         /* retrieved via the btr exec mechanism */
92         long unsigned start_chunk;
93         long unsigned seconds;
94         long unsigned num_chunks;
95         char *afhi_txt;
96 };
97
98 /** Initialize the array of errors for para_play. */
99 INIT_PLAY_ERRLISTS;
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: %s\n", path,
332                         para_strerror(-ret));
333                 goto fail;
334         }
335         pt->audio_format_num = ret;
336         free(pt->afhi_txt);
337         ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
338         if (ret < 0)
339                 pt->afhi_txt = make_message("[afhi command failed]\n");
340         ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
341         if (ret < 0)
342                 pt->seconds = 1;
343         else {
344                 int32_t x;
345                 ret = para_atoi32(tmp, &x);
346                 pt->seconds = ret < 0? 1 : x;
347                 free(tmp);
348                 tmp = NULL;
349         }
350         ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
351         if (ret < 0)
352                 pt->num_chunks = 1;
353         else {
354                 int32_t x;
355                 ret = para_atoi32(tmp, &x);
356                 pt->num_chunks = ret < 0? 1 : x;
357                 free(tmp);
358                 tmp = NULL;
359         }
360         return 1;
361 fail:
362         wipe_receiver_node(pt);
363         return ret;
364 }
365
366 static int load_file(struct play_task *pt)
367 {
368         const char *af;
369         char *tmp, buf[20];
370         int ret;
371         const struct filter *decoder;
372
373         btr_remove_node(&pt->rn.btrn);
374         if (!pt->rn.receiver || pt->next_file != pt->current_file) {
375                 ret = open_new_file(pt);
376                 if (ret < 0)
377                         return ret;
378         } else {
379                 pt->rn.btrn = new_recv_btrn(&pt->rn);
380                 sprintf(buf, "repos %lu", pt->start_chunk);
381                 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
382                 if (ret < 0)
383                         PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
384                 freep(&tmp);
385         }
386         if (!pt->playing)
387                 return 0;
388         /* set up decoding filter */
389         af = audio_format_name(pt->audio_format_num);
390         tmp = make_message("%sdec", af);
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
403         /* setup default writer */
404         pt->wn.conf = check_writer_arg_or_die(NULL, &pt->wn.writer_num);
405
406         /* success, register tasks */
407         pt->rn.task = task_register(
408                 &(struct task_info) {
409                         .name = afh_recv->name,
410                         .pre_select = afh_recv->pre_select,
411                         .post_select = afh_recv->post_select,
412                         .context = &pt->rn
413                 }, &sched);
414         sprintf(buf, "%s decoder", af);
415         pt->fn.task = task_register(
416                 &(struct task_info) {
417                         .name = buf,
418                         .pre_select = decoder->pre_select,
419                         .post_select = decoder->post_select,
420                         .context = &pt->fn
421                 }, &sched);
422         register_writer_node(&pt->wn, pt->fn.btrn, &sched);
423         return 1;
424 fail:
425         wipe_receiver_node(pt);
426         return ret;
427 }
428
429 static int next_valid_file(struct play_task *pt)
430 {
431         int i, j = pt->current_file;
432
433         FOR_EACH_PLAYLIST_FILE(i) {
434                 j = (j + 1) % conf.inputs_num;
435                 if (!pt->invalid[j])
436                         return j;
437         }
438         return -E_NO_VALID_FILES;
439 }
440
441 static int load_next_file(struct play_task *pt)
442 {
443         int ret;
444
445 again:
446         if (pt->rq == CRT_NONE) {
447                 pt->start_chunk = 0;
448                 ret = next_valid_file(pt);
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(pt);
455         if (ret < 0) {
456                 pt->invalid[pt->next_file] = true;
457                 pt->rq = CRT_NONE;
458                 goto again;
459         }
460         pt->current_file = pt->next_file;
461         pt->rq = CRT_NONE;
462         return ret;
463 }
464
465 static void kill_stream(struct play_task *pt)
466 {
467         if (pt->wn.task)
468                 task_notify(pt->wn.task, E_EOF);
469 }
470
471 #ifdef HAVE_READLINE
472
473 /* only called from com_prev(), nec. only if we have readline */
474 static int previous_valid_file(struct play_task *pt)
475 {
476         int i, j = pt->current_file;
477
478         FOR_EACH_PLAYLIST_FILE(i) {
479                 j--;
480                 if (j < 0)
481                         j = conf.inputs_num - 1;
482                 if (!pt->invalid[j])
483                         return j;
484         }
485         return -E_NO_VALID_FILES;
486 }
487
488 #include "interactive.h"
489
490 /*
491  * Define the default (internal) key mappings and helper functions to get the
492  * key sequence or the command from a key id, which is what we obtain from
493  * i9e/readline when the key is pressed.
494  *
495  * In some of these helper functions we could return pointers to the constant
496  * arrays defined below. However, for others we can not, so let's better be
497  * consistent and allocate all returned strings on the heap.
498  */
499
500 #define INTERNAL_KEYMAP_ENTRIES \
501         KEYMAP_ENTRY("^", "jmp 0"), \
502         KEYMAP_ENTRY("1", "jmp 10"), \
503         KEYMAP_ENTRY("2", "jmp 21"), \
504         KEYMAP_ENTRY("3", "jmp 32"), \
505         KEYMAP_ENTRY("4", "jmp 43"), \
506         KEYMAP_ENTRY("5", "jmp 54"), \
507         KEYMAP_ENTRY("6", "jmp 65"), \
508         KEYMAP_ENTRY("7", "jmp 76"), \
509         KEYMAP_ENTRY("8", "jmp 87"), \
510         KEYMAP_ENTRY("9", "jmp 98"), \
511         KEYMAP_ENTRY("+", "next"), \
512         KEYMAP_ENTRY("-", "prev"), \
513         KEYMAP_ENTRY(":", "bg"), \
514         KEYMAP_ENTRY("i", "info"), \
515         KEYMAP_ENTRY("l", "ls"), \
516         KEYMAP_ENTRY("s", "play"), \
517         KEYMAP_ENTRY("p", "pause"), \
518         KEYMAP_ENTRY("q", "quit"), \
519         KEYMAP_ENTRY("?", "help"), \
520         KEYMAP_ENTRY("\033[D", "ff -10"), \
521         KEYMAP_ENTRY("\033[C", "ff 10"), \
522         KEYMAP_ENTRY("\033[A", "ff 60"), \
523         KEYMAP_ENTRY("\033[B", "ff -60"), \
524
525 #define KEYMAP_ENTRY(a, b) a
526 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
527 #undef KEYMAP_ENTRY
528 #define KEYMAP_ENTRY(a, b) b
529 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
530 #undef KEYMAP_ENTRY
531 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
532 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + conf.key_map_given)
533 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
534
535 static inline bool is_internal_key(int key)
536 {
537         return key < NUM_INTERNALLY_MAPPED_KEYS;
538 }
539
540 /* for internal keys, the key id is just the array index. */
541 static inline int get_internal_key_map_idx(int key)
542 {
543         assert(is_internal_key(key));
544         return key;
545 }
546
547 /*
548  * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
549  * difference is the index to the array of user defined key maps.
550  */
551 static inline int get_user_key_map_idx(int key)
552 {
553         assert(!is_internal_key(key));
554         return key - NUM_INTERNALLY_MAPPED_KEYS;
555 }
556
557 static inline int get_key_map_idx(int key)
558 {
559         return is_internal_key(key)?
560                 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
561 }
562
563 static inline char *get_user_key_map_arg(int key)
564 {
565         return conf.key_map_arg[get_user_key_map_idx(key)];
566 }
567
568 static inline char *get_internal_key_map_seq(int key)
569 {
570         return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
571 }
572
573 static char *get_user_key_map_seq(int key)
574 {
575         const char *kma = get_user_key_map_arg(key);
576         const char *p = strchr(kma + 1, ':');
577         char *result;
578         int len;
579
580         if (!p)
581                 return NULL;
582         len = p - kma;
583         result = para_malloc(len + 1);
584         memcpy(result, kma, len);
585         result[len] = '\0';
586         return result;
587 }
588
589 static char *get_key_map_seq(int key)
590 {
591         return is_internal_key(key)?
592                 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
593 }
594
595 static char *get_key_map_seq_safe(int key)
596 {
597         const char hex[] = "0123456789abcdef";
598         char *seq = get_key_map_seq(key), *sseq;
599         size_t n, len = strlen(seq);
600
601         if (len == 1 && isprint(*seq))
602                 return seq;
603         sseq = para_malloc(2 + 2 * len + 1);
604         sseq[0] = '0';
605         sseq[1] = 'x';
606         for (n = 0; n < len; n++) {
607                 uint8_t val = (seq[n] & 0xf0) >> 4;
608                 sseq[2 + 2 * n] = hex[val];
609                 val = seq[n] & 0xf;
610                 sseq[2 + 2 * n + 1] = hex[val];
611         }
612         free(seq);
613         sseq[2 + 2 * n] = '\0';
614         return sseq;
615 }
616
617 static inline char *get_internal_key_map_cmd(int key)
618 {
619         return para_strdup(default_commands[get_internal_key_map_idx(key)]);
620 }
621
622 static char *get_user_key_map_cmd(int key)
623 {
624         const char *kma = get_user_key_map_arg(key);
625         const char *p = strchr(kma + 1, ':');
626
627         if (!p)
628                 return NULL;
629         return para_strdup(p + 1);
630 }
631
632 static char *get_key_map_cmd(int key)
633 {
634         return is_internal_key(key)?
635                 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
636 }
637
638 static char **get_mapped_keyseqs(void)
639 {
640         char **result;
641         int i;
642
643         result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
644         FOR_EACH_MAPPED_KEY(i) {
645                 char *seq = get_key_map_seq(i);
646                 result[i] = seq;
647         }
648         result[i] = NULL;
649         return result;
650 }
651
652 #include "play.command_list.h"
653
654 typedef int play_command_handler_t(struct play_task *, int, char**);
655 static play_command_handler_t PLAY_COMMAND_HANDLERS;
656
657 /* defines one command of para_play */
658 struct pp_command {
659         const char *name;
660         play_command_handler_t *handler;
661         const char *description;
662         const char *usage;
663         const char *help;
664 };
665
666 static struct pp_command pp_cmds[] = {DEFINE_PLAY_CMD_ARRAY};
667 #define FOR_EACH_COMMAND(c) for (c = 0; pp_cmds[c].name; c++)
668
669 #include "play.completion.h"
670 static struct i9e_completer pp_completers[];
671
672 I9E_DUMMY_COMPLETER(jmp);
673 I9E_DUMMY_COMPLETER(next);
674 I9E_DUMMY_COMPLETER(prev);
675 I9E_DUMMY_COMPLETER(fg);
676 I9E_DUMMY_COMPLETER(bg);
677 I9E_DUMMY_COMPLETER(ls);
678 I9E_DUMMY_COMPLETER(info);
679 I9E_DUMMY_COMPLETER(play);
680 I9E_DUMMY_COMPLETER(pause);
681 I9E_DUMMY_COMPLETER(stop);
682 I9E_DUMMY_COMPLETER(tasks);
683 I9E_DUMMY_COMPLETER(quit);
684 I9E_DUMMY_COMPLETER(ff);
685
686 static void help_completer(struct i9e_completion_info *ci,
687                 struct i9e_completion_result *result)
688 {
689         result->matches = i9e_complete_commands(ci->word, pp_completers);
690 }
691
692 static struct i9e_completer pp_completers[] = {PLAY_COMPLETERS {.name = NULL}};
693
694 static void attach_stdout(struct play_task *pt, const char *name)
695 {
696         if (pt->btrn)
697                 return;
698         pt->btrn = btr_new_node(&(struct btr_node_description)
699                 EMBRACE(.name = name));
700         i9e_attach_to_stdout(pt->btrn);
701 }
702
703 static void detach_stdout(struct play_task *pt)
704 {
705         btr_remove_node(&pt->btrn);
706 }
707
708 static int com_quit(struct play_task *pt, int argc, __a_unused char **argv)
709 {
710         if (argc != 1)
711                 return -E_PLAY_SYNTAX;
712         pt->rq = CRT_TERM_RQ;
713         return 0;
714 }
715
716 static int com_help(struct play_task *pt, int argc, char **argv)
717 {
718         int i;
719         char *buf;
720         size_t sz;
721
722         if (argc > 2)
723                 return -E_PLAY_SYNTAX;
724         if (argc < 2) {
725                 if (pt->background)
726                         FOR_EACH_COMMAND(i) {
727                                 sz = xasprintf(&buf, "%s\t%s\n", pp_cmds[i].name,
728                                         pp_cmds[i].description);
729                                 btr_add_output(buf, sz, pt->btrn);
730                         }
731                 else {
732                         FOR_EACH_MAPPED_KEY(i) {
733                                 bool internal = is_internal_key(i);
734                                 int idx = get_key_map_idx(i);
735                                 char *seq = get_key_map_seq_safe(i);
736                                 char *cmd = get_key_map_cmd(i);
737                                 sz = xasprintf(&buf,
738                                         "%s key #%d: %s -> %s\n",
739                                         internal? "internal" : "user-defined",
740                                         idx, seq, cmd);
741                                 btr_add_output(buf, sz, pt->btrn);
742                                 free(seq);
743                                 free(cmd);
744                         }
745                 }
746                 return 0;
747         }
748         FOR_EACH_COMMAND(i) {
749                 if (strcmp(pp_cmds[i].name, argv[1]))
750                         continue;
751                 sz = xasprintf(&buf,
752                         "NAME\n\t%s -- %s\n"
753                         "SYNOPSIS\n\t%s\n"
754                         "DESCRIPTION\n%s\n",
755                         argv[1],
756                         pp_cmds[i].description,
757                         pp_cmds[i].usage,
758                         pp_cmds[i].help
759                 );
760                 btr_add_output(buf, sz, pt->btrn);
761                 return 0;
762         }
763         return -E_BAD_PLAY_CMD;
764 }
765
766 static int com_info(struct play_task *pt, int argc, __a_unused char **argv)
767 {
768         char *buf;
769         size_t sz;
770         static char dflt[] = "[no information available]";
771
772         if (argc != 1)
773                 return -E_PLAY_SYNTAX;
774         sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
775                 pt->current_file, conf.inputs[pt->current_file]);
776         btr_add_output(buf, sz, pt->btrn);
777         buf = pt->afhi_txt? pt->afhi_txt : dflt;
778         btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
779         return 0;
780 }
781
782 static void list_file(struct play_task *pt, int num)
783 {
784         char *buf;
785         size_t sz;
786
787         sz = xasprintf(&buf, "%s %4u %s\n", num == pt->current_file?
788                 "*" : " ", num, conf.inputs[num]);
789         btr_add_output(buf, sz, pt->btrn);
790 }
791
792 static int com_tasks(struct play_task *pt, int argc, __a_unused char **argv)
793 {
794         static char state;
795         char *buf;
796         size_t sz;
797
798         if (argc != 1)
799                 return -E_PLAY_SYNTAX;
800
801         buf = get_task_list(&sched);
802         btr_add_output(buf, strlen(buf), pt->btrn);
803         state = get_playback_state(pt);
804         sz = xasprintf(&buf, "state: %c\n", state);
805         btr_add_output(buf, sz, pt->btrn);
806         return 0;
807 }
808
809 static int com_ls(struct play_task *pt, int argc, char **argv)
810 {
811         int i, j, ret;
812
813         if (argc == 1) {
814                 FOR_EACH_PLAYLIST_FILE(i)
815                         list_file(pt, i);
816                 return 0;
817         }
818         for (j = 1; j < argc; j++) {
819                 FOR_EACH_PLAYLIST_FILE(i) {
820                         ret = fnmatch(argv[j], conf.inputs[i], 0);
821                         if (ret == 0) /* match */
822                                 list_file(pt, i);
823                 }
824         }
825         return 0;
826 }
827
828 static int com_play(struct play_task *pt, int argc, char **argv)
829 {
830         int32_t x;
831         int ret;
832         char state;
833
834         if (argc > 2)
835                 return -E_PLAY_SYNTAX;
836         state = get_playback_state(pt);
837         if (argc == 1) {
838                 if (state == 'P')
839                         return 0;
840                 pt->next_file = pt->current_file;
841                 pt->rq = CRT_REPOS;
842                 pt->playing = true;
843                 return 0;
844         }
845         ret = para_atoi32(argv[1], &x);
846         if (ret < 0)
847                 return ret;
848         if (x < 0 || x >= conf.inputs_num)
849                 return -ERRNO_TO_PARA_ERROR(EINVAL);
850         kill_stream(pt);
851         pt->next_file = x;
852         pt->rq = CRT_FILE_CHANGE;
853         return 0;
854 }
855
856 static int com_pause(struct play_task *pt, int argc, __a_unused char **argv)
857 {
858         char state;
859         long unsigned seconds, ss;
860
861         if (argc != 1)
862                 return -E_PLAY_SYNTAX;
863         state = get_playback_state(pt);
864         pt->playing = false;
865         if (state != 'P')
866                 return 0;
867         seconds = get_play_time(pt);
868         pt->playing = false;
869         ss = 0;
870         if (pt->seconds > 0)
871                 ss = seconds * pt->num_chunks / pt->seconds + 1;
872         ss = PARA_MAX(ss, 0UL);
873         ss = PARA_MIN(ss, pt->num_chunks);
874         pt->start_chunk = ss;
875         kill_stream(pt);
876         return 0;
877 }
878
879 static int com_prev(struct play_task *pt, int argc, __a_unused char **argv)
880
881 {
882         int ret;
883
884         if (argc != 1)
885                 return -E_PLAY_SYNTAX;
886         ret = previous_valid_file(pt);
887         if (ret < 0)
888                 return ret;
889         kill_stream(pt);
890         pt->next_file = ret;
891         pt->rq = CRT_FILE_CHANGE;
892         pt->start_chunk = 0;
893         return 0;
894 }
895
896 static int com_next(struct play_task *pt, int argc, __a_unused char **argv)
897 {
898         int ret;
899
900         if (argc != 1)
901                 return -E_PLAY_SYNTAX;
902         ret = next_valid_file(pt);
903         if (ret < 0)
904                 return ret;
905         kill_stream(pt);
906         pt->next_file = ret;
907         pt->rq = CRT_FILE_CHANGE;
908         pt->start_chunk = 0;
909         return 0;
910 }
911
912 static int com_fg(struct play_task *pt, int argc, __a_unused char **argv)
913 {
914         if (argc != 1)
915                 return -E_PLAY_SYNTAX;
916         pt->background = false;
917         return 0;
918 }
919
920 static int com_bg(struct play_task *pt, int argc, __a_unused char **argv)
921 {
922         if (argc != 1)
923                 return -E_PLAY_SYNTAX;
924         pt->background = true;
925         return 0;
926 }
927
928 static int com_jmp(struct play_task *pt, int argc, char **argv)
929 {
930         int32_t percent;
931         int ret;
932
933         if (argc != 2)
934                 return -E_PLAY_SYNTAX;
935         ret = para_atoi32(argv[1], &percent);
936         if (ret < 0)
937                 return ret;
938         if (percent < 0 || percent > 100)
939                 return -ERRNO_TO_PARA_ERROR(EINVAL);
940         if (percent == 100)
941                 return com_next(pt, 1, (char *[]){"next", NULL});
942         if (pt->playing && !pt->fn.btrn)
943                 return 0;
944         pt->start_chunk = percent * pt->num_chunks / 100;
945         if (!pt->playing)
946                 return 0;
947         pt->rq = CRT_REPOS;
948         kill_stream(pt);
949         return 0;
950 }
951
952 static int com_ff(struct play_task *pt, int argc, char **argv)
953 {
954         int32_t seconds;
955         int ret;
956
957         if (argc != 2)
958                 return -E_PLAY_SYNTAX;
959         ret = para_atoi32(argv[1], &seconds);
960         if (ret < 0)
961                 return ret;
962         if (pt->playing && !pt->fn.btrn)
963                 return 0;
964         seconds += get_play_time(pt);
965         seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
966         seconds = PARA_MAX(seconds, 0);
967         pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
968         pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
969         pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
970         if (!pt->playing)
971                 return 0;
972         pt->rq = CRT_REPOS;
973         kill_stream(pt);
974         return 0;
975 }
976
977 static int run_command(char *line, struct play_task *pt)
978 {
979         int i, ret, argc;
980         char **argv = NULL;
981
982         attach_stdout(pt, __FUNCTION__);
983         ret = create_argv(line, " ", &argv);
984         if (ret < 0) {
985                 PARA_ERROR_LOG("parse error: %s\n", para_strerror(-ret));
986                 return 0;
987         }
988         if (ret == 0)
989                 goto out;
990         argc = ret;
991         FOR_EACH_COMMAND(i) {
992                 if (strcmp(pp_cmds[i].name, argv[0]))
993                         continue;
994                 ret = pp_cmds[i].handler(pt, argc, argv);
995                 if (ret < 0)
996                         PARA_WARNING_LOG("%s: %s\n", pt->background?
997                                 "" : argv[0], para_strerror(-ret));
998                 ret = 1;
999                 goto out;
1000         }
1001         PARA_WARNING_LOG("invalid command: %s\n", argv[0]);
1002         ret = 0;
1003 out:
1004         free_argv(argv);
1005         return ret;
1006 }
1007
1008 static int play_i9e_line_handler(char *line)
1009 {
1010         return run_command(line, &play_task);
1011 }
1012
1013 static int play_i9e_key_handler(int key)
1014 {
1015         struct play_task *pt = &play_task;
1016         int idx = get_key_map_idx(key);
1017         char *seq = get_key_map_seq(key);
1018         char *cmd = get_key_map_cmd(key);
1019         bool internal = is_internal_key(key);
1020
1021         PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1022                 key, internal? "internal" : "user-defined",
1023                 idx, seq, cmd);
1024         run_command(cmd, pt);
1025         free(seq);
1026         free(cmd);
1027         pt->next_update = *now;
1028         return 0;
1029 }
1030
1031 static struct i9e_client_info ici = {
1032         .fds = {0, 1, 2},
1033         .prompt = "para_play> ",
1034         .line_handler = play_i9e_line_handler,
1035         .key_handler = play_i9e_key_handler,
1036         .completers = pp_completers,
1037 };
1038
1039 static void sigint_handler(int sig)
1040 {
1041         play_task.background = true;
1042         i9e_signal_dispatch(sig);
1043 }
1044
1045 /*
1046  * We start with para_log() set to the standard log function which writes to
1047  * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1048  * log facility.
1049  */
1050 static void session_open(struct play_task *pt)
1051 {
1052         int ret;
1053         char *history_file;
1054         struct sigaction act;
1055
1056         PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1057         if (conf.history_file_given)
1058                 history_file = para_strdup(conf.history_file_arg);
1059         else {
1060                 char *home = para_homedir();
1061                 history_file = make_message("%s/.paraslash/play.history",
1062                         home);
1063                 free(home);
1064         }
1065         ici.history_file = history_file;
1066         ici.loglevel = loglevel;
1067
1068         act.sa_handler = sigint_handler;
1069         sigemptyset(&act.sa_mask);
1070         act.sa_flags = 0;
1071         sigaction(SIGINT, &act, NULL);
1072         act.sa_handler = i9e_signal_dispatch;
1073         sigemptyset(&act.sa_mask);
1074         act.sa_flags = 0;
1075         sigaction(SIGWINCH, &act, NULL);
1076         sched.select_function = i9e_select;
1077
1078         ici.bound_keyseqs = get_mapped_keyseqs();
1079         pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1080                 EMBRACE(.name = __FUNCTION__));
1081         ret = i9e_open(&ici, &sched);
1082         if (ret < 0)
1083                 goto out;
1084         para_log = i9e_log;
1085         return;
1086 out:
1087         free(history_file);
1088         if (ret >= 0)
1089                 return;
1090         PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1091         exit(EXIT_FAILURE);
1092 }
1093
1094 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1095 {
1096         if (pt->background)
1097                 return;
1098         if (pt->btrn) {
1099                 if (btr_get_output_queue_size(pt->btrn) > 0)
1100                         return;
1101                 if (btr_get_input_queue_size(pt->btrn) > 0)
1102                         return;
1103         }
1104         ie9_print_status_bar(str, len);
1105 }
1106
1107 /*
1108  * If we are about to die we must call i9e_close() to reset the terminal.
1109  * However, i9e_close() must be called in *this* context, i.e. from
1110  * play_task.post_select() rather than from i9e_post_select(), because
1111  * otherwise i9e would access freed memory upon return. So the play task must
1112  * stay alive until the i9e task terminates.
1113  *
1114  * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1115  * and reschedule. In the next iteration, i9e->post_select returns an error and
1116  * terminates. Subsequent calls to i9e_get_error() then return negative and we
1117  * are allowed to call i9e_close() and terminate as well.
1118  */
1119 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1120 {
1121         int ret;
1122
1123         if (pt->background)
1124                 detach_stdout(pt);
1125         else
1126                 attach_stdout(pt, __FUNCTION__);
1127         ret = i9e_get_error();
1128         if (ret < 0) {
1129                 kill_stream(pt);
1130                 i9e_close();
1131                 para_log = stderr_log;
1132                 free(ici.history_file);
1133                 return ret;
1134         }
1135         if (get_playback_state(pt) == 'X')
1136                 i9e_signal_dispatch(SIGTERM);
1137         return 0;
1138 }
1139
1140 #else /* HAVE_READLINE */
1141
1142 static int session_post_select(struct sched *s, struct play_task *pt)
1143 {
1144         char c;
1145
1146         if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1147                 return 0;
1148         if (read(STDIN_FILENO, &c, 1))
1149                 do_nothing;
1150         kill_stream(pt);
1151         return 1;
1152 }
1153
1154 static void session_open(__a_unused struct play_task *pt)
1155 {
1156 }
1157
1158 static void session_update_time_string(__a_unused struct play_task *pt,
1159                 char *str, __a_unused unsigned len)
1160 {
1161         printf("\r%s     ", str);
1162         fflush(stdout);
1163 }
1164 #endif /* HAVE_READLINE */
1165
1166 static void play_pre_select(struct sched *s, void *context)
1167 {
1168         struct play_task *pt = context;
1169         char state;
1170
1171         para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1172         state = get_playback_state(pt);
1173         if (state == 'R' || state == 'F' || state == 'X')
1174                 return sched_min_delay(s);
1175         sched_request_barrier_or_min_delay(&pt->next_update, s);
1176 }
1177
1178 static unsigned get_time_string(struct play_task *pt, char **result)
1179 {
1180         int seconds, length;
1181         char state = get_playback_state(pt);
1182
1183         /* do not return anything if things are about to change */
1184         if (state != 'P' && state != 'U') {
1185                 *result = NULL;
1186                 return 0;
1187         }
1188         length = pt->seconds;
1189         if (length == 0)
1190                 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1191         seconds = get_play_time(pt);
1192         return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1193                 pt->current_file,
1194                 seconds / 60,
1195                 seconds % 60,
1196                 (length - seconds) / 60,
1197                 (length - seconds) % 60,
1198                 length? (seconds * 100 + length / 2) / length : 0,
1199                 length / 60,
1200                 length % 60,
1201                 conf.inputs[pt->current_file]
1202         );
1203 }
1204
1205 static int play_post_select(struct sched *s, void *context)
1206 {
1207         struct play_task *pt = context;
1208         int ret;
1209
1210         ret = eof_cleanup(pt);
1211         if (ret < 0) {
1212                 pt->rq = CRT_TERM_RQ;
1213                 return 0;
1214         }
1215         ret = session_post_select(s, pt);
1216         if (ret < 0)
1217                 goto out;
1218         if (!pt->wn.btrn && !pt->fn.btrn) {
1219                 char state = get_playback_state(pt);
1220                 if (state == 'P' || state == 'R' || state == 'F') {
1221                         PARA_NOTICE_LOG("state: %c\n", state);
1222                         ret = load_next_file(pt);
1223                         if (ret < 0) {
1224                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1225                                 pt->rq = CRT_TERM_RQ;
1226                                 ret = 1;
1227                                 goto out;
1228                         }
1229                         pt->next_update = *now;
1230                 }
1231         }
1232         if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1233                 char *str;
1234                 unsigned len = get_time_string(pt, &str);
1235                 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1236                 if (str && len > 0)
1237                         session_update_time_string(pt, str, len);
1238                 free(str);
1239                 tv_add(now, &delay, &pt->next_update);
1240         }
1241         ret = 1;
1242 out:
1243         return ret;
1244 }
1245
1246 /**
1247  * The main function of para_play.
1248  *
1249  * \param argc Standard.
1250  * \param argv Standard.
1251  *
1252  * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1253  */
1254 int main(int argc, char *argv[])
1255 {
1256         int ret;
1257         struct play_task *pt = &play_task;
1258
1259         /* needed this early to make help work */
1260         recv_init();
1261         filter_init();
1262         writer_init();
1263
1264         sched.default_timeout.tv_sec = 5;
1265
1266         parse_config_or_die(argc, argv);
1267         if (conf.inputs_num == 0)
1268                 print_help_and_die();
1269         check_afh_receiver_or_die();
1270
1271         session_open(pt);
1272         if (conf.randomize_given)
1273                 shuffle(conf.inputs, conf.inputs_num);
1274         pt->invalid = para_calloc(sizeof(*pt->invalid) * conf.inputs_num);
1275         pt->rq = CRT_FILE_CHANGE;
1276         pt->current_file = conf.inputs_num - 1;
1277         pt->playing = true;
1278         pt->task = task_register(&(struct task_info){
1279                 .name = "play",
1280                 .pre_select = play_pre_select,
1281                 .post_select = play_post_select,
1282                 .context = pt,
1283         }, &sched);
1284         ret = schedule(&sched);
1285         sched_shutdown(&sched);
1286         if (ret < 0)
1287                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1288         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1289 }