about summary refs log tree commit diff
path: root/converter/ppm/ppmtompeg/parallel.c
blob: 50381271a29bb9c7aa02d75581bd88d07f05422b (plain) (blame)
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
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
/*===========================================================================*
 * parallel.c              
 *                         
 *  Procedures to make encoder run in parallel   
 *                             
 *===========================================================================*/

/* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */


/*==============*
 * HEADER FILES *
 *==============*/

#define _XOPEN_SOURCE 500 /* Make sure stdio.h contains pclose() */
/* _ALL_SOURCE is needed on AIX to make the C library include the 
   socket services (e.g. define struct sockaddr) 

   Note that AIX standards.h actually sets feature declaration macros such
   as _XOPEN_SOURCE, unless they are already set.
*/
#define _ALL_SOURCE

/* On AIX, pm_config.h includes standards.h, which expects to be included
   after feature declaration macros such as _XOPEN_SOURCE.  So we include
   pm_config.h as late as possible.
*/


#include <stdarg.h>
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <netdb.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/times.h>

#include "mallocvar.h"
#include "nstring.h"
#include "nsleep.h"

#include "pm.h"

#include "all.h"
#include "param.h"
#include "mpeg.h"
#include "prototypes.h"
#include "readframe.h"
#include "fsize.h"
#include "combine.h"
#include "frames.h"
#include "input.h"
#include "psocket.h"
#include "frametype.h"
#include "gethostname.h"

#include "parallel.h"


struct childState {
    boolean      finished;
    unsigned int startFrame;
    unsigned int numFrames;
    unsigned int lastNumFrames;
    unsigned int numSeconds;
    float        fps;
};


struct scheduler {
    /* This tracks the state of the subsystem that determines the assignments
       for the children
    */
    unsigned int nextFrame;
        /* The next frame that needs to be assigned to a child */
    unsigned int numFramesInJob;
        /* Total number of frames in the whole run of Ppmtompeg */
    unsigned int numMachines;
};



#define MAX_IO_SERVERS  10
#ifndef SOMAXCONN
#define SOMAXCONN 5
#endif

/*==================*
 * CONSTANTS        *
 *==================*/

#define TERMINATE_PID_SIGNAL    SIGTERM  /* signal used to terminate forked childs */
#ifndef MAXARGS
#define MAXARGS     1024   /* Max Number of arguments in safe_fork command */
#endif

/*==================*
 * STATIC VARIABLES *
 *==================*/

static char rsh[256];
static struct hostent *hostEntry = NULL;
static boolean  *frameDone;
static int  outputServerSocket;
static int  decodeServerSocket;
static boolean  parallelPerfect = FALSE;
static  int current_max_forked_pid=0;


/*==================*
 * GLOBAL VARIABLES *
 *==================*/

extern int yuvHeight, yuvWidth;
extern char statFileName[256];
extern FILE *statFile;
extern boolean debugMachines;
extern boolean debugSockets;
int parallelTestFrames = 10;
int parallelTimeChunks = 60;
const char *IOhostName;
int ioPortNumber;
int decodePortNumber;
boolean niceProcesses = FALSE;
boolean forceIalign = FALSE;
int     machineNumber = -1;
boolean remoteIO = FALSE;
boolean separateConversion;
    /* The I/O server will convert from the input format to the base format,
       and the slave will convert from the base format to the YUV internal
       format.  If false, the I/O server assumes the input format is the
       base format and converts from the base format to the YUV internal
       format; the slave does no conversion.
    */
time_t  IOtime = 0;
extern char encoder_name[];
int     ClientPid[MAX_MACHINES+4];


/*=====================*
 * INTERNAL PROCEDURES *
 *=====================*/


static void PM_GNU_PRINTF_ATTR(1,2)
machineDebug(const char format[], ...) {

    va_list args;

    va_start(args, format);

    if (debugMachines) {
        const char * const hostname = GetHostName();
        fprintf(stderr, "%s: ---", hostname);
        pm_strfree(hostname);
        vfprintf(stderr, format, args);
        fputc('\n', stderr);
    }
    va_end(args);
}



static void PM_GNU_PRINTF_ATTR(1,2)
errorExit(const char format[], ...) {

    const char * const hostname = GetHostName();

    va_list args;

    va_start(args, format);

    fprintf(stderr, "%s: FATAL ERROR.  ", hostname);
    pm_strfree(hostname);
    vfprintf(stderr, format, args);
    fputc('\n', stderr);

    exit(1);

    va_end(args);
}



static void
TransmitPortNum(const char * const hostName, 
                int          const portNum, 
                int          const newPortNum) {
/*----------------------------------------------------------------------------
   Transmit the port number 'newPortNum' to the master on port 'portNum'
   of host 'hostName'.
-----------------------------------------------------------------------------*/
    int clientSocket;
    const char * error;
    
    ConnectToSocket(hostName, portNum, &hostEntry, &clientSocket, &error);
    
    if (error)
        errorExit("Can't connect in order to transmit port number.  %s",
                  error);

    WriteInt(clientSocket, newPortNum);
    
    close(clientSocket);
}



static void
readYUVDecoded(int          const socketFd,
               unsigned int const Fsize_x,
               unsigned int const Fsize_y,
               MpegFrame *  const frameP) {
    
    unsigned int y;
    
    for (y = 0; y < Fsize_y; ++y)         /* Y */
        ReadBytes(socketFd, 
                  (unsigned char *)frameP->decoded_y[y], Fsize_x);
    
    for (y = 0; y < (Fsize_y >> 1); ++y)  /* U */
        ReadBytes(socketFd, 
                  (unsigned char *)frameP->decoded_cb[y], (Fsize_x >> 1));
    
    for (y = 0; y < (Fsize_y >> 1); ++y)  /* V */
        ReadBytes(socketFd, 
                  (unsigned char *)frameP->decoded_cr[y], (Fsize_x >> 1));
}



static void
writeYUVDecoded(int          const socketFd,
                unsigned int const Fsize_x,
                unsigned int const Fsize_y,
                MpegFrame *  const frameP) {
    
    unsigned int y;
    
    for (y = 0; y < Fsize_y; ++y)         /* Y */
        WriteBytes(socketFd, 
                  (unsigned char *)frameP->decoded_y[y], Fsize_x);
    
    for (y = 0; y < (Fsize_y >> 1); ++y)  /* U */
        WriteBytes(socketFd, 
                   (unsigned char *)frameP->decoded_cb[y], (Fsize_x >> 1));
    
    for (y = 0; y < (Fsize_y >> 1); ++y)  /* V */
        WriteBytes(socketFd, 
                   (unsigned char *)frameP->decoded_cr[y], (Fsize_x >> 1));
}



static void
writeYUVOrig(int          const socketFd,
             unsigned int const Fsize_x,
             unsigned int const Fsize_y,
             MpegFrame *  const frameP) {
    
    unsigned int y;
    
    for (y = 0; y < Fsize_y; ++y)         /* Y */
        WriteBytes(socketFd, 
                  (unsigned char *)frameP->orig_y[y], Fsize_x);
    
    for (y = 0; y < (Fsize_y >> 1); ++y)  /* U */
        WriteBytes(socketFd, 
                   (unsigned char *)frameP->orig_cb[y], (Fsize_x >> 1));
    
    for (y = 0; y < (Fsize_y >> 1); ++y)  /* V */
        WriteBytes(socketFd, 
                   (unsigned char *)frameP->orig_cr[y], (Fsize_x >> 1));
}



static void
readYUVOrig(int          const socketFd,
            unsigned int const Fsize_x,
            unsigned int const Fsize_y,
            MpegFrame *  const frameP) {
    
    unsigned int y;
    
    for (y = 0; y < Fsize_y; ++y)         /* Y */
        ReadBytes(socketFd, 
                  (unsigned char *)frameP->orig_y[y], Fsize_x);
    
    for (y = 0; y < (Fsize_y >> 1); ++y)  /* U */
        ReadBytes(socketFd, 
                  (unsigned char *)frameP->orig_cb[y], (Fsize_x >> 1));
    
    for (y = 0; y < (Fsize_y >> 1); ++y)  /* V */
        ReadBytes(socketFd, 
                  (unsigned char *)frameP->orig_cr[y], (Fsize_x >> 1));
}



/*===========================================================================*
 *
 * EndIOServer
 *
 *  called by the master process -- tells the I/O server to commit
 *  suicide
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:    none
 *
 *===========================================================================*/
static void
  EndIOServer()
{
  /* send signal to IO server:  -1 as frame number */
  GetRemoteFrame(NULL, -1);
}


/*===========================================================================*
 *
 * NotifyDecodeServerReady
 *
 *  called by a slave to the Decode Server to tell it a decoded frame
 *  is ready and waiting
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:    none
 *
 *===========================================================================*/
void
NotifyDecodeServerReady(int const id) {

    int   clientSocket;
    time_t  tempTimeStart, tempTimeEnd;
    const char * error;
    
    time(&tempTimeStart);
    
    ConnectToSocket(IOhostName, decodePortNumber, &hostEntry, &clientSocket,
                    &error);
    
    if (error)
        errorExit("CHILD: Can't connect to decode server to tell it a frame "
                "is ready.  %s", error);
    
    WriteInt(clientSocket, id);
    
    close(clientSocket);
    
    time(&tempTimeEnd);
    IOtime += (tempTimeEnd-tempTimeStart);
}



/*===========================================================================*
 *
 * WaitForDecodedFrame
 *
 *  blah blah blah
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:    none
 *
 *===========================================================================*/
void
  WaitForDecodedFrame(id)
int id;
{
  int const negativeTwo = -2;
  int   clientSocket;
  int     ready;
  const char * error;

  /* wait for a decoded frame */
  if ( debugSockets ) {
    fprintf(stdout, "WAITING FOR DECODED FRAME %d\n", id);
  }

  ConnectToSocket(IOhostName, decodePortNumber, &hostEntry, &clientSocket,
                  &error);

  if (error)
      errorExit("CHILD: Can't connect to decode server "
                "to get decoded frame.  %s",
                error);

  /* first, tell DecodeServer we're waiting for this frame */
  WriteInt(clientSocket, negativeTwo);

  WriteInt(clientSocket, id);

  ReadInt(clientSocket, &ready);

  if ( ! ready ) {
    int     waitSocket;
    int     waitPort;
    int     otherSock;
    const char * error;

    /* it's not ready; set up a connection and wait for decode server */
    CreateListeningSocket(&waitSocket, &waitPort, &error);
    if (error)
        errorExit("Unable to create socket on which to listen for "
                  "decoded frame.  %s", error);

    /* tell decode server where we are */
    WriteInt(clientSocket, machineNumber);

    WriteInt(clientSocket, waitPort);

    close(clientSocket);

    if ( debugSockets ) {
      fprintf(stdout, "SLAVE:  WAITING ON SOCKET %d\n", waitPort);
      fflush(stdout);
    }

    AcceptConnection(waitSocket, &otherSock, &error);
    if (error)
        errorExit("I/O SERVER: Failed to accept next connection.  %s", error);

    /* should we verify this is decode server? */
    /* for now, we won't */

    close(otherSock);

    close(waitSocket);
  } else {
    close(clientSocket);
  }

  if ( debugSockets ) {
    fprintf(stdout, "YE-HA FRAME %d IS NOW READY\n", id);
  }
}


/*===========================================================================*
 *
 * SendDecodedFrame
 *
 *  Send the frame to the decode server.
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:    none
 *
 *===========================================================================*/
void
SendDecodedFrame(MpegFrame * const frameP) {
/*----------------------------------------------------------------------------
   Send frame *frameP to the decode server.
-----------------------------------------------------------------------------*/
    int const negativeTwo = -2;
    
    int clientSocket;
    const char * error;
    
    /* send to IOServer */
    ConnectToSocket(IOhostName, ioPortNumber, &hostEntry,
                    &clientSocket, &error);
    if (error)
        errorExit("CHILD: Can't connect to decode server to "
                  "give it a decoded frame.  %s", error);
    
    WriteInt(clientSocket, negativeTwo);
    
    WriteInt(clientSocket, frameP->id);

    writeYUVDecoded(clientSocket, Fsize_x, Fsize_y, frameP);
    
    close(clientSocket);
}


/*===========================================================================*
 *
 * GetRemoteDecodedFrame
 *
 *  get the decoded frame from the decode server.
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:   
 *
 *===========================================================================*/
void
GetRemoteDecodedRefFrame(MpegFrame * const frameP, 
                         int         const frameNumber) {
/*----------------------------------------------------------------------------
   Get decoded frame number 'frameNumber' *frameP from the decode server.
-----------------------------------------------------------------------------*/
  int const negativeThree = -3;
  int clientSocket;
  const char * error;

  /* send to IOServer */
  ConnectToSocket(IOhostName, ioPortNumber, &hostEntry,
                  &clientSocket, &error);
  if (error)
      errorExit("CHILD: Can't connect to decode server "
                "to get a decoded frame.  %s",
                error);

  /* ask IOServer for decoded frame */
  WriteInt(clientSocket, negativeThree);

  WriteInt(clientSocket, frameP->id);

  readYUVDecoded(clientSocket, Fsize_x, Fsize_y, frameP);

  close(clientSocket);
}


/*********
  routines handling forks, execs, PIDs and signals
  save, system-style forks
  apian@ise.fhg.de
  *******/


/*===========================================================================*
 *
 * cleanup_fork
 *
 *  Kill all the children, to be used when we get killed
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:   kills other processes
 *
 *===========================================================================*/
static void cleanup_fork( dummy )       /* try to kill all child processes */
     int dummy;
{
  register int i;
  for (i = 0;  i < current_max_forked_pid;  ++i ) {

#ifdef DEBUG_FORK
    fprintf(stderr, "cleanup_fork: killing PID %d\n", ClientPid[i]);
#endif

    if (kill(ClientPid[i], TERMINATE_PID_SIGNAL)) {
      fprintf(stderr, "cleanup_fork: killed PID=%d failed (errno %d)\n", 
          ClientPid[i], errno);
    }
  }
}

/*===========================================================================*
 *
 * safe_fork
 *
 *  fork a command
 *
 * RETURNS:     success/failure
 *
 * SIDE EFFECTS:   Fork the command, and save to PID so you can kil it later!
 *
 *===========================================================================*/
static int safe_fork(command)       /* fork child process and remember its PID */
     char *command;
{
  static int init=0;
  char *argis[MAXARGS];
  register int i=1;
  
  if (!(argis[0] = strtok(command, " \t"))) return(0); /* tokenize */
  while ((argis[i] = strtok(NULL, " \t")) && i < MAXARGS) ++i;
  argis[i] = NULL;
  
#ifdef DEBUG_FORK
  {register int i=0; 
   fprintf(stderr, "Command %s becomes:\n", command);
   while(argis[i]) {fprintf(stderr, "--%s--\n", argis[i]); ++i;} }
#endif
  
  if (!init) {          /* register clean-up routine */
    signal (SIGQUIT, cleanup_fork);
    signal (SIGTERM, cleanup_fork);
    signal (SIGINT , cleanup_fork);
    init=1;
  }
  
  if (-1 == (ClientPid[current_max_forked_pid] = fork()) )  {
    perror("safe_fork: fork failed ");
    return(-1);
  }
  if( !ClientPid[current_max_forked_pid]) { /* we are in child process */
    execvp(argis[0], argis );
    perror("safe_fork child: exec failed ");
    exit(1);
  }
#ifdef DEBUG_FORK
  fprintf(stderr, "parallel: forked PID=%d\n", ClientPid[current_max_forked_pid]);
#endif
  current_max_forked_pid++;
  return(0);
}


/*=====================*
 * EXPORTED PROCEDURES *
 *=====================*/

            /*=================*
             * IO SERVER STUFF *
             *=================*/


/*===========================================================================*
 *
 * SetIOConvert
 *
 *  sets the IO conversion to be separate or not.  If separate, then
 *  some post-processing is done at slave end
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:    none
 *
 *===========================================================================*/
void
SetIOConvert(boolean const separate) {
    separateConversion = separate;
}


/*===========================================================================*
 *
 * SetParallelPerfect
 *
 *  If this is called, then frames will be divided up completely, and
 *  evenly (modulo rounding) between all the processors
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:    Sets parallelPerfect ....
 *
 *===========================================================================*/
void
SetParallelPerfect(boolean val)
{
    parallelPerfect = val;
}


/*===========================================================================*
 *
 * SetRemoteShell
 *
 *  sets the remote shell program (usually rsh, but different on some
 *  machines)
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:    none
 *
 *===========================================================================*/
void
SetRemoteShell(const char * const shell) {
    strcpy(rsh, shell);
}


static void
decodedFrameToDisk(int const otherSock) {
/*----------------------------------------------------------------------------
  Get a decoded from from socket 'otherSock' and write it to disk.
-----------------------------------------------------------------------------*/
    int frameNumber;
    MpegFrame * frameP;

    ReadInt(otherSock, &frameNumber);
    
    if (debugSockets) {
        fprintf(stdout, "INPUT SERVER:  GETTING DECODED FRAME %d\n", 
                frameNumber);
        fflush(stdout);
    }

    /* should read frame from socket, then write to disk */
    frameP = Frame_New(frameNumber, 'i');
    
    Frame_AllocDecoded(frameP, TRUE);
    
    readYUVDecoded(otherSock, Fsize_x, Fsize_y, frameP);

    /* now output to disk */
    WriteDecodedFrame(frameP);

    Frame_Free(frameP);
}        



static void
decodedFrameFromDisk(int const otherSock) {

    /* request for decoded frame from disk */
            
    int frameNumber;
    MpegFrame * frameP;

    ReadInt(otherSock, &frameNumber);
    
    if (debugSockets) {
        fprintf(stdout, "INPUT SERVER:  READING DECODED FRAME %d "
                "from DISK\n", frameNumber);
        fflush(stdout);
    }

    /* should read frame from disk, then write to socket */
    frameP = Frame_New(frameNumber, 'i');
    
    Frame_AllocDecoded(frameP, TRUE);
    
    ReadDecodedRefFrame(frameP, frameNumber);
    
    writeYUVDecoded(otherSock, Fsize_x, Fsize_y, frameP);
    
    Frame_Free(frameP);
}        



static void
routeFromSocketToDisk(int              const otherSock,
                      unsigned char ** const bigBufferP,
                      unsigned int *   const bigBufferSizeP) {

    /* routing output frame from socket to disk */

    int frameNumber;
    int numBytes;
    unsigned char * bigBuffer;
    unsigned int bigBufferSize;
    const char * fileName;
    FILE * filePtr;

    bigBuffer     = *bigBufferP;
    bigBufferSize = *bigBufferSizeP;

    ReadInt(otherSock, &frameNumber);
    ReadInt(otherSock, &numBytes);

    /* Expand bigBuffer if necessary to fit this frame */
    if (numBytes > bigBufferSize) {
        bigBufferSize = numBytes;
        if (bigBuffer != NULL)
            free(bigBuffer);

        MALLOCARRAY_NOFAIL(bigBuffer, bigBufferSize);
    }
    
    /* now read in the bytes */
    ReadBytes(otherSock, bigBuffer, numBytes);
    
    /* open file to output this stuff to */
    pm_asprintf(&fileName, "%s.frame.%d", outputFileName, frameNumber);
    filePtr = fopen(fileName, "wb");

    if (filePtr == NULL)
        errorExit("I/O SERVER: Could not open output file(3):  %s", fileName);

    pm_strfree(fileName);

    /* now write the bytes here */
    fwrite(bigBuffer, sizeof(char), numBytes, filePtr);
    
    fclose(filePtr);
    
    if (debugSockets) {
        fprintf(stdout, "====I/O SERVER:  WROTE FRAME %d to disk\n",
                frameNumber);
        fflush(stdout);
    }

    *bigBufferP     = bigBuffer;
    *bigBufferSizeP = bigBufferSize;
}        



static void
readConvertWriteToSocket(struct inputSource * const inputSourceP,
                         int                  const otherSock,
                         int                  const frameNumber,
                         bool *               const endOfStreamP) {
/*----------------------------------------------------------------------------
   Get the frame numbered 'frameNumber' from input source
   *inputSourceP, apply format conversion User requested, and write
   the "base format" result to socket 'otherSock'.
-----------------------------------------------------------------------------*/
    FILE * convertedFileP;
    
    convertedFileP = ReadIOConvert(inputSourceP, frameNumber);
    if (convertedFileP) {
        bool eof;
        eof = FALSE;  /* initial value */
        while (!eof) {
            unsigned char buffer[1024];
            unsigned int numBytes;
            
            numBytes = fread(buffer, 1, sizeof(buffer), convertedFileP);
            
            if (numBytes > 0) {
                WriteInt(otherSock, numBytes);
                WriteBytes(otherSock, buffer, numBytes);
            } else
                eof = TRUE;
        }
        
        if (strcmp(ioConversion, "*") == 0 )
            fclose(convertedFileP);
        else
            pclose(convertedFileP);
        
        *endOfStreamP = FALSE;
    } else
        *endOfStreamP = TRUE;
}



static void
readWriteYuvToSocket(struct inputSource * const inputSourceP,
                     int                  const otherSock,
                     int                  const frameNumber,
                     bool *               const endOfStreamP) {
/*----------------------------------------------------------------------------
   Read Frame number 'frameNumber' from the input source *inputSourceP,
   assuming it is in base format, and write its contents in YUV format
   to socket 'otherSock'.

   Wait for acknowledgement that consumer has received it.
-----------------------------------------------------------------------------*/
    MpegFrame * frameP;

    frameP = Frame_New(frameNumber, 'i');
    
    ReadFrame(frameP, inputSourceP, frameNumber, inputConversion,
              endOfStreamP);
    
    if (!*endOfStreamP) {
        writeYUVOrig(otherSock, Fsize_x, Fsize_y, frameP);
        
        {
            /* Make sure we don't leave until other processor read
               everything
            */
            int dummy;
            ReadInt(otherSock, &dummy);
            assert(dummy == 0);
        }
    }
    Frame_Free(frameP);
}



static void
readFrameWriteToSocket(struct inputSource * const inputSourceP,
                       int                  const otherSock,
                       int                  const frameNumber,
                       bool *               const endOfStreamP) {
/*----------------------------------------------------------------------------
   Read Frame number 'frameNumber' from the input source *inputSourceP
   and write it to socket 'otherSock'.
-----------------------------------------------------------------------------*/
    if (debugSockets) {
        fprintf(stdout, "I/O SERVER GETTING FRAME %d\n", frameNumber);
        fflush(stdout);
    }

    if (separateConversion)
        readConvertWriteToSocket(inputSourceP, otherSock, frameNumber,
                                 endOfStreamP);
    else
        readWriteYuvToSocket(inputSourceP, otherSock, frameNumber,
                             endOfStreamP);

    if (debugSockets) {
        fprintf(stdout, "====I/O SERVER:  READ FRAME %d\n", frameNumber);
    }
}



static void
processNextConnection(int                  const serverSocket,
                      struct inputSource * const inputSourceP,
                      bool *               const doneP,
                      unsigned char **     const bigBufferP,
                      unsigned int *       const bigBufferSizeP) {

    int          otherSock;
    int          command;
    const char * error;
    
    AcceptConnection(serverSocket, &otherSock, &error);
    if (error)
        errorExit("I/O SERVER: Failed to accept next connection.  %s", error);

    ReadInt(otherSock, &command);

    switch (command) {
    case -1:
        *doneP = TRUE;
        break;
    case -2:
        decodedFrameToDisk(otherSock);
        break;
    case -3:
        decodedFrameFromDisk(otherSock);
        break;
    case -4:
        routeFromSocketToDisk(otherSock, bigBufferP, bigBufferSizeP);
        break;
    default: {
        unsigned int const frameNumber = command;

        bool endOfStream;

        readFrameWriteToSocket(inputSourceP, otherSock, frameNumber,
                               &endOfStream);

        if (endOfStream) {
            /* We don't do anything.  Closing the socket with having written
               anything is our signal that there is no more input.

               (Actually, Ppmtompeg cannot handle stream input in parallel
               mode -- this code is just infrastructure so maybe it can some
               day).
            */
        }
    }
    }
    close(otherSock);
}
 


void
IoServer(struct inputSource * const inputSourceP,
         const char *         const parallelHostName, 
         int                  const portNum) {
/*----------------------------------------------------------------------------
   Execute an I/O server.

   An I/O server is the partner on the master machine of a child process
   on a "remote" system.  "Remote" here doesn't just mean on another system.
   It means on a system that isn't even in the same cluster -- specifically,
   a system that doesn't have access to the same filesystem as the master.

   The child process passes frame contents between it and the master via
   the I/O server.
-----------------------------------------------------------------------------*/
    int       ioPortNum;
    int       serverSocket;
    boolean   done;
    unsigned char   *bigBuffer;
        /* A work buffer that we keep around permanently.  We increase
           its size as needed, but never shrink it.
        */
    unsigned int bigBufferSize;
        /* The current allocated size of bigBuffer[] */
    const char * error;

    bigBufferSize = 0;  /* Start with no buffer */
    bigBuffer = NULL;
    
    /* once we get IO port num, should transmit it to parallel server */

    CreateListeningSocket(&serverSocket, &ioPortNum, &error);
    if (error)
        errorExit("Unable to create socket on which to listen for "
                  "reports from children.  %s", error);

    if (debugSockets)
        fprintf(stdout, "====I/O USING PORT %d\n", ioPortNum);

    TransmitPortNum(parallelHostName, portNum, ioPortNum);

    if (separateConversion)
        SetFileType(ioConversion);  /* for reading */
    else
        SetFileType(inputConversion);

    done = FALSE;  /* initial value */

    while (!done)
        processNextConnection(serverSocket, inputSourceP,
                              &done, &bigBuffer, &bigBufferSize);

    close(serverSocket);

    if ( debugSockets ) {
        fprintf(stdout, "====I/O SERVER:  Shutting Down\n");
    }
}



/*===========================================================================*
 *
 * SendRemoteFrame
 *
 *  called by a slave to the I/O server; sends an encoded frame
 *  to the server to be sent to disk
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:    none
 *
 *===========================================================================*/
void
SendRemoteFrame(int const frameNumber, BitBucket * const bb) {

    int const negativeFour = -4;
    int clientSocket;
    time_t  tempTimeStart, tempTimeEnd;
    const char * error;

    time(&tempTimeStart);

    ConnectToSocket(IOhostName, ioPortNumber, &hostEntry,
                    &clientSocket, &error);
    if (error)
        errorExit("CHILD: Can't connect to I/O server to deliver results.  %s",
                  error);

    WriteInt(clientSocket, negativeFour);

    WriteInt(clientSocket, frameNumber);
    
    if (frameNumber != -1) {
        /* send number of bytes */
        
        WriteInt(clientSocket, (bb->totalbits+7)>>3);
    
        /* now send the bytes themselves */
        Bitio_WriteToSocket(bb, clientSocket);
    }

    close(clientSocket);

    time(&tempTimeEnd);
    IOtime += (tempTimeEnd-tempTimeStart);
}



void
GetRemoteFrame(MpegFrame * const frameP, 
               int         const frameNumber) {
/*----------------------------------------------------------------------------
   Get a frame from the I/O server.
   
   This is intended for use by a child.
-----------------------------------------------------------------------------*/
    int           clientSocket;
    const char * error;

    Fsize_Note(frameNumber, yuvWidth, yuvHeight);

    if (debugSockets) {
        fprintf(stdout, "MACHINE %s REQUESTING connection for FRAME %d\n",
                getenv("HOST"), frameNumber);
        fflush(stdout);
    }

    ConnectToSocket(IOhostName, ioPortNumber, &hostEntry,
                    &clientSocket, &error);

    if (error)
        errorExit("CHILD: Can't connect to I/O server to get a frame.  %s", 
                  error);

    WriteInt(clientSocket, frameNumber);

    if (frameNumber != -1) {
        if (separateConversion) {
            unsigned char buffer[1024];
            /* This is by design the exact size of the data per message (except
               the last message for a frame) the I/O server sends.
            */
            int numBytes;  /* Number of data bytes in message */
            FILE * filePtr = pm_tmpfile();

            /* read in stuff, write to file, perform local conversion */
            do {
                ReadInt(clientSocket, &numBytes);

                if (numBytes > sizeof(buffer))
                    errorExit("Invalid message received: numBytes = %d, "
                              "which is greater than %u", 
                              numBytes, (unsigned)sizeof(numBytes));
                ReadBytes(clientSocket, buffer, numBytes);

                fwrite(buffer, 1, numBytes, filePtr);
            } while ( numBytes == sizeof(buffer) );
            fflush(filePtr);
            {
                bool endOfStream;
                rewind(filePtr);
                /* I/O Server gave us base format.  Read it as an MpegFrame */
                ReadFrameFile(frameP, filePtr, slaveConversion, &endOfStream);
                assert(!endOfStream);
            }
            fclose(filePtr);
        } else {
            Frame_AllocYCC(frameP);

            if (debugSockets) {
                fprintf(stdout, "MACHINE %s allocated YCC FRAME %d\n",
                        getenv("HOST"), frameNumber);
                fflush(stdout);
            }
            /* I/O Server gave us internal YUV format.  Read it as MpegFrame */
            readYUVOrig(clientSocket, yuvWidth, yuvHeight, frameP);
        }
    }

    WriteInt(clientSocket, 0);

    close(clientSocket);

    if (debugSockets) {
        fprintf(stdout, "MACHINE %s READ COMPLETELY FRAME %d\n",
                getenv("HOST"), frameNumber);
        fflush(stdout);
    }
}


struct combineControl {
    unsigned int numFrames;
};




static void
getAndProcessACombineConnection(int const outputServerSocket) {
    int          otherSock;
    int          command;
    const char * error;

    AcceptConnection(outputServerSocket, &otherSock, &error);

    if (error)
        errorExit("COMBINE SERVER: "
                  "Failed to accept next connection.  %s", error);
    
    ReadInt(otherSock, &command);
    
    if (command == -2) {
        /* this is notification from non-remote process that a
           frame is done.
            */
        int frameStart, frameEnd;

        ReadInt(otherSock, &frameStart);
        ReadInt(otherSock, &frameEnd);
            
        machineDebug("COMBINE_SERVER: Frames %d - %d done",
                     frameStart, frameEnd);
        {
            unsigned int i;
            for (i = frameStart; i <= frameEnd; ++i)
                frameDone[i] = TRUE;
        }
    } else
        errorExit("COMBINE SERVER: Unrecognized command %d received.",
                  command);

    close(otherSock);
}



#define READ_ATTEMPTS 5 /* number of times (seconds) to retry an input file */


static void
openInputFile(const char * const fileName,
              FILE **      const inputFilePP) {

    FILE * inputFileP;
    unsigned int attempts;
    
    inputFileP = NULL;
    attempts = 0;

    while (!inputFileP && attempts < READ_ATTEMPTS) {
        inputFileP = fopen(fileName, "rb");
        if (inputFileP == NULL) {
            pm_message("ERROR  Couldn't read frame file '%s' errno = %d (%s)"
                       "attempt %d", 
                       fileName, errno, strerror(errno), attempts);
            pm_sleep(1000);
        }
        ++attempts;
    }
    if (inputFileP == NULL)
        pm_error("Unable to open file '%s' after %d attempts.", 
                 fileName, attempts);

    *inputFilePP = inputFileP;
}



static void
waitForOutputFile(void *        const inputHandle,
                  unsigned int  const frameNumber,
                  FILE **       const ifPP) {
/*----------------------------------------------------------------------------
   Keep handling output events until we get the specified frame number.
   Open the file it's in and return the stream handle.
-----------------------------------------------------------------------------*/
    struct combineControl * const combineControlP = (struct combineControl *)
        inputHandle;

    if (frameNumber >= combineControlP->numFrames)
        *ifPP = NULL;
    else {
        const char * fileName;

        while (!frameDone[frameNumber]) {
            machineDebug("COMBINE_SERVER: Waiting for frame %u done", 
                         frameNumber);

            getAndProcessACombineConnection(outputServerSocket);
        }
        machineDebug("COMBINE SERVER: Wait for frame %u over", frameNumber);

        pm_asprintf(&fileName, "%s.frame.%u", outputFileName, frameNumber);

        openInputFile(fileName, ifPP);

        pm_strfree(fileName);
    }
}



static void
unlinkFile(void *       const inputHandle,
           unsigned int const frameNumber) {

    if (!keepTempFiles) {
        const char * fileName;

        pm_asprintf(&fileName, "%s.frame.%u", outputFileName, frameNumber);

        unlink(fileName);

        pm_strfree(fileName);
    }
}



void
CombineServer(int          const numFrames, 
              const char * const masterHostName, 
              int          const masterPortNum,
              const char * const outputFileName) {
/*----------------------------------------------------------------------------
   Execute a combine server.

   This handles combination of frames.
-----------------------------------------------------------------------------*/
  int    combinePortNum;
  FILE * ofP;
  const char * error;
  struct combineControl combineControl;
  
  /* once we get Combine port num, should transmit it to parallel server */
  
  CreateListeningSocket(&outputServerSocket, &combinePortNum, &error);
  if (error)
      errorExit("Unable to create socket on which to listen.  %s", error);

  machineDebug("COMBINE SERVER: LISTENING ON PORT %d", combinePortNum);
  
  TransmitPortNum(masterHostName, masterPortNum, combinePortNum);
  
  MALLOCARRAY_NOFAIL(frameDone, numFrames);
  {
      unsigned int i;
      for (i = 0; i < numFrames; ++i)
          frameDone[i] = FALSE;
  }
  ofP = pm_openw(outputFileName);
  
  combineControl.numFrames = numFrames;

  FramesToMPEG(ofP, &combineControl, &waitForOutputFile, &unlinkFile);

  machineDebug("COMBINE SERVER: Shutting down");
  
  /* tell Master server we are done */
  TransmitPortNum(masterHostName, masterPortNum, combinePortNum);
  
  close(outputServerSocket);

  fclose(ofP);
}


/*=====================*
 * MASTER SERVER STUFF *
 *=====================*/


static void
startCombineServer(const char * const encoderName,
                   unsigned int const numMachines,
                   const char * const masterHostName,
                   int          const masterPortNum,
                   unsigned int const numInputFiles,
                   const char * const paramFileName,
                   int          const masterSocket,
                   int *        const combinePortNumP) {

    char         command[1024];
    int          otherSock;
    const char * error;

    pm_snprintf(command, sizeof(command), 
                "%s %s -max_machines %d -output_server %s %d %d %s",
                encoderName, 
                debugMachines ? "-debug_machines" : "",
                numMachines, masterHostName, masterPortNum, 
                numInputFiles, paramFileName);
    
    machineDebug("MASTER: Starting combine server with shell command '%s'",
                 command);

    safe_fork(command);
    
    machineDebug("MASTER: Listening for connection back from "
                 "new Combine server");

    AcceptConnection(masterSocket, &otherSock, &error);
    if (error)
        errorExit("MASTER SERVER: "
                  "Failed to accept next connection.  %s", error);

    ReadInt(otherSock, combinePortNumP);
    close(otherSock);

    machineDebug("MASTER:  Combine port number = %d", *combinePortNumP);
}



static void
startDecodeServer(const char * const encoderName,
                  unsigned int const numMachines,
                  const char * const masterHostName,
                  int          const masterPortNum,
                  unsigned int const numInputFiles,
                  const char * const paramFileName,
                  int          const masterSocket,
                  int *        const decodePortNumP) {

    char         command[1024];
    int          otherSock;
    const char * error;

    pm_snprintf(command, sizeof(command), 
                "%s %s -max_machines %d -decode_server %s %d %d %s",
                encoder_name, 
                debugMachines ? "-debug_machines" : "",
                numMachines, masterHostName, masterPortNum,
                numInputFiles, paramFileName);

    machineDebug("MASTER: Starting decode server with shell command '%s'",
                 command);

    safe_fork(command);

    machineDebug("MASTER: Listening for connection back from "
                 "new Decode server");

    AcceptConnection(masterSocket, &otherSock, &error);
    if (error)
        errorExit("MASTER SERVER: "
                  "Failed to accept connection back from the new "
                  "decode server.  %s", error);

    ReadInt(otherSock, decodePortNumP);
    
    close(otherSock);
    
    machineDebug("MASTER:  Decode port number = %d", *decodePortNumP);
}



static void
startIoServer(const char *   const encoderName,
              unsigned int   const numChildren,
              const char *   const masterHostName,
              int            const masterPortNum,
              int            const masterSocket,
              const char *   const paramFileName,
              int *          const ioPortNumP) {
              
    char         command[1024];
    int          otherSock;
    const char * error;
    
    sprintf(command, "%s -max_machines %d -io_server %s %d %s",
            encoderName, numChildren, masterHostName, masterPortNum,
            paramFileName);

    machineDebug("MASTER: Starting I/O server with remote shell command '%s'",
                 command);

    safe_fork(command);
    
    machineDebug("MASTER: Listening for connection back from "
                 "new I/O server");

    AcceptConnection(masterSocket, &otherSock, &error);
    if (error)
        errorExit("MASTER SERVER: "
                  "Failed to accept connection back from the new "
                  "I/O server.  %s", error);
    
    ReadInt(otherSock, ioPortNumP);
    close(otherSock);
    
    machineDebug("MASTER:  I/O port number = %d", *ioPortNumP);
}    
    
    

static void
extendToEndOfPattern(unsigned int * const nFramesP,
                     unsigned int   const startFrame,
                     unsigned int   const framePatternLen,
                     unsigned int   const numFramesInStream) {

    assert(framePatternLen >= 1);
        
    while (startFrame + *nFramesP < numFramesInStream &&
           (startFrame + *nFramesP) % framePatternLen != 0)
        ++(*nFramesP);
}



static void
allocateInitialFrames(struct scheduler * const schedulerP,
                      boolean            const parallelPerfect,
                      boolean            const forceIalign,
                      unsigned int       const framePatternLen,
                      unsigned int       const parallelTestFrames,
                      unsigned int       const childNum,
                      unsigned int *     const startFrameP,
                      unsigned int *     const nFramesP) {
/*----------------------------------------------------------------------------
   Choose which frames, to hand out to the new child numbered 'childNum'.
-----------------------------------------------------------------------------*/
    unsigned int const framesPerChild = 
        MAX(1, ((schedulerP->numFramesInJob - schedulerP->nextFrame) /
                (schedulerP->numMachines - childNum)));

    unsigned int nFrames;

    if (parallelPerfect)
        nFrames = framesPerChild;
    else {
        assert(parallelTestFrames >= 1);

        nFrames = MIN(parallelTestFrames, framesPerChild);
    }
    if (forceIalign)
        extendToEndOfPattern(&nFrames, schedulerP->nextFrame,
                             framePatternLen, schedulerP->numFramesInJob);

    nFrames = MIN(nFrames, schedulerP->numFramesInJob - schedulerP->nextFrame);

    *startFrameP = schedulerP->nextFrame;
    *nFramesP = nFrames;
    schedulerP->nextFrame += nFrames;
}



static float
taperedGoalTime(struct childState const childState[],
                unsigned int      const remainingFrameCount) {
        
    float        goalTime;
    float        allChildrenFPS;
    float        remainingJobTime;
        /* How long we expect it to be before the whole movie is encoded*/
    float        sum;
    int          numMachinesToEstimate;
    unsigned int childNum;
    
    /* frames left = lastFrameInStream - startFrame + 1 */
    for (childNum = 0, sum = 0.0, numMachinesToEstimate = 0; 
         childNum < numMachines; ++childNum) {
        if (!childState[childNum].finished) {
            if (childState[childNum].fps < 0.0 )
                ++numMachinesToEstimate;
            else
                sum += childState[childNum].fps;
        }
    }
    
    allChildrenFPS = (float)numMachines *
        (sum/(float)(numMachines-numMachinesToEstimate));
    
    remainingJobTime = (float)remainingFrameCount/allChildrenFPS;
    
    goalTime = MAX(5.0, remainingJobTime/2);

    return goalTime;
}



static void
allocateMoreFrames(struct scheduler * const schedulerP,
                   unsigned int       const childNum,
                   struct childState  const childState[],
                   bool               const forceIalign,
                   unsigned int       const framePatternLen,
                   bool               const goalTimeSpecified,
                   unsigned int       const goalTimeArg,
                   unsigned int *     const startFrameP,
                   unsigned int *     const nFramesP) {
/*----------------------------------------------------------------------------
   Decide which frames should be child 'childNum''s next assignment,
   given the state/history of all children is childState[].

   The lowest numbered frame which needs yet to be encoded is frame
   number 'startFrame' and 'lastFrameInStream' is the highest.

   The allocation always starts at the lowest numbered frame that
   hasn't yet been allocated and is sequential.  We return as
   *startFrameP the frame number of the first frame in the allocation
   and as *nFramesP the number of frames.

   If 'goalTimeSpecified' is true, we try to make the assignment take
   'goalTimeArg' seconds.  If 'goalTimeSpecified' is not true, we choose
   a goal time ourselves, which is based on how long we think it will
   take for all the children to finish all the remaining frames.
-----------------------------------------------------------------------------*/
    float goalTime;
        /* Number of seconds we want the assignment to take.  We size the
           assignment to try to meet this goal.
        */
    unsigned int nFrames;
    float avgFps;

    if (!goalTimeSpecified) {
        goalTime = taperedGoalTime(childState,
                                   schedulerP->numFramesInJob - 
                                   schedulerP->nextFrame);
    
        pm_message("MASTER: ASSIGNING %s %.2f seconds of work",
                   machineName[childNum], goalTime);
    } else
        goalTime = goalTimeArg;
    
    if (childState[childNum].numSeconds != 0)
        avgFps = (float)childState[childNum].numFrames / 
            childState[childNum].numSeconds;
    else
        avgFps = 0.1;       /* arbitrary small value */

    nFrames = MAX(1u, (unsigned int)(goalTime * avgFps + 0.5));
    
    nFrames = MIN(nFrames, 
                  schedulerP->numFramesInJob - schedulerP->nextFrame);

    if (forceIalign)
        extendToEndOfPattern(&nFrames, schedulerP->nextFrame,
                             framePatternLen, schedulerP->numFramesInJob);

    *startFrameP = schedulerP->nextFrame;
    *nFramesP = nFrames;
    schedulerP->nextFrame += nFrames;
}



static void
startChildren(struct scheduler *   const schedulerP,
              const char *         const encoderName,
              const char *         const masterHostName,
              int                  const masterPortNum,
              const char *         const paramFileName,
              boolean              const parallelPerfect,
              boolean              const forceIalign,
              unsigned int         const framePatternLen,
              unsigned int         const parallelTestFrames,
              boolean              const beNice,
              int                  const masterSocket,
              int                  const combinePortNum,
              int                  const decodePortNum,
              int *                const ioPortNum,
              unsigned int *       const numIoServersP,
              struct childState ** const childStateP) {
/*----------------------------------------------------------------------------
   Start up the children.  Tell them to work for the master at
   'masterHostName':'masterPortNum'.

   Start I/O servers (as processes on this system) as required and return
   the port numbers of the TCP ports on which they listen as
   ioPortNum[] and the number of them as *numIoServersP.

   Give each of the children some initial work to do.  This may be just
   a small amount for timing purposes.

   We access and manipulate the various global variables that represent
   the state of the children, and the scheduler structure.
-----------------------------------------------------------------------------*/
    struct childState * childState;  /* malloc'ed */
    unsigned int childNum;
    unsigned int numIoServers;
    unsigned int childrenLeftCurrentIoServer;
        /* The number of additional children we can hook up to the
           current I/O server before reaching our maximum children per
           I/O server.  0 if there is no current I/O server.
        */

    MALLOCARRAY_NOFAIL(childState, schedulerP->numMachines);

    childrenLeftCurrentIoServer = 0;  /* No current I/O server yet */
    
    numIoServers = 0;  /* None created yet */

    for (childNum = 0; childNum < schedulerP->numMachines; ++childNum) {
        char command[1024];
        unsigned int startFrame;
        unsigned int nFrames;

        childState[childNum].fps        = -1.0;  /* illegal value as flag */
        childState[childNum].numSeconds = 0;

        allocateInitialFrames(schedulerP, parallelPerfect, forceIalign,
                              framePatternLen, parallelTestFrames,
                              childNum, &startFrame, &nFrames);

        if (nFrames == 0) {
            childState[childNum].finished = TRUE;
            machineDebug("MASTER: No more frames; not starting child '%s'",
                         machineName[childNum]);
        } else {
            childState[childNum].finished   = FALSE;
        
            if (remote[childNum]) {
                if (childrenLeftCurrentIoServer == 0) {
                    startIoServer(encoderName, schedulerP->numMachines, 
                                  masterHostName, masterPortNum, masterSocket,
                                  paramFileName, &ioPortNum[numIoServers++]);
                    
                    childrenLeftCurrentIoServer = SOMAXCONN;
                }
                --childrenLeftCurrentIoServer;
            } 
            pm_snprintf(command, sizeof(command),
                        "%s %s -l %s %s "
                        "%s %s -child %s %d %d %d %d %d %d "
                        "-frames %d %d %s",
                        rsh,
                        machineName[childNum], userName[childNum],
                        beNice ? "nice" : "",
                        executable[childNum],
                        debugMachines ? "-debug_machines" : "",
                        masterHostName, masterPortNum, 
                        remote[childNum] ? ioPortNum[numIoServers-1] : 0,
                        combinePortNum, decodePortNum, childNum,
                        remote[childNum] ? 1 : 0,
                        startFrame, startFrame + nFrames - 1,
                        remote[childNum] ? 
                          remoteParamFile[childNum] : paramFileName
                );
        
            machineDebug("MASTER: Starting child server "
                         "with shell command '%s'", command);

            safe_fork(command);

            machineDebug("MASTER: Frames %d-%d assigned to new child %s",
                         startFrame, startFrame + nFrames - 1, 
                         machineName[childNum]);
        }
        childState[childNum].startFrame = startFrame;
        childState[childNum].lastNumFrames = nFrames;
        childState[childNum].numFrames = childState[childNum].lastNumFrames;
    }
    *childStateP   = childState;
    *numIoServersP = numIoServers;
}



static void
noteFrameDone(const char * const combineHostName,
              int          const combinePortNum,
              unsigned int const frameStart, 
              unsigned int const frameEnd) {
/*----------------------------------------------------------------------------
   Tell the Combine server that frames 'frameStart' through 'frameEnd'
   are done.
-----------------------------------------------------------------------------*/
    int const negativeTwo = -2;
    int clientSocket;
    time_t  tempTimeStart, tempTimeEnd;
    const char * error;
    struct hostent * hostEntP;

    time(&tempTimeStart);

    hostEntP = NULL;

    ConnectToSocket(combineHostName, combinePortNum, &hostEntP,
                    &clientSocket, &error);
    
    if (error)
        errorExit("MASTER: Can't connect to Combine server to tell it frames "
                  "are done.  %s", error);

    WriteInt(clientSocket, negativeTwo);

    WriteInt(clientSocket, frameStart);

    WriteInt(clientSocket, frameEnd);

    close(clientSocket);

    time(&tempTimeEnd);
    IOtime += (tempTimeEnd-tempTimeStart);
}



static void
feedTheChildren(struct scheduler * const schedulerP,
                struct childState        childState[],
                int                const masterSocket,
                const char *       const combineHostName,
                int                const combinePortNum,
                bool               const forceIalign,
                unsigned int       const framePatternLen,
                bool               const goalTimeSpecified,
                unsigned int       const goalTime) {
/*----------------------------------------------------------------------------
   Listen for children to tell us they have finished their assignments
   and give them new assignments, until all the frames have been assigned
   and all the children have finished.

   As children finish assignments, inform the combine server at
   'combineHostName':'combinePortNum' of such.

   Note that the children got initial assigments when they were created.
   So the first thing we do is wait for them to finish those.
-----------------------------------------------------------------------------*/
    unsigned int numFinished;
        /* Number of child machines that have been excused because there
           is no more work for them.
        */
    unsigned int framesDone;

    numFinished = 0;
    framesDone = 0;

    while (numFinished != schedulerP->numMachines) {
        int                 otherSock;
        int                 childNum;
        int                 seconds;
        float               framesPerSecond;
        struct childState * csP;
        const char *        error;
        unsigned int nextFrame;
        unsigned int nFrames;

        machineDebug("MASTER: Listening for a connection...");

        AcceptConnection(masterSocket, &otherSock, &error);
        if (error)
            errorExit("MASTER SERVER: "
                      "Failed to accept next connection.  %s", error);

        ReadInt(otherSock, &childNum);
        ReadInt(otherSock, &seconds);

        csP = &childState[childNum];
        
        csP->numSeconds += seconds;
        csP->fps = (float)csP->numFrames / (float)csP->numSeconds;

        if (seconds != 0)
            framesPerSecond = (float)csP->lastNumFrames / (float)seconds;
        else
            framesPerSecond = (float)csP->lastNumFrames * 2.0;

        machineDebug("MASTER: Child %s FINISHED ASSIGNMENT.  "
                     "%f frames per second", 
                     machineName[childNum], framesPerSecond);

        noteFrameDone(combineHostName, combinePortNum, csP->startFrame,
                      csP->startFrame + csP->lastNumFrames - 1);

        framesDone += csP->lastNumFrames;

        allocateMoreFrames(schedulerP, childNum, childState,
                           forceIalign, framePatternLen,
                           goalTimeSpecified, goalTime,
                           &nextFrame, &nFrames);

        if (nFrames == 0) {
            WriteInt(otherSock, -1);
            WriteInt(otherSock, 0);

            ++numFinished;

            machineDebug("MASTER: NO MORE WORK FOR CHILD %s.  "
                         "(%d of %d children now done)",
                         machineName[childNum], numFinished, numMachines);
        } else {
            WriteInt(otherSock, nextFrame);
            WriteInt(otherSock, nextFrame + nFrames - 1);

            machineDebug("MASTER: Frames %d-%d assigned to child %s",
                         nextFrame, nextFrame + nFrames - 1,
                         machineName[childNum]);

            csP->startFrame    = nextFrame;
            csP->lastNumFrames = nFrames;
            csP->numFrames    += csP->lastNumFrames;
        }
        close(otherSock);

        machineDebug("MASTER: %d/%d DONE; %d ARE ASSIGNED",
                     framesDone, schedulerP->numFramesInJob, 
                     schedulerP->nextFrame - framesDone);
    }
}



static void
stopIoServers(const char * const hostName,
              int          const ioPortNum[],
              unsigned int const numIoServers) {

    unsigned int childNum;

    IOhostName = hostName;
    for (childNum = 0; childNum < numIoServers; ++childNum) {
        ioPortNumber = ioPortNum[childNum];
        EndIOServer();
    }
}



static void
waitForCombineServerToTerminate(int const masterSocket) {

    int otherSock;
    const char * error;

    machineDebug("MASTER SERVER: Waiting for combine server to terminate");

    AcceptConnection(masterSocket, &otherSock, &error);
    if (error)
        errorExit("MASTER SERVER: "
                  "Failed to accept connection expected from a "
                  "terminating combine server.  %s", error);

    {
        int dummy;
        ReadInt(otherSock, &dummy);
    }
    close(otherSock);
}
    


static void
printFinalStats(FILE *            const statfileP,
                time_t            const startUpBegin,
                time_t            const startUpEnd,
                time_t            const shutDownBegin,
                time_t            const shutDownEnd,
                unsigned int      const numChildren,
                struct childState const childState[],
                unsigned int      const numFrames) {

    unsigned int pass;
    FILE * fileP;

    for (pass = 0; pass < 2; ++pass) {
        if (pass == 0)
            fileP = stdout;
        else
            fileP = statfileP;

        if (fileP) {
            unsigned int childNum;
            float totalFPS;

            fprintf(fileP, "\n\n");
            fprintf(fileP, "PARALLEL SUMMARY\n");
            fprintf(fileP, "----------------\n");
            fprintf(fileP, "\n");
            fprintf(fileP, "START UP TIME:  %u seconds\n",
                    (unsigned int)(startUpEnd - startUpBegin));
            fprintf(fileP, "SHUT DOWN TIME:  %u seconds\n",
                    (unsigned int)(shutDownEnd - shutDownBegin));
            
            fprintf(fileP, 
                    "%14.14s %8.8s %8.8s %12.12s %9.9s\n",
                    "MACHINE", "Frames", "Seconds", "Frames/Sec",
                    "Self Time");

            fprintf(fileP, 
                    "%14.14s %8.8s %8.8s %12.12s %9.9s\n",
                    "--------------", "--------", "--------", "------------",
                    "---------");

            totalFPS = 0.0;
            for (childNum = 0; childNum < numChildren; ++childNum) {
                float const localFPS = 
                    (float)childState[childNum].numFrames /
                    childState[childNum].numSeconds;
                fprintf(fileP, "%14.14s %8u %8u %12.4f %8u\n",
                        machineName[childNum], 
                        childState[childNum].numFrames, 
                        childState[childNum].numSeconds,
                        localFPS, 
                        (unsigned int)((float)numFrames/localFPS));
                totalFPS += localFPS;
            }

            fprintf(fileP, 
                    "%14.14s %8.8s %8.8s %12.12s %9.9s\n",
                    "--------------", "--------", "--------", "------------",
                    "---------");

            fprintf(fileP, "%14s %8.8s %8u %12.4f\n", 
                    "OPTIMAL", "", 
                    (unsigned int)((float)numFrames/totalFPS),
                    totalFPS);
            
            {
                unsigned int const diffTime = shutDownEnd - startUpBegin;
                
                fprintf(fileP, "%14s %8.8s %8u %12.4f\n", 
                        "ACTUAL", "", diffTime, 
                        (float)numFrames / diffTime);
            }
            fprintf(fileP, "\n\n");
        }
    }
}



void
MasterServer(struct inputSource * const inputSourceP,
             const char *         const paramFileName, 
             const char *         const outputFileName) {
/*----------------------------------------------------------------------------
   Execute the master server function.

   Start all the other servers.
-----------------------------------------------------------------------------*/
    const char *hostName;
    int       portNum;
    int       masterSocket;
        /* The file descriptor for the socket on which the master listens */
    int ioPortNum[MAX_IO_SERVERS];
    int       combinePortNum, decodePortNum;
    struct childState * childState;  /* malloc'ed */
    unsigned int numIoServers;
    time_t  startUpBegin, startUpEnd;
    time_t  shutDownBegin, shutDownEnd;
    const char * error;
    struct scheduler scheduler;

    time(&startUpBegin);

    scheduler.nextFrame = 0;
    scheduler.numFramesInJob = inputSourceP->numInputFiles;
    scheduler.numMachines = numMachines;

    PrintStartStats(startUpBegin, FALSE, 0, 0, inputSourceP);

    hostName = GetHostName();

    hostEntry = gethostbyname(hostName);
    if (hostEntry == NULL)
        errorExit("Could not find host name '%s' in database", hostName);

    CreateListeningSocket(&masterSocket, &portNum, &error);
    if (error)
        errorExit("Unable to create socket on which to listen.  %s", error);

    if (debugSockets)
        fprintf(stdout, "---MASTER USING PORT %d\n", portNum);

    startCombineServer(encoder_name, numMachines, hostName, portNum,
                       inputSourceP->numInputFiles, 
                       paramFileName, masterSocket, 
                       &combinePortNum);

    if (referenceFrame == DECODED_FRAME)
        startDecodeServer(encoder_name, numMachines, hostName, portNum,
                          inputSourceP->numInputFiles, 
                          paramFileName, masterSocket,
                          &decodePortNum);

    startChildren(&scheduler, encoder_name, hostName, portNum,
                  paramFileName, parallelPerfect, forceIalign,
                  framePatternLen, parallelTestFrames, 
                  niceProcesses,
                  masterSocket, combinePortNum, decodePortNum, 
                  ioPortNum, &numIoServers,
                  &childState);

    time(&startUpEnd);

    feedTheChildren(&scheduler, childState,
                    masterSocket, hostName, combinePortNum,
                    forceIalign, framePatternLen,
                    parallelTimeChunks != -1, parallelTimeChunks);

    assert(scheduler.nextFrame == scheduler.numFramesInJob);

    time(&shutDownBegin);

    stopIoServers(hostName, ioPortNum, numIoServers);

    waitForCombineServerToTerminate(masterSocket);

    close(masterSocket);

    time(&shutDownEnd);

    printFinalStats(statFile, startUpBegin, startUpEnd,
                    shutDownBegin, shutDownEnd, numMachines,
                    childState, inputSourceP->numInputFiles);

    if (statFile)
        fclose(statFile);

    free(childState);
    pm_strfree(hostName);
}



void
NotifyMasterDone(const char * const masterHostName, 
                 int          const masterPortNum, 
                 int          const childNum,
                 unsigned int const seconds, 
                 boolean *    const moreWorkToDoP,
                 int *        const nextFrameStartP,
                 int *        const nextFrameEndP) {
/*----------------------------------------------------------------------------
   Tell the master, at 'masterHostName':'masterPortNum' that child
   number 'childNum' has finished its assignment, and the decoding
   took 'seconds' wall clock seconds.  Get the next assignment, if
   any, from the master.

   If the master gives us a new assignment, return *moreWorkToDoP ==
   TRUE and the frames the master wants us to do as *nextFrameStartP
   and nextFrameEndP.  Otherwise (there is no more work for machine
   'childNum' to do), return *moreWorkToDoP == FALSE.
-----------------------------------------------------------------------------*/
    int    clientSocket;
    time_t tempTimeStart, tempTimeEnd;
    const char * error;

    machineDebug("CHILD: NOTIFYING MASTER Machine %d assignment complete", 
                 childNum);

    time(&tempTimeStart);
    
    ConnectToSocket(masterHostName, masterPortNum, &hostEntry,
                    &clientSocket, &error);
    if (error)
        errorExit("CHILD: Can't connect to master to tell him we've finished "
                  "our assignment.  %s", error);

    WriteInt(clientSocket, childNum);
    WriteInt(clientSocket, seconds);

    ReadInt(clientSocket, nextFrameStartP);
    ReadInt(clientSocket, nextFrameEndP);

    *moreWorkToDoP = (*nextFrameStartP >= 0);

    if (*moreWorkToDoP)
        machineDebug("CHILD: Master says next assignment: start %d end %d",
                     *nextFrameStartP, *nextFrameEndP);
    else
        machineDebug("CHILD: Master says no more work for us.");

    close(clientSocket);

    time(&tempTimeEnd);
    IOtime += (tempTimeEnd-tempTimeStart);
}



void
DecodeServer(int          const numInputFiles, 
             const char * const decodeFileName, 
             const char * const masterHostName, 
             int          const masterPortNum) {
/*----------------------------------------------------------------------------
   Execute the decode server.

   The decode server handles transfer of decoded frames to/from processes.

   It is necessary only if referenceFrame == DECODED_FRAME.

   Communicate to the master at hostname 'masterHostName':'masterPortNum'.

-----------------------------------------------------------------------------*/
    int     otherSock;
    int     decodePortNum;
    int     frameReady;
    boolean *ready;
    int     *waitMachine;
    int     *waitPort;
    int     *waitList;
    int     slaveNumber;
    int     slavePort;
    int     waitPtr;
    struct hostent *nullHost = NULL;
    int     clientSocket;
    const char * error;

    /* should keep list of port numbers to notify when frames become ready */

    ready = (boolean *) calloc(numInputFiles, sizeof(boolean));
    waitMachine = (int *) calloc(numInputFiles, sizeof(int));
    waitPort = (int *) malloc(numMachines*sizeof(int));
    waitList = (int *) calloc(numMachines, sizeof(int));

    CreateListeningSocket(&decodeServerSocket, &decodePortNum, &error);
    if (error)
        errorExit("Unable to create socket on which to listen.  %s", error);

    machineDebug("DECODE SERVER LISTENING ON PORT %d", decodePortNum);

    TransmitPortNum(masterHostName, masterPortNum, decodePortNum);

    frameDone = (boolean *) malloc(numInputFiles*sizeof(boolean));
    memset((char *)frameDone, 0, numInputFiles*sizeof(boolean));

    /* wait for ready signals and requests */
    while ( TRUE ) {
        const char * error;

        AcceptConnection(decodeServerSocket, &otherSock, &error);
        if (error)
            errorExit("DECODE SERVER: "
                      "Failed to accept next connection.  %s", error);

        ReadInt(otherSock, &frameReady);

        if ( frameReady == -2 ) {
            ReadInt(otherSock, &frameReady);

            machineDebug("DECODE SERVER:  REQUEST FOR FRAME %d", frameReady);

            /* now respond if it's ready yet */
            WriteInt(otherSock, frameDone[frameReady]);

            if ( ! frameDone[frameReady] ) {
                /* read machine number, port number */
                ReadInt(otherSock, &slaveNumber);
                ReadInt(otherSock, &slavePort);

                machineDebug("DECODE SERVER: WAITING:  SLAVE %d, PORT %d",
                             slaveNumber, slavePort);

                waitPort[slaveNumber] = slavePort;
                if ( waitMachine[frameReady] == 0 ) {
                    waitMachine[frameReady] = slaveNumber+1;
                } else {
                    /* someone already waiting for this frame */
                    /* follow list of waiters to the end */
                    waitPtr = waitMachine[frameReady]-1;
                    while ( waitList[waitPtr] != 0 ) {
                        waitPtr = waitList[waitPtr]-1;
                    }

                    waitList[waitPtr] = slaveNumber+1;
                    waitList[slaveNumber] = 0;
                }
            }
        } else {
            frameDone[frameReady] = TRUE;
            
            machineDebug("DECODE SERVER:  FRAME %d READY", frameReady);

            if ( waitMachine[frameReady] ) {
                /* need to notify one or more machines it's ready */
                waitPtr = waitMachine[frameReady]-1;
                while ( waitPtr >= 0 ) {
                    const char * error;
                    ConnectToSocket(machineName[waitPtr], waitPort[waitPtr],
                                    &nullHost,
                                    &clientSocket, &error);
                    if (error)
                        errorExit("DECODE SERVER: "
                                  "Can't connect to child machine.  %s", 
                                  error);
                    close(clientSocket);
                    waitPtr = waitList[waitPtr]-1;
                }
            }
        }

        close(otherSock);
    }
    
    machineDebug("DECODE SERVER:  Shutting down");

    /* tell Master server we are done */
    TransmitPortNum(masterHostName, masterPortNum, decodePortNum);

    close(decodeServerSocket);
}



/*
 * 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.
 */