http://www.jwz.org/xscreensaver/xscreensaver-5.13.tar.gz
[xscreensaver] / hacks / xanalogtv.c
1 /* xanalogtv, Copyright (c) 2003 Trevor Blackwell <tlb@tlb.org>
2  *
3  * Permission to use, copy, modify, distribute, and sell this software and its
4  * documentation for any purpose is hereby granted without fee, provided that
5  * the above copyright notice appear in all copies and that both that
6  * copyright notice and this permission notice appear in supporting
7  * documentation.  No representations are made about the suitability of this
8  * software for any purpose.  It is provided "as is" without express or 
9  * implied warranty.
10  *
11  *
12  * Simulate test patterns on an analog TV. Concept similar to xteevee
13  * in this distribution, but a totally different implementation based
14  * on the simulation of an analog TV set in utils/analogtv.c. Much
15  * more realistic, but needs more video card bandwidth.
16  *
17  * It flips around through simulated channels 2 through 13. Some show
18  * pictures from your images directory, some show color bars, and some
19  * just have static. Some channels receive two stations simultaneously
20  * so you see a ghostly, misaligned image.
21  *
22  * It's easy to add some test patterns by compiling in an XPM, but I
23  * can't find any that are clearly freely redistributable.
24  *
25  */
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif /* HAVE_CONFIG_H */
30
31 #include <math.h>
32
33 #ifdef HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36
37 #ifndef HAVE_COCOA
38 # include <X11/Intrinsic.h> /* for XtDatabase in hack_resources() */
39 #endif
40
41 #include "screenhack.h"
42 #include "xpm-pixmap.h"
43 #include "analogtv.h"
44
45 #include "images/logo-50.xpm"
46
47 /* #define DEBUG 1 */
48 /* #define USE_TEST_PATTERNS */
49
50 #define countof(x) (sizeof((x))/sizeof((*x)))
51
52 enum {
53   N_CHANNELS=12, /* Channels 2 through 13 on VHF */
54   MAX_MULTICHAN=2,
55   MAX_STATIONS=6
56 }; 
57
58 typedef struct chansetting_s {
59
60   analogtv_reception recs[MAX_MULTICHAN];
61   double noise_level;
62   Bool image_loaded_p;
63 /*  char *filename;     was only used for diagnostics */
64   int dur;
65 } chansetting;
66
67
68 struct state {
69   Display *dpy;
70   Window window;
71   analogtv *tv;
72   analogtv_font ugly_font;
73   struct timeval basetime;
74
75   int n_stations;
76   analogtv_input *stations[MAX_STATIONS];
77   Bool image_loading_p;
78
79   int curinputi;
80   int change_ticks;
81   chansetting chansettings[N_CHANNELS];
82   chansetting *cs;
83
84   int change_now;
85
86 };
87
88
89 static void
90 update_smpte_colorbars(analogtv_input *input)
91 {
92   struct state *st = (struct state *) input->client_data;
93   int col;
94   int xpos, ypos;
95   int black_ntsc[4];
96
97   /* 
98      SMPTE is the society of motion picture and television engineers, and
99      these are the standard color bars in the US. Following the partial spec
100      at http://broadcastengineering.com/ar/broadcasting_inside_color_bars/
101      These are luma, chroma, and phase numbers for each of the 7 bars.
102   */
103   double top_cb_table[7][3]={
104     {75, 0, 0.0},    /* gray */
105     {69, 31, 167.0}, /* yellow */
106     {56, 44, 283.5}, /* cyan */
107     {48, 41, 240.5}, /* green */
108     {36, 41, 60.5},  /* magenta */
109     {28, 44, 103.5}, /* red */
110     {15, 31, 347.0}  /* blue */
111   };
112   double mid_cb_table[7][3]={
113     {15, 31, 347.0}, /* blue */
114     {7, 0, 0},       /* black */
115     {36, 41, 60.5},  /* magenta */
116     {7, 0, 0},       /* black */
117     {56, 44, 283.5}, /* cyan */
118     {7, 0, 0},       /* black */
119     {75, 0, 0.0}     /* gray */
120   };
121
122   analogtv_lcp_to_ntsc(0.0, 0.0, 0.0, black_ntsc);
123
124   analogtv_setup_sync(input, 1, 0);
125   analogtv_setup_teletext(input);
126
127   for (col=0; col<7; col++) {
128     analogtv_draw_solid_rel_lcp(input, col*(1.0/7.0), (col+1)*(1.0/7.0), 0.00, 0.68, 
129                                 top_cb_table[col][0], 
130                                 top_cb_table[col][1], top_cb_table[col][2]);
131     
132     analogtv_draw_solid_rel_lcp(input, col*(1.0/7.0), (col+1)*(1.0/7.0), 0.68, 0.75, 
133                                 mid_cb_table[col][0], 
134                                 mid_cb_table[col][1], mid_cb_table[col][2]);
135   }
136
137   analogtv_draw_solid_rel_lcp(input, 0.0, 1.0/6.0,
138                               0.75, 1.00, 7, 40, 303);   /* -I */
139   analogtv_draw_solid_rel_lcp(input, 1.0/6.0, 2.0/6.0,
140                               0.75, 1.00, 100, 0, 0);    /* white */
141   analogtv_draw_solid_rel_lcp(input, 2.0/6.0, 3.0/6.0,
142                               0.75, 1.00, 7, 40, 33);    /* +Q */
143   analogtv_draw_solid_rel_lcp(input, 3.0/6.0, 4.0/6.0,
144                               0.75, 1.00, 7, 0, 0);      /* black */
145   analogtv_draw_solid_rel_lcp(input, 12.0/18.0, 13.0/18.0,
146                               0.75, 1.00, 3, 0, 0);      /* black -4 */
147   analogtv_draw_solid_rel_lcp(input, 13.0/18.0, 14.0/18.0,
148                               0.75, 1.00, 7, 0, 0);      /* black */
149   analogtv_draw_solid_rel_lcp(input, 14.0/18.0, 15.0/18.0,
150                               0.75, 1.00, 11, 0, 0);     /* black +4 */
151   analogtv_draw_solid_rel_lcp(input, 5.0/6.0, 6.0/6.0,
152                               0.75, 1.00, 7, 0, 0);      /* black */
153
154
155   ypos=ANALOGTV_V/5;
156   xpos=ANALOGTV_VIS_START + ANALOGTV_VIS_LEN/2;
157
158   {
159     char localname[256];
160     if (gethostname (localname, sizeof (localname))==0) {
161       localname[sizeof(localname)-1]=0; /* "The returned name is null-
162                                            terminated unless insufficient 
163                                            space is provided" */
164       localname[24]=0; /* limit length */
165
166       analogtv_draw_string_centered(input, &st->ugly_font, localname,
167                                     xpos, ypos, black_ntsc);
168     }
169   }
170   ypos += st->ugly_font.char_h*5/2;
171
172   analogtv_draw_xpm(st->tv, input,
173                     logo_50_xpm, xpos - 100, ypos);
174
175   ypos += 58;
176
177 #if 0
178   analogtv_draw_string_centered(input, &st->ugly_font,
179                                 "Please Stand By", xpos, ypos);
180   ypos += st->ugly_font.char_h*4;
181 #endif
182
183   {
184     char timestamp[256];
185     time_t t = time ((time_t *) 0);
186     struct tm *tm = localtime (&t);
187
188     /* Y2K: It is OK for this to use a 2-digit year because it's simulating a
189        TV display and is purely decorative. */
190     strftime(timestamp, sizeof(timestamp)-1, "%y.%m.%d %H:%M:%S ", tm);
191     analogtv_draw_string_centered(input, &st->ugly_font, timestamp,
192                                   xpos, ypos, black_ntsc);
193   }
194
195   
196   input->next_update_time += 1.0;
197 }
198
199 #if 0
200 static void
201 draw_color_square(analogtv_input *input)
202 {
203   double xs,ys;
204
205   analogtv_draw_solid_rel_lcp(input, 0.0, 1.0, 0.0, 1.0,
206                               30.0, 0.0, 0.0);
207   
208   for (xs=0.0; xs<0.9999; xs+=1.0/15.0) {
209     analogtv_draw_solid_rel_lcp(input, xs, xs, 0.0, 1.0,
210                                 100.0, 0.0, 0.0);
211   }
212
213   for (ys=0.0; ys<0.9999; ys+=1.0/11.0) {
214     analogtv_draw_solid_rel_lcp(input, 0.0, 1.0, ys, ys,
215                                 100.0, 0.0, 0.0);
216   }
217
218   for (ys=0.0; ys<0.9999; ys+=0.01) {
219     
220     analogtv_draw_solid_rel_lcp(input, 0.0/15, 1.0/15, ys, ys+0.01,
221                                 40.0, 45.0, 103.5*(1.0-ys) + 347.0*ys);
222
223     analogtv_draw_solid_rel_lcp(input, 14.0/15, 15.0/15, ys, ys+0.01,
224                                 40.0, 45.0, 103.5*(ys) + 347.0*(1.0-ys));
225   }
226
227   for (ys=0.0; ys<0.9999; ys+=0.02) {
228     analogtv_draw_solid_rel_lcp(input, 1.0/15, 2.0/15, ys*2.0/11.0+1.0/11.0, 
229                                 (ys+0.01)*2.0/11.0+1.0/11.0,
230                                 100.0*(1.0-ys), 0.0, 0.0);
231   }
232
233
234 }
235 #endif
236
237 static const char *xanalogtv_defaults [] = {
238   ".background:         black",
239   ".foreground:         white",
240   "*delay:              5",
241   "*grabDesktopImages:  False",   /* HAVE_COCOA */
242   "*chooseRandomImages: True",    /* HAVE_COCOA */
243   ANALOGTV_DEFAULTS
244   0,
245 };
246
247 static XrmOptionDescRec xanalogtv_options [] = {
248   { "-delay",           ".delay",               XrmoptionSepArg, 0 },
249   ANALOGTV_OPTIONS
250   { 0, 0, 0, 0 }
251 };
252
253
254 #ifdef USE_TEST_PATTERNS
255
256 #include "images/earth.xpm"
257
258 char **test_patterns[] = {
259   earth_xpm,
260 };
261
262 #endif
263
264
265 static int
266 getticks(struct state *st)
267 {
268   struct timeval tv;
269   gettimeofday(&tv,NULL);
270   return ((tv.tv_sec - st->basetime.tv_sec)*1000 +
271           (tv.tv_usec - st->basetime.tv_usec)/1000);
272 }
273
274
275 /* The first time we grab an image, do it the default way.
276    The second and subsequent times, add "-no-desktop" to the command.
277    That way we don't have to watch the window un-map 5+ times in a row.
278    Also, we end up with the desktop on only one channel, and pictures
279    on all the others (or colorbars, if no imageDirectory is set.)
280  */
281 static void
282 hack_resources (Display *dpy)
283 {
284 #ifndef HAVE_COCOA
285   static int count = -1;
286   count++;
287
288   if (count == 0)
289     return;
290   else if (count == 1)
291     {
292       XrmDatabase db = XtDatabase (dpy);
293       char *res = "desktopGrabber";
294       char *val = get_string_resource (dpy, res, "DesktopGrabber");
295       char buf1[255];
296       char buf2[255];
297       XrmValue value;
298       sprintf (buf1, "%.100s.%.100s", progname, res);
299       sprintf (buf2, "%.200s -no-desktop", val);
300       value.addr = buf2;
301       value.size = strlen(buf2);
302       XrmPutResource (&db, buf1, "String", &value);
303     }
304 #endif /* HAVE_COCOA */
305 }
306
307
308 static void analogtv_load_random_image(struct state *);
309
310
311 static void image_loaded_cb (Screen *screen, Window window, Drawable pixmap,
312                              const char *name, XRectangle *geometry,
313                              void *closure)
314 {
315   /* When an image has just been loaded, store it into the first available
316      channel.  If there are other unloaded channels, then start loading
317      another image.
318   */
319   struct state *st = (struct state *) closure;
320   int i;
321   int this = -1;
322   int next = -1;
323
324   if (!st->image_loading_p) abort();  /* only one at a time... */
325   st->image_loading_p = False;
326
327   for (i = 0; i < MAX_STATIONS; i++) {
328     if (! st->chansettings[i].image_loaded_p) {
329       if (this == -1) this = i;
330       else if (next == -1) next = i;
331     }
332   }
333   if (this == -1) abort();  /* no unloaded stations? */
334
335   /* Load this image into the next channel. */
336   {
337     analogtv_input *input = st->stations[this];
338     int width=ANALOGTV_PIC_LEN;
339     int height=width*3/4;
340     XImage *image = XGetImage (st->dpy, pixmap, 0, 0,
341                                width, height, ~0L, ZPixmap);
342     XFreePixmap(st->dpy, pixmap);
343
344     analogtv_setup_sync(input, 1, (random()%20)==0);
345     analogtv_load_ximage(st->tv, input, image);
346     if (image) XDestroyImage(image);
347     st->chansettings[this].image_loaded_p = True;
348 #if 0
349     if (name) {
350       const char *s = strrchr (name, '/');
351       if (s) s++;
352       else s = name;
353       st->chansettings[this].filename = strdup (s);
354     }
355     fprintf(stderr, "%s: loaded channel %d, %s\n", progname, this, 
356             st->chansettings[this].filename);
357 #endif
358   }
359
360   /* If there are still unloaded stations, fire off another loader. */
361   if (next != -1)
362     analogtv_load_random_image (st);
363 }
364
365
366 /* Queues a single image for loading.  Only load one at a time.
367    The image is done loading when st->img_loader is null and
368    it->loaded_image is a pixmap.
369  */
370 static void
371 analogtv_load_random_image(struct state *st)
372 {
373   int width=ANALOGTV_PIC_LEN;
374   int height=width*3/4;
375   Pixmap p;
376
377   if (st->image_loading_p)  /* a load is already in progress */
378     return;
379
380   st->image_loading_p = True;
381   p = XCreatePixmap(st->dpy, st->window, width, height, st->tv->visdepth);
382   hack_resources(st->dpy);
383   load_image_async (st->tv->xgwa.screen, st->window, p, image_loaded_cb, st);
384 }
385
386
387 #if 0
388 static int
389 analogtv_load_xpm(analogtv *it, analogtv_input *input, char **xpm)
390 {
391   Pixmap pixmap;
392   XImage *image;
393   int width,height;
394   int rc;
395
396   pixmap=xpm_data_to_pixmap (it->dpy, it->window, xpm,
397                              &width, &height, NULL);
398   image = XGetImage(it->dpy, pixmap, 0, 0, width, height, ~0L, ZPixmap);
399   XFreePixmap(it->dpy, pixmap);
400   rc=analogtv_load_ximage(it, input, image);
401   if (image) XDestroyImage(image);
402   return rc;
403 }
404 #endif
405
406
407 static void add_stations(struct state *st)
408 {
409   while (st->n_stations < MAX_STATIONS) {
410     analogtv_input *input=analogtv_input_allocate();
411     st->stations[st->n_stations++]=input;
412     input->client_data = st;
413   }
414 }
415
416
417 static void load_station_images(struct state *st)
418 {
419   int i;
420   for (i = 0; i < MAX_STATIONS; i++) {
421     analogtv_input *input = st->stations[i];
422
423     st->chansettings[i].image_loaded_p = True;
424     if (i == 0) {   /* station 0 is always colorbars */
425       input->updater = update_smpte_colorbars;
426       input->do_teletext=1;
427     }
428 #ifdef USE_TEST_PATTERNS
429     else if (random()%5==0) {
430       j=random()%countof(test_patterns);
431       analogtv_setup_sync(input);
432       analogtv_load_xpm(tv, input, test_patterns[j]);
433       analogtv_setup_teletext(input);
434     }
435 #endif
436     else {
437       analogtv_load_random_image(st);
438       input->do_teletext=1;
439       st->chansettings[i].image_loaded_p = False;
440     }
441   }
442 }
443
444
445 static void *
446 xanalogtv_init (Display *dpy, Window window)
447 {
448   struct state *st = (struct state *) calloc (1, sizeof(*st));
449   int i;
450   int last_station=42;
451   int delay = get_integer_resource(dpy, "delay", "Integer");
452   if (delay < 1) delay = 1;
453
454   analogtv_make_font(dpy, window, &st->ugly_font, 7, 10, "6x10");
455   
456   st->dpy = dpy;
457   st->window = window;
458   st->tv=analogtv_allocate(dpy, window);
459
460   add_stations(st);
461
462   analogtv_set_defaults(st->tv, "");
463   st->tv->need_clear=1;
464
465   if (random()%4==0) {
466     st->tv->tint_control += pow(frand(2.0)-1.0, 7) * 180.0;
467   }
468   if (1) {
469     st->tv->color_control += frand(0.3);
470   }
471
472   for (i=0; i<N_CHANNELS; i++) {
473     memset(&st->chansettings[i], 0, sizeof(chansetting));
474
475     st->chansettings[i].noise_level = 0.06;
476     st->chansettings[i].dur = 1000*delay;
477
478     if (random()%6==0) {
479       st->chansettings[i].dur=600;
480     }
481     else {
482       int stati;
483       for (stati=0; stati<MAX_MULTICHAN; stati++) {
484         analogtv_reception *rec=&st->chansettings[i].recs[stati];
485         int station;
486         while (1) {
487           station=random()%st->n_stations;
488           if (station!=last_station) break;
489           if ((random()%10)==0) break;
490         }
491         last_station=station;
492         rec->input = st->stations[station];
493         rec->level = pow(frand(1.0), 3.0) * 2.0 + 0.05;
494         rec->ofs=random()%ANALOGTV_SIGNAL_LEN;
495         if (random()%3) {
496           rec->multipath = frand(1.0);
497         } else {
498           rec->multipath=0.0;
499         }
500         if (stati) {
501           /* We only set a frequency error for ghosting stations,
502              because it doesn't matter otherwise */
503           rec->freqerr = (frand(2.0)-1.0) * 3.0;
504         }
505
506         if (rec->level > 0.3) break;
507         if (random()%4) break;
508       }
509     }
510   }
511
512   gettimeofday(&st->basetime,NULL);
513
514   st->curinputi=0;
515   st->cs = &st->chansettings[st->curinputi];
516   st->change_ticks = st->cs->dur + 1500;
517
518   st->tv->powerup=0.0;
519
520   load_station_images(st);
521
522   return st;
523 }
524
525 static unsigned long
526 xanalogtv_draw (Display *dpy, Window window, void *closure)
527 {
528   struct state *st = (struct state *) closure;
529   int i;
530
531   int curticks=getticks(st);
532   double curtime=curticks*0.001;
533
534   if (st->change_now || 
535       (curticks >= st->change_ticks && st->tv->powerup > 10.0)) {
536     st->change_now = 0;
537     st->curinputi=(st->curinputi+1)%N_CHANNELS;
538     st->cs = &st->chansettings[st->curinputi];
539 #if 0
540     fprintf (stderr, "%s: channel %d, %s\n", progname, st->curinputi,
541              st->cs->filename);
542 #endif
543     st->change_ticks = curticks + st->cs->dur;
544     /* Set channel change noise flag */
545     st->tv->channel_change_cycles=200000;
546   }
547
548   for (i=0; i<MAX_MULTICHAN; i++) {
549     analogtv_reception *rec = &st->cs->recs[i];
550     analogtv_input *inp=rec->input;
551     if (!inp) continue;
552
553     if (inp->updater) {
554       inp->next_update_time = curtime;
555       (inp->updater)(inp);
556     }
557     rec->ofs += rec->freqerr;
558   }
559
560   st->tv->powerup=curtime;
561
562   analogtv_init_signal(st->tv, st->cs->noise_level);
563   for (i=0; i<MAX_MULTICHAN; i++) {
564     analogtv_reception *rec = &st->cs->recs[i];
565     analogtv_input *inp=rec->input;
566     if (!inp) continue;
567
568     analogtv_reception_update(rec);
569     analogtv_add_signal(st->tv, rec);
570   }
571   analogtv_draw(st->tv);
572   return 10000;
573 }
574
575 static void
576 xanalogtv_reshape (Display *dpy, Window window, void *closure, 
577                  unsigned int w, unsigned int h)
578 {
579   struct state *st = (struct state *) closure;
580   analogtv_reconfigure(st->tv);
581 }
582
583 static Bool
584 xanalogtv_event (Display *dpy, Window window, void *closure, XEvent *event)
585 {
586   struct state *st = (struct state *) closure;
587
588   if (event->type == ButtonPress)
589     {
590       st->change_now = 1;
591       return True;
592     }
593   else if (event->type == KeyPress)
594     {
595       KeySym keysym;
596       char c = 0;
597       XLookupString (&event->xkey, &c, 1, &keysym, 0);
598       if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
599         {
600           st->change_now = 1;
601           return True;
602         }
603     }
604
605   return False;
606 }
607
608 static void
609 xanalogtv_free (Display *dpy, Window window, void *closure)
610 {
611   struct state *st = (struct state *) closure;
612   analogtv_release(st->tv);
613   free (st);
614 }
615
616
617 XSCREENSAVER_MODULE ("XAnalogTV", xanalogtv)