less: fix help text conditional for -R
[oweals/busybox.git] / miscutils / fbsplash.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Copyright (C) 2008 Michele Sanges <michele.sanges@gmail.com>
4  *
5  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
6  *
7  * Usage:
8  * - use kernel option 'vga=xxx' or otherwise enable framebuffer device.
9  * - put somewhere fbsplash.cfg file and an image in .ppm format.
10  * - run applet: $ setsid fbsplash [params] &
11  *      -c: hide cursor
12  *      -d /dev/fbN: framebuffer device (if not /dev/fb0)
13  *      -s path_to_image_file (can be "-" for stdin)
14  *      -i path_to_cfg_file
15  *      -f path_to_fifo (can be "-" for stdin)
16  * - if you want to run it only in presence of a kernel parameter
17  *   (for example fbsplash=on), use:
18  *   grep -q "fbsplash=on" </proc/cmdline && setsid fbsplash [params]
19  * - commands for fifo:
20  *   "NN" (ASCII decimal number) - percentage to show on progress bar.
21  *   "exit" (or just close fifo) - well you guessed it.
22  */
23 //config:config FBSPLASH
24 //config:       bool "fbsplash (27 kb)"
25 //config:       default y
26 //config:       select PLATFORM_LINUX
27 //config:       help
28 //config:       Shows splash image and progress bar on framebuffer device.
29 //config:       Can be used during boot phase of an embedded device.
30 //config:       Usage:
31 //config:       - use kernel option 'vga=xxx' or otherwise enable fb device.
32 //config:       - put somewhere fbsplash.cfg file and an image in .ppm format.
33 //config:       - $ setsid fbsplash [params] &
34 //config:           -c: hide cursor
35 //config:           -d /dev/fbN: framebuffer device (if not /dev/fb0)
36 //config:           -s path_to_image_file (can be "-" for stdin)
37 //config:           -i path_to_cfg_file (can be "-" for stdin)
38 //config:           -f path_to_fifo (can be "-" for stdin)
39 //config:       - if you want to run it only in presence of kernel parameter:
40 //config:           grep -q "fbsplash=on" </proc/cmdline && setsid fbsplash [params] &
41 //config:       - commands for fifo:
42 //config:           "NN" (ASCII decimal number) - percentage to show on progress bar
43 //config:           "exit" - well you guessed it
44
45 //applet:IF_FBSPLASH(APPLET(fbsplash, BB_DIR_SBIN, BB_SUID_DROP))
46
47 //kbuild:lib-$(CONFIG_FBSPLASH) += fbsplash.o
48
49 //usage:#define fbsplash_trivial_usage
50 //usage:       "-s IMGFILE [-c] [-d DEV] [-i INIFILE] [-f CMD]"
51 //usage:#define fbsplash_full_usage "\n\n"
52 //usage:       "        -s      Image"
53 //usage:     "\n        -c      Hide cursor"
54 //usage:     "\n        -d      Framebuffer device (default /dev/fb0)"
55 //usage:     "\n        -i      Config file (var=value):"
56 //usage:     "\n                        BAR_LEFT,BAR_TOP,BAR_WIDTH,BAR_HEIGHT"
57 //usage:     "\n                        BAR_R,BAR_G,BAR_B"
58 //usage:     "\n        -f      Control pipe (else exit after drawing image)"
59 //usage:     "\n                        commands: 'NN' (% for progress bar) or 'exit'"
60
61 #include "libbb.h"
62 #include "common_bufsiz.h"
63 #include <linux/fb.h>
64
65 /* If you want logging messages on /tmp/fbsplash.log... */
66 #define DEBUG 0
67
68 #define ESC "\033"
69
70 struct globals {
71 #if DEBUG
72         bool bdebug_messages;   // enable/disable logging
73         FILE *logfile_fd;       // log file
74 #endif
75         unsigned char *addr;    // pointer to framebuffer memory
76         unsigned ns[7];         // n-parameters
77         const char *image_filename;
78         struct fb_var_screeninfo scr_var;
79         struct fb_fix_screeninfo scr_fix;
80         unsigned bytes_per_pixel;
81         // cached (8 - scr_var.COLOR.length):
82         unsigned red_shift;
83         unsigned green_shift;
84         unsigned blue_shift;
85 };
86 #define G (*ptr_to_globals)
87 #define INIT_G() do { \
88         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
89 } while (0)
90
91 #define nbar_width      ns[0]   // progress bar width
92 #define nbar_height     ns[1]   // progress bar height
93 #define nbar_posx       ns[2]   // progress bar horizontal position
94 #define nbar_posy       ns[3]   // progress bar vertical position
95 #define nbar_colr       ns[4]   // progress bar color red component
96 #define nbar_colg       ns[5]   // progress bar color green component
97 #define nbar_colb       ns[6]   // progress bar color blue component
98
99 #if DEBUG
100 #define DEBUG_MESSAGE(strMessage, args...) \
101         if (G.bdebug_messages) { \
102                 fprintf(G.logfile_fd, "[%s][%s] - %s\n", \
103                 __FILE__, __FUNCTION__, strMessage);    \
104         }
105 #else
106 #define DEBUG_MESSAGE(...) ((void)0)
107 #endif
108
109 /**
110  * Configure palette for RGB:332
111  */
112 static void fb_setpal(int fd)
113 {
114         struct fb_cmap cmap;
115         /* fb colors are 16 bit */
116         unsigned short red[256], green[256], blue[256];
117         unsigned i;
118
119         /* RGB:332 */
120         for (i = 0; i < 256; i++) {
121                 /* Color is encoded in pixel value as rrrgggbb.
122                  * 3-bit color is mapped to 16-bit one as:
123                  * 000 -> 00000000 00000000
124                  * 001 -> 00100100 10010010
125                  * ...
126                  * 011 -> 01101101 10110110
127                  * 100 -> 10010010 01001001
128                  * ...
129                  * 111 -> 11111111 11111111
130                  */
131                 red[i]   = (( i >> 5       ) * 0x9249) >> 2; // rrr * 00 10010010 01001001 >> 2
132                 green[i] = (((i >> 2) & 0x7) * 0x9249) >> 2; // ggg * 00 10010010 01001001 >> 2
133                 /* 2-bit color is easier: */
134                 blue[i]  =  ( i       & 0x3) * 0x5555; // bb * 01010101 01010101
135         }
136
137         cmap.start = 0;
138         cmap.len   = 256;
139         cmap.red   = red;
140         cmap.green = green;
141         cmap.blue  = blue;
142         cmap.transp = 0;
143
144         xioctl(fd, FBIOPUTCMAP, &cmap);
145 }
146
147 /**
148  * Open and initialize the framebuffer device
149  * \param *strfb_device pointer to framebuffer device
150  */
151 static void fb_open(const char *strfb_device)
152 {
153         int fbfd = xopen(strfb_device, O_RDWR);
154
155         // framebuffer properties
156         xioctl(fbfd, FBIOGET_VSCREENINFO, &G.scr_var);
157         xioctl(fbfd, FBIOGET_FSCREENINFO, &G.scr_fix);
158
159         switch (G.scr_var.bits_per_pixel) {
160         case 8:
161                 fb_setpal(fbfd);
162                 break;
163
164         case 16:
165         case 24:
166         case 32:
167                 break;
168
169         default:
170                 bb_error_msg_and_die("unsupported %u bpp", (int)G.scr_var.bits_per_pixel);
171                 break;
172         }
173
174         G.red_shift   = 8 - G.scr_var.red.length;
175         G.green_shift = 8 - G.scr_var.green.length;
176         G.blue_shift  = 8 - G.scr_var.blue.length;
177         G.bytes_per_pixel = (G.scr_var.bits_per_pixel + 7) >> 3;
178
179         // map the device in memory
180         G.addr = mmap(NULL,
181                         (G.scr_var.yres_virtual ?: G.scr_var.yres) * G.scr_fix.line_length,
182                         PROT_WRITE, MAP_SHARED, fbfd, 0);
183         if (G.addr == MAP_FAILED)
184                 bb_perror_msg_and_die("mmap");
185
186         // point to the start of the visible screen
187         G.addr += G.scr_var.yoffset * G.scr_fix.line_length + G.scr_var.xoffset * G.bytes_per_pixel;
188         close(fbfd);
189 }
190
191
192 /**
193  * Return pixel value of the passed RGB color.
194  * This is performance critical fn.
195  */
196 static unsigned fb_pixel_value(unsigned r, unsigned g, unsigned b)
197 {
198         /* We assume that the r,g,b values are <= 255 */
199
200         if (G.bytes_per_pixel == 1) {
201                 r = r        & 0xe0; // 3-bit red
202                 g = (g >> 3) & 0x1c; // 3-bit green
203                 b =  b >> 6;         // 2-bit blue
204                 return r + g + b;
205         }
206         if (G.bytes_per_pixel == 2) {
207                 // ARM PL110 on Integrator/CP has RGBA5551 bit arrangement.
208                 // We want to support bit locations like that.
209                 //
210                 // First shift out unused bits
211                 r = r >> G.red_shift;
212                 g = g >> G.green_shift;
213                 b = b >> G.blue_shift;
214                 // Then shift the remaining bits to their offset
215                 return (r << G.scr_var.red.offset) +
216                         (g << G.scr_var.green.offset) +
217                         (b << G.scr_var.blue.offset);
218         }
219         // RGB 888
220         return b + (g << 8) + (r << 16);
221 }
222
223 /**
224  * Draw pixel on framebuffer
225  */
226 static void fb_write_pixel(unsigned char *addr, unsigned pixel)
227 {
228         switch (G.bytes_per_pixel) {
229         case 1:
230                 *addr = pixel;
231                 break;
232         case 2:
233                 *(uint16_t *)addr = pixel;
234                 break;
235         case 4:
236                 *(uint32_t *)addr = pixel;
237                 break;
238         default: // 24 bits per pixel
239                 addr[0] = pixel;
240                 addr[1] = pixel >> 8;
241                 addr[2] = pixel >> 16;
242         }
243 }
244
245
246 /**
247  * Draw hollow rectangle on framebuffer
248  */
249 static void fb_drawrectangle(void)
250 {
251         int cnt;
252         unsigned thispix;
253         unsigned char *ptr1, *ptr2;
254         unsigned char nred = G.nbar_colr/2;
255         unsigned char ngreen =  G.nbar_colg/2;
256         unsigned char nblue = G.nbar_colb/2;
257
258         thispix = fb_pixel_value(nred, ngreen, nblue);
259
260         // horizontal lines
261         ptr1 = G.addr + G.nbar_posy * G.scr_fix.line_length + G.nbar_posx * G.bytes_per_pixel;
262         ptr2 = G.addr + (G.nbar_posy + G.nbar_height - 1) * G.scr_fix.line_length + G.nbar_posx * G.bytes_per_pixel;
263         cnt = G.nbar_width - 1;
264         do {
265                 fb_write_pixel(ptr1, thispix);
266                 fb_write_pixel(ptr2, thispix);
267                 ptr1 += G.bytes_per_pixel;
268                 ptr2 += G.bytes_per_pixel;
269         } while (--cnt >= 0);
270
271         // vertical lines
272         ptr1 = G.addr + G.nbar_posy * G.scr_fix.line_length + G.nbar_posx * G.bytes_per_pixel;
273         ptr2 = G.addr + G.nbar_posy * G.scr_fix.line_length + (G.nbar_posx + G.nbar_width - 1) * G.bytes_per_pixel;
274         cnt = G.nbar_height - 1;
275         do {
276                 fb_write_pixel(ptr1, thispix);
277                 fb_write_pixel(ptr2, thispix);
278                 ptr1 += G.scr_fix.line_length;
279                 ptr2 += G.scr_fix.line_length;
280         } while (--cnt >= 0);
281 }
282
283
284 /**
285  * Draw filled rectangle on framebuffer
286  * \param nx1pos,ny1pos upper left position
287  * \param nx2pos,ny2pos down right position
288  * \param nred,ngreen,nblue rgb color
289  */
290 static void fb_drawfullrectangle(int nx1pos, int ny1pos, int nx2pos, int ny2pos,
291         unsigned char nred, unsigned char ngreen, unsigned char nblue)
292 {
293         int cnt1, cnt2, nypos;
294         unsigned thispix;
295         unsigned char *ptr;
296
297         thispix = fb_pixel_value(nred, ngreen, nblue);
298
299         cnt1 = ny2pos - ny1pos;
300         nypos = ny1pos;
301         do {
302                 ptr = G.addr + nypos * G.scr_fix.line_length + nx1pos * G.bytes_per_pixel;
303                 cnt2 = nx2pos - nx1pos;
304                 do {
305                         fb_write_pixel(ptr, thispix);
306                         ptr += G.bytes_per_pixel;
307                 } while (--cnt2 >= 0);
308
309                 nypos++;
310         } while (--cnt1 >= 0);
311 }
312
313
314 /**
315  * Draw a progress bar on framebuffer
316  * \param percent percentage of loading
317  */
318 static void fb_drawprogressbar(unsigned percent)
319 {
320         int left_x, top_y, pos_x;
321         unsigned width, height;
322
323         // outer box
324         left_x = G.nbar_posx;
325         top_y = G.nbar_posy;
326         width = G.nbar_width - 1;
327         height = G.nbar_height - 1;
328         if ((int)(height | width) < 0)
329                 return;
330         // NB: "width" of 1 actually makes rect with width of 2!
331         fb_drawrectangle();
332
333         // inner "empty" rectangle
334         left_x++;
335         top_y++;
336         width -= 2;
337         height -= 2;
338         if ((int)(height | width) < 0)
339                 return;
340
341         pos_x = left_x;
342         if (percent > 0) {
343                 int i, y;
344
345                 // actual progress bar
346                 pos_x += (unsigned)(width * percent) / 100;
347
348                 y = top_y;
349                 i = height;
350                 if (height == 0)
351                         height++; // divide by 0 is bad
352                 while (i >= 0) {
353                         // draw one-line thick "rectangle"
354                         // top line will have gray lvl 200, bottom one 100
355                         unsigned gray_level = 100 + (unsigned)i*100 / height;
356                         fb_drawfullrectangle(
357                                         left_x, y, pos_x, y,
358                                         gray_level, gray_level, gray_level);
359                         y++;
360                         i--;
361                 }
362         }
363
364         fb_drawfullrectangle(
365                         pos_x, top_y,
366                         left_x + width, top_y + height,
367                         G.nbar_colr, G.nbar_colg, G.nbar_colb);
368 }
369
370
371 /**
372  * Draw image from PPM file
373  */
374 static void fb_drawimage(void)
375 {
376         FILE *theme_file;
377         char *read_ptr;
378         unsigned char *pixline;
379         unsigned i, j, width, height, line_size;
380
381         if (LONE_DASH(G.image_filename)) {
382                 theme_file = stdin;
383         } else {
384                 int fd = open_zipped(G.image_filename, /*fail_if_not_compressed:*/ 0);
385                 if (fd < 0)
386                         bb_simple_perror_msg_and_die(G.image_filename);
387                 theme_file = xfdopen_for_read(fd);
388         }
389
390         /* Parse ppm header:
391          * - Magic: two characters "P6".
392          * - Whitespace (blanks, TABs, CRs, LFs).
393          * - A width, formatted as ASCII characters in decimal.
394          * - Whitespace.
395          * - A height, ASCII decimal.
396          * - Whitespace.
397          * - The maximum color value, ASCII decimal, in 0..65535
398          * - Newline or other single whitespace character.
399          *   (we support newline only)
400          * - A raster of Width * Height pixels in triplets of rgb
401          *   in pure binary by 1 or 2 bytes. (we support only 1 byte)
402          */
403 #define concat_buf bb_common_bufsiz1
404         setup_common_bufsiz();
405
406         read_ptr = concat_buf;
407         while (1) {
408                 int w, h, max_color_val;
409                 int rem = concat_buf + COMMON_BUFSIZE - read_ptr;
410                 if (rem < 2
411                  || fgets(read_ptr, rem, theme_file) == NULL
412                 ) {
413                         bb_error_msg_and_die("bad PPM file '%s'", G.image_filename);
414                 }
415                 read_ptr = strchrnul(read_ptr, '#');
416                 *read_ptr = '\0'; /* ignore #comments */
417                 if (sscanf(concat_buf, "P6 %u %u %u", &w, &h, &max_color_val) == 3
418                  && max_color_val <= 255
419                 ) {
420                         width = w; /* w is on stack, width may be in register */
421                         height = h;
422                         break;
423                 }
424         }
425
426         line_size = width*3;
427         pixline = xmalloc(line_size);
428
429         if (width > G.scr_var.xres)
430                 width = G.scr_var.xres;
431         if (height > G.scr_var.yres)
432                 height = G.scr_var.yres;
433         for (j = 0; j < height; j++) {
434                 unsigned char *pixel;
435                 unsigned char *src;
436
437                 if (fread(pixline, 1, line_size, theme_file) != line_size)
438                         bb_error_msg_and_die("bad PPM file '%s'", G.image_filename);
439                 pixel = pixline;
440                 src = G.addr + j * G.scr_fix.line_length;
441                 for (i = 0; i < width; i++) {
442                         unsigned thispix = fb_pixel_value(pixel[0], pixel[1], pixel[2]);
443                         fb_write_pixel(src, thispix);
444                         src += G.bytes_per_pixel;
445                         pixel += 3;
446                 }
447         }
448         free(pixline);
449         fclose(theme_file);
450 }
451
452
453 /**
454  * Parse configuration file
455  * \param *cfg_filename name of the configuration file
456  */
457 static void init(const char *cfg_filename)
458 {
459         static const char param_names[] ALIGN1 =
460                 "BAR_WIDTH\0" "BAR_HEIGHT\0"
461                 "BAR_LEFT\0" "BAR_TOP\0"
462                 "BAR_R\0" "BAR_G\0" "BAR_B\0"
463 #if DEBUG
464                 "DEBUG\0"
465 #endif
466                 ;
467         char *token[2];
468         parser_t *parser = config_open2(cfg_filename, xfopen_stdin);
469         while (config_read(parser, token, 2, 2, "#=",
470                                 (PARSE_NORMAL | PARSE_MIN_DIE) & ~(PARSE_TRIM | PARSE_COLLAPSE))) {
471                 unsigned val = xatoi_positive(token[1]);
472                 int i = index_in_strings(param_names, token[0]);
473                 if (i < 0)
474                         bb_error_msg_and_die("syntax error: %s", token[0]);
475                 if (i >= 0 && i < 7)
476                         G.ns[i] = val;
477 #if DEBUG
478                 if (i == 7) {
479                         G.bdebug_messages = val;
480                         if (G.bdebug_messages)
481                                 G.logfile_fd = xfopen_for_write("/tmp/fbsplash.log");
482                 }
483 #endif
484         }
485         config_close(parser);
486 }
487
488
489 int fbsplash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
490 int fbsplash_main(int argc UNUSED_PARAM, char **argv)
491 {
492         const char *fb_device, *cfg_filename, *fifo_filename;
493         FILE *fp = fp; // for compiler
494         char *num_buf;
495         unsigned num;
496         bool bCursorOff;
497
498         INIT_G();
499
500         // parse command line options
501         fb_device = "/dev/fb0";
502         cfg_filename = NULL;
503         fifo_filename = NULL;
504         bCursorOff = 1 & getopt32(argv, "cs:d:i:f:",
505                         &G.image_filename, &fb_device, &cfg_filename, &fifo_filename);
506
507         // parse configuration file
508         if (cfg_filename)
509                 init(cfg_filename);
510
511         // We must have -s IMG
512         if (!G.image_filename)
513                 bb_show_usage();
514
515         fb_open(fb_device);
516
517         if (fifo_filename && bCursorOff) {
518                 // hide cursor (BEFORE any fb ops)
519                 full_write(STDOUT_FILENO, ESC"[?25l", 6);
520         }
521
522         fb_drawimage();
523
524         if (!fifo_filename)
525                 return EXIT_SUCCESS;
526
527         fp = xfopen_stdin(fifo_filename);
528         if (fp != stdin) {
529                 // For named pipes, we want to support this:
530                 //  mkfifo cmd_pipe
531                 //  fbsplash -f cmd_pipe .... &
532                 //  ...
533                 //  echo 33 >cmd_pipe
534                 //  ...
535                 //  echo 66 >cmd_pipe
536                 // This means that we don't want fbsplash to get EOF
537                 // when last writer closes input end.
538                 // The simplest way is to open fifo for writing too
539                 // and become an additional writer :)
540                 open(fifo_filename, O_WRONLY); // errors are ignored
541         }
542
543         fb_drawprogressbar(0);
544         // Block on read, waiting for some input.
545         // Use of <stdio.h> style I/O allows to correctly
546         // handle a case when we have many buffered lines
547         // already in the pipe
548         while ((num_buf = xmalloc_fgetline(fp)) != NULL) {
549                 if (is_prefixed_with(num_buf, "exit")) {
550                         DEBUG_MESSAGE("exit");
551                         break;
552                 }
553                 num = atoi(num_buf);
554                 if (isdigit(num_buf[0]) && (num <= 100)) {
555 #if DEBUG
556                         DEBUG_MESSAGE(itoa(num));
557 #endif
558                         fb_drawprogressbar(num);
559                 }
560                 free(num_buf);
561         }
562
563         if (bCursorOff) // restore cursor
564                 full_write(STDOUT_FILENO, ESC"[?25h", 6);
565
566         return EXIT_SUCCESS;
567 }