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