File: gdith.c

package info (click to toggle)
ucbmpeg 1r2-6
  • links: PTS
  • area: non-free
  • in suites: hamm, potato, slink
  • size: 9,504 kB
  • ctags: 7,643
  • sloc: ansic: 79,920; tcl: 2,985; perl: 313; asm: 284; makefile: 269; csh: 13
file content (1112 lines) | stat: -rw-r--r-- 26,401 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
/* 
 * gdith.c --
 *
 *      Procedures dealing with grey-scale and mono dithering, 
 *      as well as X Windows set up procedures.
 *
 */

/*
 * Copyright (c) 1995 The Regents of the University of California.
 * All rights reserved.
 * 
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose, without fee, and without written agreement is
 * hereby granted, provided that the above copyright notice and the following
 * two paragraphs appear in all copies of this software.
 * 
 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
 * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 */

#include <math.h>
#include "video.h"
#include "proto.h"
#include "dither.h"
#ifndef NOCONTROLS
#include "ctrlbar.h"
#endif
#include <sys/time.h>

#ifdef __STDC__
#include <stdlib.h>
#include <string.h>
#endif

/* Range values for lum, cr, cb. */
int LUM_RANGE;
int CR_RANGE;
int CB_RANGE;

/* Array that remaps color numbers to actual pixel values used by X server. */

unsigned char pixel[256];
unsigned long wpixel[256];

/* Arrays holding quantized value ranged for lum, cr, and cb. */

int *lum_values;
int *cr_values;
int *cb_values;

/* Declaration of global variable containing dither type. */

extern int ditherType;
extern int matched_depth;

/* Structures used by the X server. */

Display *display = NULL;

static XImage *ximage = NULL;
static Colormap cmap;
#ifndef NOCONTROLS 
Window window = 0;
#else
static Window window;
#endif
static GC gc;

/* Frame Rate Info */
extern int framerate;

/* Video rates table */
/* Cheat on Vid rates, round to 30, and use 30 if illegal value 
   Except for 9, where Xing means 15, and given their popularity, we'll
   be nice and do it */
static int VidRateNum[16]={30, 24, 24, 25, 30, 30, 50, 60, 
                         60, 15, 30, 30, 30, 30, 30, 30};

/* Luminance and chrominance lookup tables */
static double *L_tab, *Cr_r_tab, *Cr_g_tab, *Cb_g_tab, *Cb_b_tab;


/*
 *--------------------------------------------------------------
 *
 * InitColor --
 *
 *	Initialize lum, cr, and cb quantized range value arrays.
 *      Also initializes the lookup tables for the possible
 *      values of lum, cr, and cb.
 *    Color values from ITU-R BT.470-2 System B, G and SMPTE 170M
 *    see InitColorDither in 16bits.c for more
 *
 * Results: 
 *      None.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */

void
InitColor()
{
  int i, CR, CB;

  L_tab    = (double *)malloc(LUM_RANGE*sizeof(double)); 
  Cr_r_tab = (double *)malloc(CR_RANGE*sizeof(double));
  Cr_g_tab = (double *)malloc(CR_RANGE*sizeof(double));
  Cb_g_tab = (double *)malloc(CB_RANGE*sizeof(double));
  Cb_b_tab = (double *)malloc(CB_RANGE*sizeof(double));

  if (L_tab == NULL    || Cr_r_tab == NULL ||
      Cr_g_tab == NULL || Cb_g_tab == NULL ||
      Cb_b_tab == NULL) {
    fprintf(stderr, "Could not alloc memory in InitColor\n");
    exit(1);
  }

  for (i=0; i<LUM_RANGE; i++) {
    lum_values[i]  = ((i * 256) / (LUM_RANGE)) + (256/(LUM_RANGE*2));
    L_tab[i] = lum_values[i];
    if (gammaCorrectFlag) {
      L_tab[i] = GAMMA_CORRECTION(L_tab[i]);
    }
  }
  
  for (i=0; i<CR_RANGE; i++) {
    register double tmp;
    if (chromaCorrectFlag) {
      tmp = ((i * 256) / (CR_RANGE)) + (256/(CR_RANGE*2));
      Cr_r_tab[i] = (int) (0.419/0.299) * CHROMA_CORRECTION128D(tmp - 128.0);
      Cr_g_tab[i] = (int) -(0.299/0.419) * CHROMA_CORRECTION128D(tmp - 128.0);
      cr_values[i] = CHROMA_CORRECTION256(tmp);
    } else {
      tmp = ((i * 256) / (CR_RANGE)) + (256/(CR_RANGE*2));
      Cr_r_tab[i] = (int)  (0.419/0.299) * (tmp - 128.0);
      Cr_g_tab[i] = (int) -(0.299/0.419) * (tmp - 128.0);
      cr_values[i] = (int) tmp;
    }
  }

  for (i=0; i<CB_RANGE; i++) {
    register double tmp;
    if (chromaCorrectFlag) {
      tmp = ((i * 256) / (CB_RANGE)) + (256/(CB_RANGE*2));
      Cb_g_tab[i] = (int) -(0.114/0.331) * CHROMA_CORRECTION128D(tmp - 128.0);
      Cb_b_tab[i] = (int)  (0.587/0.331) * CHROMA_CORRECTION128D(tmp - 128.0);
      cb_values[i] = CHROMA_CORRECTION256(tmp);
    } else {
      tmp = ((i * 256) / (CB_RANGE)) + (256/(CB_RANGE*2));
      Cb_g_tab[i] = (int) -(0.114/0.331) * (tmp - 128.0);
      Cb_b_tab[i] = (int)  (0.587/0.331) * (tmp - 128.0);
      cb_values[i] = (int) tmp;
    }
  }

}


/*
 *--------------------------------------------------------------
 *
 * ConvertColor --
 *
 *	Given a l, cr, cb tuple, converts it to r,g,b.
 *
 * Results:
 *	r,g,b values returned in pointers passed as parameters.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */

static void
ConvertColor(l, cr, cb, r, g, b)
     unsigned int l, cr, cb;
     unsigned char *r, *g, *b;
{
  double fl, fcr, fcb, fr, fg, fb;

/*
 * Old method w/o lookup table
 *
 * fl = 1.164*(((double) l)-16.0);
 * fcr =  ((double) cr) - 128.0;
 * fcb =  ((double) cb) - 128.0;
 *
 * fr = fl + (1.366 * fcr);
 * fg = fl - (0.700 * fcr) - (0.334 * fcb);
 * fb = fl + (1.732 * fcb);
 */

  fl = L_tab[l];

  fr = fl + Cr_r_tab[cr];
  fg = fl + Cr_g_tab[cr] + Cb_g_tab[cb];
  fb = fl + Cb_b_tab[cb];

  if (fr < 0.0) fr = 0.0;
  else if (fr > 255.0) fr = 255.0;

  if (fg < 0.0) fg = 0.0;
  else if (fg > 255.0) fg = 255.0;

  if (fb < 0.0) fb = 0.0;
  else if (fb > 255.0) fb = 255.0;

  *r = (unsigned char) fr;
  *g = (unsigned char) fg;
  *b = (unsigned char) fb;

}

#ifdef SH_MEM

int gXErrorFlag = 0;

int HandleXError(dpy, event)
     Display *dpy;
     XErrorEvent *event;
{
  gXErrorFlag = 1;

  return 0;
}

int HandleXError();

void InstallXErrorHandler()
{
  XSetErrorHandler(HandleXError);
  XFlush(display);
}

void DeInstallXErrorHandler()
{
  XSetErrorHandler(NULL);
  XFlush(display);
}
#endif


/*
 *--------------------------------------------------------------
 *
 * ResizeDisplay --
 *
 *	Resizes display window.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */

void ResizeDisplay(w, h)
     unsigned int w, h;
{

  if (ditherType == NO_DITHER || ditherType == PPM_DITHER) return;

  XResizeWindow(display, window, w, h);
  XFlush(display);
}


/*
 *--------------------------------------------------------------
 *
 * MakeWindow --
 *
 *	Create X Window
 *
 * Results:
 *	Read the code.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */

#ifdef SH_MEM
int CompletionType = -1;
#endif

static int
MakeWindow(name) 
char *name;
{
  
  XSizeHints hint;
  unsigned int fg, bg;
  char *hello = "MPEG Play";
  int screen;
  Window CreateFullColorWindow();
  XVisualInfo vinfo;
  
  if ((ditherType == NO_DITHER) || (ditherType == PPM_DITHER)) return;

  display = XOpenDisplay(name);
  if (display == NULL) {
    fprintf(stderr, "Cannot open display\n");
    exit(-2);
  }

#ifdef SH_MEM
  if(shmemFlag)
    CompletionType = XShmGetEventBase(display) + ShmCompletion;
#endif

  screen = DefaultScreen (display);
  
  /* Fill in hint structure */

  hint.x = 200;
  hint.y = 300;
  hint.width = 150;
  hint.height = 150;
  hint.flags = PPosition | PSize;
  
  /* Get some colors */
  
  bg = WhitePixel (display, screen);
  fg = BlackPixel (display, screen);
  
  /* Make the window */
  
  if (ditherType == FULL_COLOR_DITHER || ditherType == FULL_COLOR2_DITHER) {
    window = CreateFullColorWindow (display, hint.x, hint.y, hint.width, hint.height);
    if (window == 0) {
      fprintf (stderr, "-color option only valid on full color display\n");
      exit (-1);
    }
  } else {
    if (((XMatchVisualInfo (display, screen, 24, TrueColor,   &vinfo) != 0) ||
	 (XMatchVisualInfo (display, screen, 24, DirectColor, &vinfo) != 0)) &&
	 (!quietFlag)) {
      printf("\nOn 24 bit displays:  use -dither color to get full color\n\t\tordered dither is the default.\n");
    }
    if (ditherType == MONO_DITHER || ditherType == MONO_THRESHOLD) {
      window = XCreateSimpleWindow (display,
				    DefaultRootWindow (display),
				    hint.x, hint.y,
				    hint.width, hint.height,
				    4, fg, bg);
      matched_depth = 1;
    } else {
      Visual *vis;
      XSetWindowAttributes attrib;
      unsigned long attrib_flags=0;
      
      if (!XMatchVisualInfo (display, screen, matched_depth = 8, PseudoColor, 
			     &vinfo)) {
	if (ditherType != GRAY_DITHER && ditherType != GRAY2_DITHER &&
	    ditherType != GRAY256_DITHER && ditherType != GRAY2562_DITHER) {
	  fprintf(stderr, "specified dither requires 8 bit display\n");
	  return 0;
	} else if (!XMatchVisualInfo(display, screen, matched_depth = 32,
			GrayScale, &vinfo) &&
	           !XMatchVisualInfo(display, screen, matched_depth = 24,
			GrayScale, &vinfo) &&
	           !XMatchVisualInfo(display, screen, matched_depth = 16,
			GrayScale, &vinfo) &&
	           !XMatchVisualInfo(display, screen, matched_depth = 8,
			GrayScale, &vinfo) &&
	           !XMatchVisualInfo(display, screen, matched_depth = 32,
			TrueColor, &vinfo) &&
	           !XMatchVisualInfo(display, screen, matched_depth = 24,
			TrueColor, &vinfo) &&
	           !XMatchVisualInfo(display, screen, matched_depth = 16,
			TrueColor, &vinfo)) {
	  fprintf(stderr, "- -dither gray requires at least 8 bit display\n");
	  exit(-1);
	}
      }
      
      vis=vinfo.visual;
      if (XDefaultDepthOfScreen(XDefaultScreenOfDisplay(display)) != 8) {
	attrib_flags |= CWColormap;
	attrib.colormap = XCreateColormap(display, DefaultRootWindow(display),
					  vis, AllocNone);
	owncmFlag = TRUE; 
      }
      
      attrib.background_pixel = bg;
      attrib.border_pixel = fg;
      attrib.backing_store = NotUseful;
      attrib.save_under = False;
      attrib.background_pixel = bg;
      attrib.border_pixel = bg;
      attrib_flags |= CWBackPixel | CWBorderPixel | CWBackingStore | CWSaveUnder;
      window = XCreateWindow (display,
			      DefaultRootWindow (display),
			      hint.x, hint.y,
			      hint.width, hint.height, 4,
			      matched_depth, InputOutput, vis,
			      attrib_flags, &attrib);
    }}
  
  XSelectInput(display, window, StructureNotifyMask);
  
  /* Tell other applications about this window */
  
  XSetStandardProperties (display, window, hello, hello, None, NULL, 0, &hint);
  
  /* Map window. */
  
  XMapWindow(display, window);
  
  /* Wait for map. */
  while(1) {
    XEvent	xev;
    
    XNextEvent(display, &xev);
    if(xev.type == MapNotify && xev.xmap.event == window)
      break;
  }
  
#ifndef NOCONTROLS
  XSelectInput(display, window, ExposureMask | ButtonPressMask );
#else
  XSelectInput(display, window, NoEventMask);
#endif

  return TRUE;
}
  

/*
 *--------------------------------------------------------------
 *
 * InitDisplay --
 *
 *	Initialized display, sets up colormap, etc.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */

void InitDisplay(name)
char *name;
{

  int ncolors = LUM_RANGE*CB_RANGE*CR_RANGE;
  XColor xcolor;
  int i, lum_num, cr_num, cb_num;
  unsigned char r, g, b;
  Colormap dcmap;

  if ((ditherType == NO_DITHER) || (ditherType == PPM_DITHER)) return;
  if (noDisplayFlag) return;

  if (!MakeWindow(name)) {
    /* Could not do that dither.  Try again if can */
    switch (ditherType) {
    case HYBRID_DITHER:
    case HYBRID2_DITHER:
    case FS4_DITHER:
    case FS2_DITHER:
    case FS2FAST_DITHER:
    case Twox2_DITHER:
    case ORDERED_DITHER:
    case ORDERED2_DITHER:
    case MBORDERED_DITHER:
      fprintf(stderr, "trying -dither color\n");
      ditherType = FULL_COLOR_DITHER;
      InitColorDisplay(name);
      InitColorDither(matched_depth == 32);
      return;

    case GRAY_DITHER:
    case GRAY2_DITHER:
    case GRAY256_DITHER:
    case GRAY2562_DITHER:
    case FULL_COLOR_DITHER:
    case FULL_COLOR2_DITHER:
    case MONO_DITHER:
    case MONO_THRESHOLD:
    default:
      /* cant do anything */
      exit(-1);
  }
}

  gc = XCreateGC(display, window, 0, 0);

  dcmap = cmap = XDefaultColormap(display, DefaultScreen(display));

  xcolor.flags = DoRed | DoGreen | DoBlue;

  if (owncmFlag) goto create_map;
  retry_alloc_colors:
  for (i=0; i<ncolors; i++) {

    lum_num = (i / (CR_RANGE*CB_RANGE))%LUM_RANGE;
    cr_num = (i / CB_RANGE)%CR_RANGE;
    cb_num = i % CB_RANGE;

    ConvertColor(lum_num, cr_num, cb_num, &r, &g, &b);

    xcolor.red = r * 256;
    xcolor.green = g * 256;
    xcolor.blue = b * 256;

    if (XAllocColor(display, cmap, &xcolor) == 0 && cmap == dcmap) {
      int j;
      unsigned long tmp_pixel;
      XWindowAttributes xwa;

      if (!quietFlag) {
        fprintf(stderr, "Using private colormap.\n");
      }

      /* Free colors. */
      for(j = 0; j < i; j ++) {
        tmp_pixel = wpixel[j];
        XFreeColors(display, cmap, &tmp_pixel, 1, 0);
      }

      create_map:
      XGetWindowAttributes(display, window, &xwa);
      cmap = XCreateColormap(display, window, xwa.visual, AllocNone);
      XSetWindowColormap(display, window, cmap);

      goto retry_alloc_colors;
    }
    pixel[i] = xcolor.pixel;
    wpixel[i] = xcolor.pixel;
  }

  ximage = NULL;
}


/*
 *--------------------------------------------------------------
 *
 * InitGrayDisplay --
 *
 *	Initialized display for gray scale dither.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */

void InitGrayDisplay(name)
char *name;
{
  int ncolors = 128;
  XColor xcolor;
  int i;
  Colormap dcmap;
  unsigned long tmp_pixels[256];

  MakeWindow(name);

  gc = XCreateGC(display, window, 0, 0);

  dcmap = cmap = XDefaultColormap(display, DefaultScreen(display));

  xcolor.flags = DoRed | DoGreen | DoBlue;

  if (owncmFlag) goto create_map;
  retry_alloc_grays:
  for (i=0; i<ncolors; i++) {

    xcolor.red = xcolor.green = xcolor.blue = GAMMA_CORRECTION(i*2) * 256;

    if(XAllocColor(display, cmap, &xcolor) == 0 && cmap == dcmap) {
      int j;
      XWindowAttributes xwa;

      if (!quietFlag) {
        fprintf(stderr, "Using private colormap.\n");
      }

      /* Free colors. */
      for(j = 0; j < i; j ++) {
        unsigned long tmp_pixel;
        tmp_pixel = tmp_pixels[j*2];
        XFreeColors(display, cmap, &tmp_pixel, 1, 0);
      }

      create_map:
      XGetWindowAttributes(display, window, &xwa);
      cmap = XCreateColormap(display, window, xwa.visual, AllocNone);
      XSetWindowColormap(display, window, cmap);

      goto retry_alloc_grays;
    }
    tmp_pixels[i*2] = pixel[i*2] = xcolor.pixel;
    tmp_pixels[(i*2)+1] = pixel[(i*2)+1] = xcolor.pixel;
    wpixel[(i*2)] = xcolor.pixel;
    wpixel[(i*2)+1] = xcolor.pixel;
    if(matched_depth == 8) {
      wpixel[i*2] |= wpixel[i*2] << 8;
      wpixel[i*2+1] |= wpixel[i*2+1] << 8;
    }
    if(matched_depth == 8 || matched_depth == 16) {
      wpixel[i*2] |= wpixel[i*2] << 16;
      wpixel[i*2+1] |= wpixel[i*2+1] << 16;
    }
#ifdef SIXTYFOUR_BIT
    if(matched_depth == 8 || matched_depth == 16 || matched_depth == 24 || matched_depth == 32) {
      wpixel[i*2] |= wpixel[i*2] << 32;
      wpixel[i*2+1] |= wpixel[i*2+1] << 32;
    }
#endif

  }

  ximage = NULL;
}


/*
 *--------------------------------------------------------------
 *
 * InitGray256Display --
 *
 *	Initialized display for gray scale dither with 256 levels
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */


void InitGray256Display(name)
char *name;
{
  int ncolors = 256;
  XColor xcolor;
  int i;
  Colormap dcmap;
  int result;
  XWindowAttributes xwa;
  unsigned long tmp_pixels[256];

  MakeWindow(name);

  gc = XCreateGC(display, window, 0, 0);

  dcmap = cmap = XDefaultColormap(display, DefaultScreen(display));

  xcolor.flags = DoRed | DoGreen | DoBlue;

  if (owncmFlag) {
    XGetWindowAttributes(display, window, &xwa);
    cmap = XCreateColormap(display, window, xwa.visual, AllocNone);
    XSetWindowColormap(display, window, cmap);
  }

  retry_alloc_grays:
  for (i = 0;  i < ncolors;  i++) {
    xcolor.red = xcolor.green = xcolor.blue = GAMMA_CORRECTION(i) * 256;
    if ((result = XAllocColor(display, cmap, &xcolor)) == 0 && cmap == dcmap) {
      int j;
      unsigned long tmp_pixel;

      if (!quietFlag) {
        fprintf(stderr, "Using private colormap.\n");
      }

      /* Free colors. */
      for (j = 0; j < i; j ++) {
        tmp_pixel = tmp_pixels[j];
        XFreeColors(display, cmap, &tmp_pixel, 1, 0);
      }

      XGetWindowAttributes(display, window, &xwa);
      cmap = XCreateColormap(display, window, xwa.visual, AllocNone);
      XSetWindowColormap(display, window, cmap);

      goto retry_alloc_grays;
    }
    tmp_pixels[i] = pixel[i] = xcolor.pixel;
    wpixel[i] = xcolor.pixel;
    if(matched_depth == 8) wpixel[i] |= wpixel[i] << 8;
    if(matched_depth == 8 || matched_depth == 16) {
      wpixel[i] |= wpixel[i] << 16;
    }
#ifdef SIXTYFOUR_BIT
    if(matched_depth == 8 || matched_depth == 16 || matched_depth == 24 || matched_depth == 32) {
      wpixel[i] |= wpixel[i] << 32;
    }
#endif

  }

  ximage = NULL;
}


/*
 *--------------------------------------------------------------
 *
 * InitMonoDisplay --
 *
 *	Initialized display for monochrome dither.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */

void InitMonoDisplay(name)
char *name;
{
  XGCValues xgcv;

  MakeWindow(name);

  xgcv.background = BlackPixel(display, DefaultScreen(display));
  xgcv.foreground = WhitePixel(display, DefaultScreen(display));

  gc = XCreateGC(display, window, GCForeground | GCBackground, &xgcv);

  ximage = NULL;
}



/*
 *--------------------------------------------------------------
 *
 * InitColorDisplay --
 *
 *	Initialized display for full color output.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */

void InitColorDisplay(name)
char *name;
{
  XWindowAttributes winattr;
  MakeWindow(name);

  gc = XCreateGC(display, window, 0, 0);
  ximage = NULL;

  XGetWindowAttributes(display, window, &winattr);
  /*
   * Misuse of wpixel 
   */
  wpixel[0] = winattr.visual->red_mask;
  wpixel[1] = winattr.visual->green_mask;
  wpixel[2] = winattr.visual->blue_mask;
}


/*
 *--------------------------------------------------------------
 *
 * ExecuteDisplay --
 *
 *	Actually displays display plane in previously created window.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

void
#ifndef NOCONTROLS
ExecuteDisplay(vid_stream,frame_increment)
     VidStream *vid_stream;
     int frame_increment;
#else
ExecuteDisplay(vid_stream)
     VidStream *vid_stream;
#endif
{
  char dummy;
  Visual *FindFullColorVisual();
  Visual *fc_visual;
  int depth;
  static int rate_deal = -1;
  static int one_frame_time;
  static struct timeval tftarget, tfnow;
  register int usec, sec;
#ifndef NOCONTROLS
  XEvent xev;
#endif

#ifndef NOCONTROLS
  totNumFrames+=frame_increment;
#else
  totNumFrames++;
#endif

  if (partialFlag) {
    if ((endFrame != -1) && (totNumFrames > endFrame)) {
#ifdef ANALYSIS
      PrintAllStats();
#endif
      PrintTimeInfo();

#ifndef NOCONTROLS
      if ((frame_increment != 0) && (ControlShow != CTRLBAR_NONE))
        UpdateFrameTotal();
      FilmState = FILM_END;
      return;
#else
      if (loopFlag) {
              clear_data_stream(&vid_stream->buf_start,
			  &vid_stream->max_buf_length,
			  &vid_stream->buf_length, 
			  &vid_stream->buffer);
              longjmp(env, 1);
      }
      DestroyVidStream(curVidStream);
      exit(0);
#endif
    }
    if (totNumFrames < startFrame) {
      return;
    }
  }


  /* Do frame rate control */
  switch (rate_deal) {
  case 0:
    break;
  default:
    gettimeofday(&tfnow, (struct timezone *)NULL);
    usec = tftarget.tv_usec - tfnow.tv_usec;
    sec  = tftarget.tv_sec - tfnow.tv_sec;
    if (usec < 0) {
      usec += 1000000;
      sec--;
    }
    
    /* If we're not behind, wait a bit */
    if ((sec >= 0)  &&  usec > 0) {
      tfnow.tv_sec = sec;
      tfnow.tv_usec = usec;
      select(0, NULL, NULL, NULL ,&tfnow); 
      gettimeofday(&tfnow, (struct timezone *)NULL);
    }
    /* Setup target for next frame */
    tftarget.tv_usec = tfnow.tv_usec + one_frame_time;
    if (tftarget.tv_usec >= 1000000) {
      tftarget.tv_usec -= 1000000;
      tftarget.tv_sec = tfnow.tv_sec + 1;
    } else tftarget.tv_sec = tfnow.tv_sec;
    break;
  case -1:
    switch (framerate) {
    case -1: /* Go with stream Value */
      rate_deal = VidRateNum[vid_stream->picture_rate];
      gettimeofday(&tftarget, (struct timezone *)NULL);
      one_frame_time = 1000000 / rate_deal;
      break;
    case 0: /* as fast as possible */
      rate_deal = 0;
      break;
    default:
      rate_deal = framerate;
      gettimeofday(&tftarget, (struct timezone *)NULL);
      one_frame_time = 1000000 / rate_deal;
      break;
    }
    break;
  }

#ifndef NOCONTROLS 
  if (frame_increment > 0) {
    TotalFrameCount++;
    if ((endFrame != -1) && (totNumFrames >= endFrame)) {
      FilmState = FILM_END;
    }
    if (!quietFlag && ControlShow == CTRLBAR_NONE)
      fprintf(stderr, "%d\r", totNumFrames);
  }
#else
  if (!quietFlag) {
    fprintf (stderr, "%d\r", totNumFrames);
  }
#endif

  if (ditherType == NO_DITHER) return;
  if (ditherType == PPM_DITHER) {
    ExecutePPM(vid_stream);
    return;
  }
  if (!noDisplayFlag) {
  if (ximage == NULL) {

    int pixels_per_mb = 16;
    if(IS_2x2_DITHER(ditherType)) pixels_per_mb = 32;
    
    if ((ditherType == FULL_COLOR_DITHER) ||
	       (ditherType == FULL_COLOR2_DITHER)) {
      int w, h;
      
      w = vid_stream->mb_width  * pixels_per_mb;
      h = vid_stream->mb_height * pixels_per_mb;
      
      fc_visual = FindFullColorVisual(display, &depth);
      ximage = XCreateImage (display, fc_visual, depth, ZPixmap,
			     0, &dummy, w, h, 32, 0);
      
    } else if (ditherType == MONO_DITHER || ditherType == MONO_THRESHOLD) {
      ximage = XCreateImage (display, None, matched_depth, XYBitmap, 0, &dummy,
			     vid_stream->mb_width * pixels_per_mb,
			     vid_stream->mb_height * pixels_per_mb, 8, 0);
      ximage->byte_order = MSBFirst;
      ximage->bitmap_bit_order = MSBFirst;
    } else {
      ximage = XCreateImage(display, None, matched_depth, ZPixmap, 0, &dummy,
			    vid_stream->mb_width * pixels_per_mb,
			    vid_stream->mb_height * pixels_per_mb, 8, 0);
    }
  }

/* 
 * Always work in native bit and byte order. This tells Xlib to reverse
 * bit and byte order if necessary when crossing a network. Frankly, this
 * part of XImages is somewhat underdocumented, so this may not be exactly
 * correct.
 */ 
#ifdef LITTLE_ENDIAN_ARCHITECTURE
    ximage->byte_order = LSBFirst;
    ximage->bitmap_bit_order = LSBFirst;
#else
    ximage->byte_order = MSBFirst;
    ximage->bitmap_bit_order = MSBFirst;
#endif

  
#ifdef SH_MEM
    if (shmemFlag) {
           XShmPutImage(display, window, gc, vid_stream->current->ximage, 
           0, 0, 0, 0,
           vid_stream->current->ximage->width, 
           vid_stream->current->ximage->height, True);
           XFlush(display);
      
#ifndef NOCONTROLS
      /* Wait for it _without_ removing other events from queue */
      XIfEvent(display, &xev, IfEventType, (char *) (&CompletionType));
#else
      while(1) {
        XEvent xev;
	
        XNextEvent(display, &xev);
        if (xev.type == CompletionType) {
          break;
        }
      }
#endif
    }
    else 
#endif
      
      {
        ximage->data = (char *) vid_stream->current->display; 
	
        XPutImage(display, window, gc, ximage, 0, 0, 0, 0, ximage->width, ximage->height);
      }
  }
#ifndef NOCONTROLS
      if ((frame_increment != 0) && (ControlShow != CTRLBAR_NONE)) {
        UpdateFrameTotal();
      }
#endif
  if (requireKeypressFlag) {
    char foo;
    printf("Press return (%d) ", totNumFrames);    
    while ((foo = getchar()) != '\n')
      ;
  }

}


extern char *inputName;
extern char *strrchr();
#define PPM_BITS 8


/*
 *--------------------------------------------------------------
 *
 * ExecutePPM --
 *
 *	Write out a display plane as a PPM file.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

void
ExecutePPM(vid_stream)
     VidStream *vid_stream;
{
  static int munged = 0;
  static char mungedInputName[300];
  char fileName[300];
  FILE *file;
  int n;
  unsigned int *p;
  unsigned int r, g, b;

  if (!munged) {
    char *cp;

    cp = strrchr(inputName, '/');
    if (cp != NULL)
      ++cp;
    else
      cp = inputName;
    strcpy(mungedInputName, cp);
    cp = strrchr(mungedInputName, '.');
    if (cp != NULL)
	*cp = '\0';
    munged = 1;
  }

  sprintf(fileName, "%s_%05d.ppm", mungedInputName, totNumFrames );
  file = fopen(fileName, "w");
  if (file == NULL) {
    perror(fileName);
    exit(1);
  }

  fprintf(file, "P6\n");
  fprintf(file, "%d %d\n", vid_stream->h_size, vid_stream->v_size);
  fprintf(file, "255\n");

  p = (unsigned int *) vid_stream->current->display;
  n = vid_stream->h_size * vid_stream->v_size;
  while (n > 0) {
    r = *p & 0xff;
    g = (*p >> PPM_BITS) & 0xff;
    b = (*p >> (2*PPM_BITS)) & 0xff;
    putc(r, file);
    putc(g, file);
    putc(b, file);
    ++p;
    --n;
  }

  fclose(file);
}


#ifdef NO_GETTIMEOFDAY
/* raw approximation */
int gettimeofday (struct timeval * retval, void * unused)
{
	timeb_t tm;

	ftime (&tm);
	retval->tv_sec=  tm.time;
	retval->tv_usec= tm.millitm*1000;
	return 0;
}
#endif