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