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