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