File: yuvscaler.c

package info (click to toggle)
mjpegtools 1%3A2.1.0%2Bdebian-7
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 8,920 kB
  • sloc: ansic: 60,401; cpp: 32,321; sh: 13,910; makefile: 763; python: 291; asm: 103
file content (2119 lines) | stat: -rw-r--r-- 75,002 bytes parent folder | download | duplicates (5)
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
/*
  *  yuvscaler.c
  *  Copyright (C) 2001-2004 Xavier Biquard <xbiquard@free.fr>
  * 
  *  
  *  Scales arbitrary sized yuv frame to yuv frames suitable for VCD, SVCD or specified
  * 
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 2 of the License, or
  *  (at your option) any later version.
  *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
  *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  */
// Implementation: there are two scaling methods: one for not_interlaced output and one for interlaced output. 
// 
// First version doing only downscaling with no interlacing
// June 2001: interlacing capable version
// July 2001: upscaling capable version
// September 2001: line switching
// September/October 2001: new yuv4mpeg header
// October 2001: first MMX part for bicubic
// September/November 2001: what a mess this code! => cleaning and splitting
// December 2001: implementation of time reordering of frames
// January 2002: sample aspect ratio calculation by Matto
// February 2002: interlacing specification now possible. Replaced alloca with malloc
// Mars 2002: sample aspect ratio calculations are back!
// May/June 2002: remove file reading capabilities (do not duplicate lav2yuv), add -O DVD, add color chrominance correction 
// as well as luminance linear reequilibrium. Lots of code cleaning, function renaming, etc...
// Keywords concerning interlacing/preprocessing now under INPUT case
// October 2002: yuvscaler functionnalities not related to image rescaling now part of yuvcorrect
// January 2003: reimplementation of the bicubic algorithm => goes faster
// December-January 2004: First MMX subroutine for bicubic calculus => speed x2
// January-February 2004: make it go even faster
// This first MMX version showed the limits of the use of cspline_w and cspline_h pointers => second
// MMX version will implement dedicated cspline_w and cspline_h pointers for MMX treatment
// 
// 
// TODO:
// no more global variables for librarification

// Remove file reading/writing
// treat the interlace case + specific cases

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <signal.h>
#include "mjpeg_logging.h"
#include "yuv4mpeg.h"
#include "mjpeg_types.h"
#include "yuvscaler.h"
#include "mpegconsts.h"

#ifdef HAVE_ASM_MMX
#include <fcntl.h>
#include "../utils/mmx.h"
#endif

#define yuvscaler_VERSION "11-Dec-2007"
// For pointer address alignement
#define ALIGNEMENT 16		// 16 bytes alignement for mmx registers in SIMD instructions for Pentium
#define MAXWIDTHNEIGHBORS 16

float PI = 3.141592654;


// For input
unsigned int input_width;
unsigned int input_height;
y4m_ratio_t input_sar;		// see yuv4mpeg.h and yuv4mpeg_intern.h for possible values
unsigned int input_useful = 0;	// =1 if specified
unsigned int input_useful_width = 0;
unsigned int input_useful_height = 0;
unsigned int input_discard_col_left = 0;
unsigned int input_discard_col_right = 0;
unsigned int input_discard_line_above = 0;
unsigned int input_discard_line_under = 0;
unsigned int input_black = 0;	//=1 if black borders on input frames
unsigned int input_black_line_above = 0;
unsigned int input_black_line_under = 0;
unsigned int input_black_col_right = 0;
unsigned int input_black_col_left = 0;
unsigned int input_active_height = 0;
unsigned int input_active_width = 0;
uint8_t input_y_min, input_y_max;
float Ufactor, Vfactor, Gamma;

// Downscaling ratios
unsigned int input_height_slice;
unsigned int output_height_slice;
unsigned int input_width_slice;
unsigned int output_width_slice;


// For padded_input
unsigned int padded_width = 0;
unsigned int padded_height = 0;


// For output
unsigned int display_width;
unsigned int display_height;
unsigned int output_width;
unsigned int output_height;
unsigned int output_active_width;
unsigned int output_active_height;
unsigned int output_black_line_above = 0;
unsigned int output_black_line_under = 0;
unsigned int output_black_col_right = 0;
unsigned int output_black_col_left = 0;
unsigned int output_skip_line_above = 0;
unsigned int output_skip_line_under = 0;
unsigned int output_skip_col_right = 0;
unsigned int output_skip_col_left = 0;
unsigned int black = 0, black_line = 0, black_col = 0;	// =1 if black lines must be generated on output
unsigned int skip = 0, skip_line = 0, skip_col = 0;	// =1 if lines or columns from the active output will not be displayed on output frames
// NB: as these number may not be multiple of output_[height,width]_slice, it is not possible to remove the corresponding pixels in
// the input frame, a solution that could speed up things. 
unsigned int vcd = 0;		//=1 if vcd output was selected
unsigned int svcd = 0;		//=1 if svcd output was selected
unsigned int dvd = 0;		//=1 if dvd output was selected

// Global variables
int interlaced = -1;            //=Y4M_ILACE_NONE for not-interlaced scaling, =Y4M_ILACE_TOP_FIRST or Y4M_ILACE_BOT_FIRST for interlaced scaling
int norm = -1;			// =0 for PAL and =1 for NTSC
int wide = 0;			// =1 for wide (16:9) input to standard (4:3) output conversion
int ratio = 0;
int size_keyword = 0;		// =1 is the SIZE keyword has been used
int infile = 0;			// =0 for stdin (default) =1 for file
int algorithm = -1;		// =0 for resample, and =1 for bicubic
unsigned int specific = 0;	// is >0 if a specific downscaling speed enhanced treatment of data is possible
unsigned int mono = 0;		// is =1 for monochrome output

// Keywords for argument passing 
const char VCD_KEYWORD[] = "VCD";
const char HIRESSTILL[]   = "HIRESSTILL";
const char LOSVCDSTILL[]  = "LOSVCDSTILL";
const char LOVCDSTILL[]   = "LOVCDSTILL";
const char SVCD_KEYWORD[] = "SVCD";
const char DVD_KEYWORD[] = "DVD";
const char SIZE_KEYWORD[] = "SIZE_";
const char USE_KEYWORD[] = "USE_";
const char WIDE2STD_KEYWORD[] = "WIDE2STD";
const char INFILE_KEYWORD[] = "INFILE_";
const char RATIO_KEYWORD[] = "RATIO_";
const char MONO_KEYWORD[] = "MONOCHROME";
const char FASTVCD[] = "FASTVCD";
const char FAST_WIDE2VCD[] = "FAST_WIDE2VCD";
const char WIDE2VCD[] = "WIDE2VCD";
const char RESAMPLE[] = "RESAMPLE";
const char BICUBIC[] = "BICUBIC";
const char ACTIVE[] = "ACTIVE";
const char NO_HEADER[] = "NO_HEADER";
const char NOMMX[] = "NOMMX";

// Specific to BICUBIC algorithm
// 2048=2^11
#define FLOAT2INTEGER 2048
#define FLOAT2INTEGERPOWER 11
unsigned int bicubic_div_width = FLOAT2INTEGER, bicubic_div_height =
  FLOAT2INTEGER;
unsigned int multiplicative;


// Unclassified
unsigned long int diviseur;
uint8_t *divide;
unsigned short int *u_i_p;
unsigned int out_nb_col_slice, out_nb_line_slice;
const static char *legal_opt_flags = "k:I:d:n:v:M:m:O:whtg";
int verbose = 1;
#define PARAM_LINE_MAX 256

uint8_t blacky = 16;
uint8_t blackuv = 128;
uint8_t no_header = 0;		// =1 for no stream header output 

#ifdef HAVE_ASM_MMX
int16_t *mmx_padded, *mmx_cubic;
int32_t *mmx_res;
int mmx = 1;			// =1 for mmx activated, =0 for deactivated/not available
#endif

int32_t *intermediate,*intermediate_p,*inter_begin;


// *************************************************************************************
void
yuvscaler_print_usage (char *argv[])
{
  fprintf (stderr,
	   "usage: yuvscaler -I [input_keyword] -M [mode_keyword] -O [output_keyword] [-S 0|1] [-n p|s|n] [-v 0-2] [-h]\n"
	   "yuvscaler UPscales or DOWNscales arbitrary-sized YUV frames coming from stdin (in YUV4MPEG 4:2:2 format)\n"
	   "to a specified YUV frame sizes to stdout. Please use yuvcorrect for interlacing or color corrections\n"
	   "\n"
	   "yuvscaler is keyword driven :\n"
	   "\t -I for keyword concerning INPUT  frame characteristics\n"
	   "\t -M for keyword concerning the scaling MODE of yuvscaler\n"
	   "\t -O for keyword concerning OUTPUT frame characteristics\n"
	   "\n"
	   "Possible input keyword are:\n"
	   "\t USE_WidthxHeight+WidthOffset+HeightOffset to select a useful area of the input frame (all multiple of 2,\n"
	   "\t    Height and HeightOffset multiple of 4 if interlaced), the rest of the image being discarded\n"
	   "\t ACTIVE_WidthxHeight+WidthOffset+HeightOffset to select an active area of the input frame (all multiple of 2,\n"
	   "\t    Height and HeightOffset multiple of 4 if interlaced), the rest of the image being made black\n"
	   "\n"
	   "Possible mode keyword are:\n"
	   "\t BICUBIC       to use the (Mitchell-Netravalli) high-quality bicubic upscaling and/or downscaling algorithm\n"
	   "\t RESAMPLE      to use a classical resampling algorithm -only for downscaling- that goes much faster than bicubic\n"
	   "\t For coherence reason, yuvscaler will use RESAMPLE if only downscaling is necessary, BICUBIC otherwise\n"
	   "\t WIDE2STD      to converts widescreen (16:9) input frames to standard output (4:3), generating necessary black lines\n"
	   "\t RATIO_WidthIn_WidthOut_HeightIn_HeightOut to specified conversion ratios of\n"
	   "\t     WidthIn/WidthOut for width and HeightIN/HeightOut for height to be applied to the useful area.\n"
	   "\t     The output active area that results from scaling the input useful area might be different\n"
	   "\t     from the display area specified thereafter using the -O KEYWORD syntax.\n"
	   "\t     In that case, yuvscaler will automatically generate necessary black lines and columns and/or skip necessary\n"
	   "\t     lines and columns to get an active output centered within the display size.\n"
	   "\t WIDE2VCD      to transcode wide (16:9) frames  to VCD (equivalent to -M WIDE2STD -O VCD)\n"
	   "\t FASTVCD       to transcode full sized frames to VCD (equivalent to -M RATIO_2_1_2_1 -O VCD)\n"
	   "\t FAST_WIDE2VCD to transcode full sized wide (16:9) frames to VCD (-M WIDE2STD -M RATIO_2_1_2_1 -O VCD)\n"
	   "\t NO_HEADER     to suppress stream header generation on output (chaining scaling with different ratios)\n"
	   "\t By default, yuvscaler will use either interlaced or not-interlaced scaling according to the input header interlace information.\n"
	   "\t If this information is missing in the header (cf. mpeg2dec), yuvscaler will use interlaced acaling\n"
	   "\n"
	   "Possible output keywords are:\n"
	   "\t MONOCHROME to generate monochrome frames on output\n"
	   "\t  VCD to generate  VCD compliant frames, taking care of PAL and NTSC standards, not-interlaced/progressive frames\n"
	   "\t SVCD to generate SVCD compliant frames, taking care of PAL and NTSC standards, any interlacing types\n"
	   "\t  DVD to generate  DVD compliant frames, taking care of PAL and NTSC standards, any interlacing types\n"
	   "\t      (SVCD and DVD: if input is not-interlaced/progressive, output interlacing will be taken as top_first)\n"
	   "\t HIRESSTILL to generate HIgh-RESolution STILL images: not-interlaced/progressive frames of size 704x(PAL-576,NTSC-480)\n"
	   "\t LOSVCDSTILL to generate LOw-resolution SVCD still images, not-interlaced/progressive frames, size 480x(PAL-576,NTSC-480)\n"
	   "\t LOVCDSTILL  to generate LOw-resolution  VCD still images, not-interlaced/progressive frames, size 352x(PAL-288,NTSC-240)\n"
	   "\t SIZE_WidthxHeight to generate frames of size WidthxHeight on output (multiple of 2, Height of 4 if interlaced)\n"
	   "\n"
	   "-n  (usually not necessary) if norm could not be determined from data flux, specifies the OUTPUT norm for VCD/SVCD p=pal,s=secam,n=ntsc\n"
	   "-v  Specifies the degree of verbosity: 0=quiet, 1=normal, 2=verbose/debug\n"
	   "-h : print this lot!\n");
  exit (1);
}

// *************************************************************************************


// *************************************************************************************
void
yuvscaler_print_information (y4m_stream_info_t in_streaminfo,
			     y4m_ratio_t frame_rate)
{
  // This function print USER'S INFORMATION
   const char TOP_FIRST[] = "INTERLACED_TOP_FIRST";
   const char BOT_FIRST[] = "INTERLACED_BOTTOM_FIRST";
   const char NOT_INTER[] = "NOT_INTERLACED";
   const char PROGRESSIVE[] = "PROGRESSIVE";

  y4m_log_stream_info (mjpeg_loglev_t("info"), "input: ", &in_streaminfo);

  switch (interlaced)
    {
    case Y4M_ILACE_NONE:
      mjpeg_info ("from %ux%u, take %ux%u+%u+%u, %s/%s",
		  input_width, input_height,
		  input_useful_width, input_useful_height,
		  input_discard_col_left, input_discard_line_above,
		  NOT_INTER, PROGRESSIVE);
      break;
    case Y4M_ILACE_TOP_FIRST:
      mjpeg_info ("from %ux%u, take %ux%u+%u+%u, %s",
		  input_width, input_height,
		  input_useful_width, input_useful_height,
		  input_discard_col_left, input_discard_line_above,
		  TOP_FIRST);
      break;
    case Y4M_ILACE_BOTTOM_FIRST:
      mjpeg_info ("from %ux%u, take %ux%u+%u+%u, %s",
		  input_width, input_height,
		  input_useful_width, input_useful_height,
		  input_discard_col_left, input_discard_line_above,
		  BOT_FIRST);
      break;
    default:
      mjpeg_info ("from %ux%u, take %ux%u+%u+%u",
		  input_width, input_height,
		  input_useful_width, input_useful_height,
		  input_discard_col_left, input_discard_line_above);

    }
  if (input_black == 1)
    {
      mjpeg_info ("with %u and %u black line above and under",
		  input_black_line_above, input_black_line_under);
      mjpeg_info ("and %u and %u black col left and right",
		  input_black_col_left, input_black_col_right);
      mjpeg_info ("%u %u", input_active_width, input_active_height);
    }


   mjpeg_info ("scale to %ux%u, %ux%u being displayed",
	       output_active_width, output_active_height, display_width,
	       display_height);
   
  switch (algorithm)
    {
    case 0:
      mjpeg_info ("Scaling uses the %s algorithm, ", RESAMPLE);
      break;
    case 1:
      mjpeg_info ("Scaling uses the %s algorithm, ", BICUBIC);
      break;
    default:
      mjpeg_error_exit1 ("Unknown algorithm %d", algorithm);
    }


  if (black == 1)
    {
      mjpeg_info ("black lines: %u above and %u under",
		  output_black_line_above, output_black_line_under);
      mjpeg_info ("black columns: %u left and %u right",
		  output_black_col_left, output_black_col_right);
    }
  if (skip == 1)
    {
      mjpeg_info ("skipped lines: %u above and %u under",
		  output_skip_line_above, output_skip_line_under);
      mjpeg_info ("skipped columns: %u left and %u right",
		  output_skip_col_left, output_skip_col_right);
    }
  mjpeg_info ("frame rate: %.3f fps", Y4M_RATIO_DBL (frame_rate));

}

// *************************************************************************************


// *************************************************************************************
uint8_t
yuvscaler_nearest_integer_division (unsigned long int p, unsigned long int q)
{
  // This function returns the nearest integer of the ratio p/q. 
  // As this ratio in yuvscaler corresponds to a pixel value, it should be between 0 and 255
  unsigned long int ratio = p / q;
  unsigned long int reste = p % q;
  unsigned long int frontiere = q - q / 2;	// Do **not** change this into q/2 => it is not the same for odd q numbers

  if (reste >= frontiere)
    ratio++;

  if ((ratio < 0) || (ratio > 255))
    mjpeg_error_exit1 ("Division error: %lu/%lu not in [0;255] range !!\n", p,
		       q);
  return ((uint8_t) ratio);
}

// *************************************************************************************


// *************************************************************************************
static y4m_ratio_t
yuvscaler_calculate_output_sar (int out_w, int out_h,
				int in_w, int in_h, y4m_ratio_t in_sar)
{
// This function calculates the sample aspect ratio (SAR) for the output stream,
//    given the input->output scale factors, and the input SAR.
  if (Y4M_RATIO_EQL (in_sar, y4m_sar_UNKNOWN))
    {
      return y4m_sar_UNKNOWN;
    }
  else
    {
      y4m_ratio_t out_sar;
      /*
         out_SAR_w     in_SAR_w    input_W   output_H
         ---------  =  -------- *  ------- * --------
         out_SAR_h     in_SAR_h    input_H   output_W
       */
      out_sar.n = in_sar.n * in_w * out_h;
      out_sar.d = in_sar.d * in_h * out_w;
      y4m_ratio_reduce (&out_sar);
      return out_sar;
    }
}

// *************************************************************************************


// *************************************************************************************
int
yuvscaler_y4m_read_frame (int fd, y4m_stream_info_t *si, 
			y4m_frame_info_t * frameinfo,
			unsigned long int buflen, uint8_t * buf)
{
  // This function reads a frame from input stream. It does the same thing as the y4m_read_frame function (from yuv4mpeg.c)
  // May be replaced directly by it in the near future
  static int err = Y4M_OK;
   if ((err = y4m_read_frame_header (fd, si, frameinfo)) == Y4M_OK)
     {
	if ((err = y4m_read (fd, buf, buflen)) != Y4M_OK)
	  {
	     mjpeg_info ("Couldn't read FRAME content: %s!",
			 y4m_strerr (err));
	     return (err);
	  }
     }
   else
     {
	if (err != Y4M_ERR_EOF)
	  mjpeg_info ("Couldn't read FRAME header: %s!", y4m_strerr (err));
	else
	  mjpeg_info ("End of stream!");
	return (err);
     }
   return Y4M_OK;
}

// *************************************************************************************


// *************************************************************************************
// PREPROCESSING
// *************************************************************************************
int
blackout (uint8_t * input_y, uint8_t * input_u, uint8_t * input_v)
{
  // The blackout function makes input borders pixels become black
  unsigned int line;
  uint8_t *right;
  // Y COMPONENT

  for (line = 0; line < input_black_line_above; line++)
    {
      memset (input_y, blacky, input_useful_width);
      input_y += input_width;
    }
  right = input_y + input_black_col_left + input_active_width;
  for (line = 0; line < input_active_height; line++)
    {
      memset (input_y, blacky, input_black_col_left);
      memset (right, blacky, input_black_col_right);
      input_y += input_width;
      right += input_width;
    }
  for (line = 0; line < input_black_line_under; line++)
    {
      memset (input_y, blacky, input_useful_width);
      input_y += input_width;
    }
  // U COMPONENT
  for (line = 0; line < (input_black_line_above >> 1); line++)
    {
      memset (input_u, blackuv, input_useful_width >> 1);
      input_u += input_width >> 1;
    }
  right = input_u + ((input_black_col_left + input_active_width) >> 1);
  for (line = 0; line < (input_active_height >> 1); line++)
    {
      memset (input_u, blackuv, input_black_col_left >> 1);
      memset (right, blackuv, input_black_col_right >> 1);
      input_u += input_width >> 1;
      right += input_width >> 1;
    }
  for (line = 0; line < (input_black_line_under >> 1); line++)
    {
      memset (input_u, blackuv, input_useful_width >> 1);
      input_u += input_width >> 1;
    }
  // V COMPONENT
  for (line = 0; line < (input_black_line_above >> 1); line++)
    {
      memset (input_v, blackuv, input_useful_width >> 1);
      input_v += input_width >> 1;
    }
  right = input_v + ((input_black_col_left + input_active_width) >> 1);
  for (line = 0; line < (input_active_height >> 1); line++)
    {
      memset (input_v, blackuv, input_black_col_left >> 1);
      memset (right, blackuv, input_black_col_right >> 1);
      input_v += input_width >> 1;
      right += input_width >> 1;
    }
  for (line = 0; line < (input_black_line_under >> 1); line++)
    {
      memset (input_v, blackuv, input_useful_width >> 1);
      input_v += input_width >> 1;
    }
  return (0);
}

// *************************************************************************************


// *************************************************************************************
void
handle_args_global (int argc, char *argv[])
{
  // This function takes care of the global variables 
  // initialisation that are independent of the input stream
  // The main goal is to know whether input frames originate from file or stdin
  int c;

  while ((c = getopt (argc, argv, legal_opt_flags)) != -1)
    {
      switch (c)
	{
	case 'v':
	  verbose = atoi (optarg);
	  if (verbose < 0 || verbose > 2)
	    {
	      mjpeg_error_exit1 ("Verbose level must be [0..2]");
	    }
	  break;


	case 'n':		// TV norm for SVCD/VCD output
	  switch (*optarg)
	    {
	    case 'p':
	    case 's':
	      norm = 0;
	      break;
	    case 'n':
	      norm = 1;
	      break;
	    default:
	      mjpeg_error_exit1 ("Illegal norm letter specified: %c",
				 *optarg);
	    }
	  break;


	case 'h':
//      case '?':
	  yuvscaler_print_usage (argv);
	  break;

	default:
	  break;
	}

    }
  if (optind != argc)
    yuvscaler_print_usage (argv);

}


// *************************************************************************************


// *************************************************************************************
void
handle_args_dependent (int argc, char *argv[])
{
  // This function takes care of the global variables 
  // initialisation that may depend on the input stream
  // It does also coherence check on input, useful_input, display, output_active sizes and ratio sizes
  int c;
  unsigned int ui1, ui2, ui3, ui4;
  int output, input, mode;

  // By default, display sizes is the same as input size
  display_width = input_width;
  display_height = input_height;

  optind = 1;
  while ((c = getopt (argc, argv, legal_opt_flags)) != -1)
    {
      switch (c)
	{


	  // **************               
	  // OUTPUT KEYWORD
	  // **************               
	case 'O':
	  output = 0;
	  if (strcmp (optarg, VCD_KEYWORD) == 0)
	    {
	      output = 1;
	      vcd = 1;
	      svcd = 0;		// if user gives VCD, SVCD and DVD keywords, take last one only into account
	      dvd = 0;
	      display_width = 352;
	      if (norm == 0)
		{
		  mjpeg_info
		    ("VCD output format requested in PAL/SECAM norm");
		  display_height = 288;
		}
	      else if (norm == 1)
		{
		  mjpeg_info ("VCD output format requested in NTSC norm");
		  display_height = 240;
		}
	      else
		mjpeg_error_exit1
		  ("No norm specified, cannot determine VCD output size. Please use the -n option!");
	    }
	  if (strcmp (optarg, SVCD_KEYWORD) == 0)
	    {
	      output = 1;
	      svcd = 1;
	      vcd = 0;		// if user gives VCD, SVCD and DVD keywords, take last one only into account
	      dvd = 0;
	      display_width = 480;
	      if (norm == 0)
		{
		  mjpeg_info
		    ("SVCD output format requested in PAL/SECAM norm");
		  display_height = 576;
		}
	      else if (norm == 1)
		{
		  mjpeg_info ("SVCD output format requested in NTSC norm");
		  display_height = 480;
		}
	      else
		mjpeg_error_exit1
		  ("No norm specified, cannot determine SVCD output size. Please use the -n option!");
	    }
	  if (strcmp (optarg, DVD_KEYWORD) == 0)
	    {
	      output = 1;
	      vcd = 0;
	      svcd = 0;		// if user gives VCD, SVCD and DVD keywords, take last one only into account
	      dvd = 1;
	      display_width = 720;
	      if (norm == 0)
		{
		  mjpeg_info
		    ("DVD output format requested in PAL/SECAM norm");
		  display_height = 576;
		}
	      else if (norm == 1)
		{
		  mjpeg_info ("DVD output format requested in NTSC norm");
		  display_height = 480;
		}
	      else
		mjpeg_error_exit1
		  ("No norm specified, cannot determine DVD output size. Please use the -n option!");
	    }
	  if (strncmp (optarg, SIZE_KEYWORD, 5) == 0)
	    {
	      output = 1;
	      if (sscanf (optarg, "SIZE_%ux%u", &ui1, &ui2) == 2)
		{
		  // Coherence check: sizes must be multiple of 2
		  if ((ui1 % 2 == 0) && (ui2 % 2 == 0))
		    {
		      display_width = ui1;
		      display_height = ui2;
		      size_keyword = 1;
		    }
		  else
		    mjpeg_error_exit1
		      ("Unconsistent SIZE keyword, not multiple of 2: %s",
		       optarg);
		  // A second check will eventually be done when output interlacing is finally known
		}
	      else
		mjpeg_error_exit1
		  ("Wrong number of argument to SIZE keyword: %s", optarg);
	    }
	  // Theoritically, this should go into yuvcorrect, but I hesitate to do so
	  if (strcmp (optarg, HIRESSTILL) == 0)
	    {
	      output = 1;
	      interlaced = Y4M_ILACE_NONE;
	      display_width = 704;
	      if (norm == 0)
		{
		  mjpeg_info
		    ("HIRESSTILL output format requested in PAL/SECAM norm");
		  display_height = 576;
		}
	      else if (norm == 1)
		{
		  mjpeg_info ("HIRESSTILL output format requested in NTSC norm");
		  display_height = 480;
		}
	      else
		mjpeg_error_exit1
		  ("No norm specified, cannot determine HIRESSTILL output size. Please use the -n option!");
	    }
	   if (strcmp (optarg, LOSVCDSTILL) == 0)
	    {
	      output = 1;
	      interlaced = Y4M_ILACE_NONE;
	      display_width = 480;
	      if (norm == 0)
		{
		  mjpeg_info
		    ("LOSVCDSTILL output format requested in PAL/SECAM norm");
		  display_height = 576;
		}
	      else if (norm == 1)
		{
		  mjpeg_info ("LOSVCDSTILL output format requested in NTSC norm");
		  display_height = 480;
		}
	      else
		mjpeg_error_exit1
		  ("No norm specified, cannot determine LOSVCDSTILL output size. Please use the -n option!");
	    }
	  if (strcmp (optarg, LOVCDSTILL) == 0)
	    {
	      output = 1;
	      interlaced = Y4M_ILACE_NONE;
	      display_width = 352;
	      if (norm == 0)
		{
		  mjpeg_info
		    ("LOVCDSTILL output format requested in PAL/SECAM norm");
		  display_height = 288;
		}
	      else if (norm == 1)
		{
		  mjpeg_info ("LOVCDSTILL output format requested in NTSC norm");
		  display_height = 240;
		}
	      else
		mjpeg_error_exit1
		  ("No norm specified, cannot determine LOVCDSTILL output size. Please use the -n option!");
	    }
	  if (strcmp (optarg, MONO_KEYWORD) == 0)
	    {
	      output = 1;
	      mono = 1;
	    }

	  if (output == 0)
	    mjpeg_error_exit1 ("Uncorrect output keyword: %s", optarg);
	  break;



	  // **************            
	  // MODE KEYOWRD
	  // *************
	case 'M':
	  mode = 0;

	   
	   if (strcmp (optarg, WIDE2STD_KEYWORD) == 0)
	    {
	      wide = 1;
	      mode = 1;
	    }
	   // developper's Testing purpose only
	   if (strcmp (optarg, NOMMX) == 0)
	    {
#ifdef HAVE_ASM_MMX	       
	      mmx = 0;
#endif	       
	      mode = 1;
	    }
	  if (strcmp (optarg, RESAMPLE) == 0)
	    {
	      mode = 1;
	      algorithm = 0;
	    }
	  if (strcmp (optarg, BICUBIC) == 0)
	    {
	      mode = 1;
	      algorithm = 1;
	    }
	  if (strcmp (optarg, NO_HEADER) == 0)
	    {
	      mode = 1;
	      no_header = 1;
	    }
	  if (strncmp (optarg, RATIO_KEYWORD, 6) == 0)
	    {
	      if (sscanf (optarg, "RATIO_%u_%u_%u_%u", &ui1, &ui2, &ui3, &ui4)
		  == 4)
		{
		  // A coherence check will be done when the useful input sizes are known
		  ratio = 1;
		  mode = 1;
		  input_width_slice = ui1;
		  output_width_slice = ui2;
		  input_height_slice = ui3;
		  output_height_slice = ui4;
		}
	      if (ratio == 0)
		mjpeg_error_exit1 ("Unconsistent RATIO keyword: %s", optarg);
	    }

	  if (strcmp (optarg, FAST_WIDE2VCD) == 0)
	    {
	      wide = 1;
	      mode = 1;
	      ratio = 1;
	      input_width_slice = 2;
	      output_width_slice = 1;
	      input_height_slice = 2;
	      output_height_slice = 1;
	      vcd = 1;
	      svcd = 0;		// if user gives VCD and SVCD keyword, take last one only into account
	      display_width = 352;
	      if (norm == 0)
		{
		  mjpeg_info
		    ("VCD output format requested in PAL/SECAM norm");
		  display_height = 288;
		}
	      else if (norm == 1)
		{
		  mjpeg_info ("VCD output format requested in NTSC norm");
		  display_height = 240;
		}
	      else
		mjpeg_error_exit1
		  ("No norm specified, cannot determine VCD output size. Please use the -n option!");
	    }

	  if (strcmp (optarg, WIDE2VCD) == 0)
	    {
	      wide = 1;
	      mode = 1;
	      vcd = 1;
	      svcd = 0;		// if user gives VCD and SVCD keyword, take last one only into account
	      display_width = 352;
	      if (norm == 0)
		{
		  mjpeg_info
		    ("VCD output format requested in PAL/SECAM norm");
		  display_height = 288;
		}
	      else if (norm == 1)
		{
		  mjpeg_info ("VCD output format requested in NTSC norm");
		  display_height = 240;
		}
	      else
		mjpeg_error_exit1
		  ("No norm specified, cannot determine VCD output size. Please use the -n option!");
	    }

	  if (strcmp (optarg, FASTVCD) == 0)
	    {
	      mode = 1;
	      vcd = 1;
	      svcd = 0;		// if user gives VCD and SVCD keyword, take last one only into account
	      ratio = 1;
	      input_width_slice = 2;
	      output_width_slice = 1;
	      input_height_slice = 2;
	      output_height_slice = 1;
	      display_width = 352;
	      if (norm == 0)
		{
		  mjpeg_info
		    ("VCD output format requested in PAL/SECAM norm");
		  display_height = 288;
		}
	      else if (norm == 1)
		{
		  mjpeg_info ("VCD output format requested in NTSC norm");
		  display_height = 240;
		}
	      else
		mjpeg_error_exit1
		  ("No norm specified, cannot determine VCD output size. Please use the -n option!");
	    }

	  if (mode == 0)
	    mjpeg_error_exit1 ("Uncorrect mode keyword: %s", optarg);
	  break;



	  // **************            
	  // INPUT KEYOWRD
	  // *************
	case 'I':
	  input = 0;
	  if (strncmp (optarg, USE_KEYWORD, 4) == 0)
	    {
	      input = 1;
	      if (sscanf (optarg, "USE_%ux%u+%u+%u", &ui1, &ui2, &ui3, &ui4)
		  == 4)
		{
		  // Coherence check: 
		  // every values must be multiple of 2
		  // and if input is interlaced, height offsets must be multiple of 4
		  // since U and V have half Y resolution and are interlaced
		  // and the required zone must be inside the input size
		  if ((ui1 % 2 == 0) && (ui2 % 2 == 0) && (ui3 % 2 == 0)
		      && (ui4 % 2 == 0) && (ui1 + ui3 <= input_width)
		      && (ui2 + ui4 <= input_height))
		    {
		      input_useful_width = ui1;
		      input_useful_height = ui2;
		      input_discard_col_left = ui3;
		      input_discard_line_above = ui4;
		      input_discard_col_right =
			input_width - input_useful_width -
			input_discard_col_left;
		      input_discard_line_under =
			input_height - input_useful_height -
			input_discard_line_above;
		      input_useful = 1;
		    }
		  else
		    mjpeg_error_exit1
		      ("Unconsistent USE keyword: %s, offsets/sizes not multiple of 2 or offset+size>input size",
		       optarg);
		  if (interlaced != Y4M_ILACE_NONE)
		    {
		      if ((input_useful_height % 4 != 0)
			  || (input_discard_line_above % 4 != 0))
			mjpeg_error_exit1
			  ("Unconsistent USE keyword: %s, height offset or size not multiple of 4 but input is interlaced!!",
			   optarg);
		    }

		}
	       else
		 mjpeg_error_exit1
		 ("Uncorrect USE input flag argument: %s", optarg);
	    }
	  if (strncmp (optarg, ACTIVE, 6) == 0)
	    {
	      input = 1;
	      if (sscanf
		  (optarg, "ACTIVE_%ux%u+%u+%u", &ui1, &ui2, &ui3, &ui4) == 4)
		{
		  // Coherence check : offsets must be multiple of 2 since U and V have half Y resolution 
		  // if interlaced, height must be multiple of 4
		  // and the required zone must be inside the input size
		  if ((ui1 % 2 == 0) && (ui2 % 2 == 0) && (ui3 % 2 == 0)
		      && (ui4 % 2 == 0) && (ui1 + ui3 <= input_width)
		      && (ui2 + ui4 <= input_height))
		    {
		      input_active_width = ui1;
		      input_active_height = ui2;
		      input_black_col_left = ui3;
		      input_black_line_above = ui4;
		      input_black_col_right =
			input_width - input_active_width -
			input_black_col_left;
		      input_black_line_under =
			input_height - input_active_height -
			input_black_line_above;
		      input_black = 1;
		    }
		  else
		    mjpeg_error_exit1
		      ("Unconsistent ACTIVE keyword: %s, offsets/sizes not multiple of 2 or offset+size>input size",
		       optarg);
		  if (interlaced != Y4M_ILACE_NONE)
		    {
		      if ((input_active_height % 4 != 0)
			  || (input_black_line_above % 4 != 0))
			mjpeg_error_exit1
			  ("Unconsistent ACTIVE keyword: %s, height offset or size not multiple of 4 but input is interlaced!!",
			   optarg);
		    }

		}
	      else
		mjpeg_error_exit1
		  ("Uncorrect ACTIVE input flag argument: %s", optarg);
	    }
	  if (input == 0)
	    mjpeg_error_exit1 ("Uncorrect input keyword: %s", optarg);
	  break;

	default:
	   break;
	}
    }

// Interlacing warnings
  if (vcd == 1)
    {
       if ((interlaced == Y4M_ILACE_TOP_FIRST)
	   || (interlaced == Y4M_ILACE_BOTTOM_FIRST))
	 mjpeg_warn
	 ("Interlaced input frames will be downscaled to non-interlaced VCD frames\nIf quality is an issue, please consider deinterlacing input frames with yuvdeinterlace");
       interlaced = Y4M_ILACE_NONE;
    }


  // Size Keyword final coherence check
  if ((interlaced != Y4M_ILACE_NONE) && (size_keyword == 1))
    {
      if (display_height % 4 != 0)
	mjpeg_error_exit1
	  ("Unconsistent SIZE keyword, Height is not multiple of 4 but output interlaced!!");
    }

  // Unspecified input variables specification
  if (input_useful_width == 0)
    input_useful_width = input_width;
  if (input_useful_height == 0)
    input_useful_height = input_height;


  // Ratio coherence check against input_useful size
  if (ratio == 1)
    {
      if ((input_useful_width % input_width_slice == 0)
	  && (input_useful_height % input_height_slice == 0))
	{
	  output_active_width =
	    (input_useful_width / input_width_slice) * output_width_slice;
	  output_active_height =
	    (input_useful_height / input_height_slice) * output_height_slice;
	}
      else
	mjpeg_error_exit1
	  ("Specified input ratios (%u and %u) does not divide input useful size (%u and %u)!",
	   input_width_slice, input_height_slice, input_useful_width,
	   input_useful_height);
    }

  // if USE and ACTIVE keywords were used, redefined input ACTIVE size relative to USEFUL zone
  if ((input_black == 1) && (input_useful == 1))
    {
      input_black_line_above =
	input_black_line_above >
	input_discard_line_above ? input_black_line_above -
	input_discard_line_above : 0;
      input_black_line_under =
	input_black_line_under >
	input_discard_line_under ? input_black_line_under -
	input_discard_line_under : 0;
      input_black_col_left =
	input_black_col_left >
	input_discard_col_left ? input_black_col_left -
	input_discard_col_left : 0;
      input_black_col_right =
	input_black_col_right >
	input_discard_col_right ? input_black_col_right -
	input_discard_col_right : 0;
      input_active_width =
	input_useful_width - input_black_col_left - input_black_col_right;
      input_active_height =
	input_useful_height - input_black_line_above - input_black_line_under;
      if ((input_active_width == input_useful_width)
	  && (input_active_height == input_useful_height))
	input_black = 0;	// black zone is not enterely inside useful zone
    }


  // Unspecified output variables specification
  if (output_active_width == 0)
    output_active_width = display_width;
  if (output_active_height == 0)
    output_active_height = display_height;
//  if (display_width == 0)
//    display_width = output_active_width;
//  if (display_height == 0)
//    display_height = output_active_height;

  if (wide == 1)
    output_active_height = (output_active_height * 3) / 4;
  // Common pitfall! it is 3/4 not 9/16!
  // Indeed, Standard ratio is 4:3, so 16:9 has an height that is 3/4 smaller than the display_height

  // At this point, input size, input_useful size, output_active size and display size are specified
  // Time for the final coherence check and black and skip initialisations
  // Final check
  output_width =
    output_active_width > display_width ? output_active_width : display_width;
  output_height =
    output_active_height >
    display_height ? output_active_height : display_height;
  if (interlaced == Y4M_ILACE_NONE) 
     {
	if ((output_active_width % 2 !=0) || (output_active_height % 2 != 0)
	    || (display_width % 2 != 0) || (display_height % 2 != 0))
	  mjpeg_error_exit1
	  ("Output sizes are not multiple of 2 !!! %ux%u, %ux%u being displayed",
	   output_active_width, output_active_height, display_width,
	   display_height);
     }
   else
     {
	if ((output_active_width % 2 != 0) || (output_active_height % 4 != 0)
	    || (display_width % 2 != 0) || (display_height % 4 != 0))
	  mjpeg_error_exit1
	  ("Output sizes are not multiple of 2 on width and 4 on height (interlaced)! %ux%u, %ux%u being displayed",
	   output_active_width, output_active_height, display_width,
	   display_height);
     }
   
	// Skip and black initialisations
  // 
  if (output_active_width > display_width)
    {
      skip = 1;
      skip_col = 1;
      // output_skip_col_right and output_skip_col_left must be even numbers
      output_skip_col_right = ((output_active_width - display_width) / 4)*2;
      output_skip_col_left =
	output_active_width - display_width - output_skip_col_right;
    }
  if (output_active_width < display_width)
    {
      black = 1;
      black_col = 1;
      // output_black_col_right and output_black_col_left must be even numbers
      output_black_col_right = ((display_width - output_active_width) / 4)*2;
      output_black_col_left =
	display_width - output_active_width - output_black_col_right;
    }
  if (output_active_height > display_height)
    {
      skip = 1;
      skip_line = 1;
      // output_skip_line_above and output_skip_line_under must be even numbers
      output_skip_line_above = ((output_active_height - display_height) / 4)*2;
      output_skip_line_under =
	output_active_height - display_height - output_skip_line_above;
    }
  if (output_active_height < display_height)
    {
      black = 1;
      black_line = 1;
      // output_black_line_above and output_black_line_under must be even numbers
      output_black_line_above = ((display_height - output_active_height) / 4)*2;
      output_black_line_under =
	display_height - output_active_height - output_black_line_above;
    }
}



// *************************************************************************************
// MAIN
// *************************************************************************************
int
main (int argc, char *argv[])
{
  int input_fd = 0;
  int output_fd = 1;

//  DDD and time use
//   int input_fd  = open("./yuvscaler.input",O_RDONLY);
//   int output_fd = open("./yuvscaler.output",O_WRONLY);
// DDD use

  int err = Y4M_OK, nb;
  unsigned long int i, j, h, w;

  long int frame_num = 0;
  unsigned int *height_coeff = NULL, *width_coeff = NULL;
  uint8_t *input = NULL, *output = NULL,
    *padded_input = NULL, *padded_bottom = NULL, *padded_top = NULL;
  uint8_t *input_y, *input_u, *input_v;
  uint8_t *output_y, *output_u, *output_v;
  uint8_t *frame_y, *frame_u, *frame_v;
  uint8_t **frame_y_p = NULL, **frame_u_p = NULL, **frame_v_p = NULL;	// size is not yet known => pointer of pointer
  uint8_t *u_c_p;		//u_c_p = uint8_t pointer
  unsigned int divider;

  // SPECIFIC TO BICUBIC
  unsigned int *in_line = NULL, *in_col = NULL, out_line, out_col;
  unsigned long int somme;
  float *a = NULL, *b = NULL;
  int16_t *cspline_w=NULL,*cspline_h=NULL;
  uint16_t width_offset=0,height_offset=0,left_offset=0,top_offset=0,right_offset=0,bottom_offset=0;
  uint16_t height_pad=0,width_pad=0,width_neighbors=0,height_neighbors=0;
   // On constate que souvent, le dernier coeff cspline est nul => 
   // pas la peine de le prendre en compte dans les calculs
   // Attention ! optimisation vitesse yuvscaler_bicubic.c suppose que zero_width_neighbors=0 ou 1 seulement
  uint8_t zero_width_neighbors=1,zero_height_neighbors=1;
  float width_scale,height_scale;
  int16_t cspline_value = 0;
  int16_t *pointer;
     

  // SPECIFIC TO YUV4MPEG 
  unsigned long int nb_pixels;
  y4m_frame_info_t frameinfo;
  y4m_stream_info_t in_streaminfo;
  y4m_stream_info_t out_streaminfo;
  y4m_ratio_t frame_rate = y4m_fps_UNKNOWN;

  // Initialisation of global variables that are independent of the input stream, input_file in particular
  handle_args_global (argc, argv);

  // Information output
  if (verbose)
     {
     mjpeg_info ("yuvscaler %s %s", PACKAGE_VERSION, yuvscaler_VERSION);
     mjpeg_info ("(C) 2001-2004 Xavier Biquard <xbiquard@free.fr>, yuvscaler -h for help, or man yuvscaler");
     }

  // mjpeg tools global initialisations
  mjpeg_default_handler_verbosity (verbose);
  y4m_init_stream_info (&in_streaminfo);
  y4m_init_stream_info (&out_streaminfo);
  y4m_init_frame_info (&frameinfo);


  // ***************************************************************
  // Get video stream informations (size, framerate, interlacing, sample aspect ratio).
  // The in_streaminfo structure is filled in accordingly 
  // ***************************************************************
  if (y4m_read_stream_header (input_fd, &in_streaminfo) != Y4M_OK)
    mjpeg_error_exit1 ("Could'nt read YUV4MPEG header!");
  input_width = y4m_si_get_width (&in_streaminfo);
  input_height = y4m_si_get_height (&in_streaminfo);
  frame_rate = y4m_si_get_framerate (&in_streaminfo);
  interlaced = y4m_si_get_interlace (&in_streaminfo);
  // ***************************************************************


  // INITIALISATIONS
  // Norm determination from header (this has precedence over user's specification through the -n flag)
  if (Y4M_RATIO_EQL (frame_rate, y4m_fps_PAL))
    norm = 0;
  if (Y4M_RATIO_EQL (frame_rate, y4m_fps_NTSC))
    norm = 1;
  if (norm < 0)
    {
      mjpeg_warn
	("Could not infer norm (PAL/SECAM or NTSC) from input data (frame size=%dx%d, frame rate=%d:%d fps)!!",
	 input_width, input_height, frame_rate.n, frame_rate.d);
    }



  // Deal with args that depend on input stream
  handle_args_dependent (argc, argv);

  // Scaling algorithm determination
  if ((algorithm == 0) || (algorithm == -1))
    {
      // Coherences check: resample can only downscale not upscale
      if ((input_useful_width < output_active_width)
	  || (input_useful_height < output_active_height))
	{
	  if (algorithm == 0)
	    mjpeg_info
	      ("Resampling algorithm can only downscale, not upscale => switching to bicubic algorithm");
	  algorithm = 1;
	}
      else
	algorithm = 0;
    }

  // USER'S INFORMATION OUTPUT
  yuvscaler_print_information (in_streaminfo, frame_rate);

  divider = pgcd (input_useful_width, output_active_width);
  input_width_slice = input_useful_width / divider;
  output_width_slice = output_active_width / divider;
  mjpeg_debug ("divider,i_w_s,o_w_s = %d,%d,%d",
	       divider, input_width_slice, output_width_slice);

  divider = pgcd (input_useful_height, output_active_height);
  input_height_slice = input_useful_height / divider;
  output_height_slice = output_active_height / divider;
  mjpeg_debug ("divider,i_w_s,o_w_s = %d,%d,%d",
	       divider, input_height_slice, output_height_slice);

  diviseur = input_height_slice * input_width_slice;
  mjpeg_debug ("Diviseur=%ld", diviseur);

  mjpeg_info ("Scaling ratio for width is %u to %u",
	      input_width_slice, output_width_slice);
  mjpeg_info ("and is %u to %u for height", input_height_slice,
	      output_height_slice);


  // Now that we know about scaling ratios, we can optimize treatment of an active input zone:
  // we must also check final new size is multiple of 2 on width and 2 or 4 on height
  if (input_black == 1)
    {
      if (((nb = input_black_line_above / input_height_slice) > 0)
	  && ((nb * input_height_slice) % 2 == 0))
	{
	  if (interlaced == Y4M_ILACE_NONE)
	    {
	      input_useful = 1;
	      black = 1;
	      black_line = 1;
	      output_black_line_above += nb * output_height_slice;
	      input_black_line_above -= nb * input_height_slice;
	      input_discard_line_above += nb * input_height_slice;
	    }
	  if ((interlaced != Y4M_ILACE_NONE)
	      && ((nb * input_height_slice) % 4 == 0))
	    {
	      input_useful = 1;
	      black = 1;
	      black_line = 1;
	      output_black_line_above += nb * output_height_slice;
	      input_black_line_above -= nb * input_height_slice;
	      input_discard_line_above += nb * input_height_slice;
	    }
	}
      if (((nb = input_black_line_under / input_height_slice) > 0)
	  && ((nb * input_height_slice) % 2 == 0))
	{
	  if (interlaced == Y4M_ILACE_NONE)
	    {
	      input_useful = 1;
	      black = 1;
	      black_line = 1;
	      output_black_line_under += nb * output_height_slice;
	      input_black_line_under -= nb * input_height_slice;
	      input_discard_line_under += nb * input_height_slice;
	    }
	  if ((interlaced != Y4M_ILACE_NONE)
	      && ((nb * input_height_slice) % 4 == 0))
	    {
	      input_useful = 1;
	      black = 1;
	      black_line = 1;
	      output_black_line_under += nb * output_height_slice;
	      input_black_line_under -= nb * input_height_slice;
	      input_discard_line_under += nb * input_height_slice;
	    }
	}
      if (((nb = input_black_col_left / input_width_slice) > 0)
	  && ((nb * input_height_slice) % 2 == 0))
	{
	  input_useful = 1;
	  black = 1;
	  black_col = 1;
	  output_black_col_left += nb * output_width_slice;
	  input_black_col_left -= nb * input_width_slice;
	  input_discard_col_left += nb * input_width_slice;
	}
      if (((nb = input_black_col_right / input_width_slice) > 0)
	  && ((nb * input_height_slice) % 2 == 0))
	{
	  input_useful = 1;
	  black = 1;
	  black_col = 1;
	  output_black_col_right += nb * output_width_slice;
	  input_black_col_right -= nb * input_width_slice;
	  input_discard_col_right += nb * input_width_slice;
	}
      input_useful_height =
	input_height - input_discard_line_above - input_discard_line_under;
      input_useful_width =
	input_width - input_discard_col_left - input_discard_col_right;
      input_active_width =
	input_useful_width - input_black_col_left - input_black_col_right;
      input_active_height =
	input_useful_height - input_black_line_above - input_black_line_under;
      if ((input_active_width == input_useful_width)
	  && (input_active_height == input_useful_height))
	input_black = 0;	// black zone doesn't go beyong useful zone
      output_active_width =
	(input_useful_width / input_width_slice) * output_width_slice;
      output_active_height =
	(input_useful_height / input_height_slice) * output_height_slice;

      // USER'S INFORMATION OUTPUT
      mjpeg_info (" --- Newly speed optimized parameters ---");
      yuvscaler_print_information (in_streaminfo, frame_rate);
    }

   
   // Take care of the case where ratios are 1:1 and 1:1 => in the resample algorithm category by convention
   if ((output_height_slice == 1) && (input_height_slice == 1)
	  && (output_width_slice == 1) && (input_width_slice == 1)) 
     algorithm =0;


  // RESAMPLE RESAMPLE RESAMPLE   
  if (algorithm == 0)
    {
      // SPECIFIC
      // Is a specific downscaling speed enhanced treatment available?
      if ((output_width_slice == 1) && (input_width_slice == 1))
	specific = 5;
      if ((output_width_slice == 1) && (input_width_slice == 1)
	  && (input_height_slice == 4) && (output_height_slice == 3))
	specific = 7;
      if ((input_height_slice == 2) && (output_height_slice == 1))
	specific = 3;
      if ((output_height_slice == 1) && (input_height_slice == 1))
	specific = 1;
      if ((output_height_slice == 1) && (input_height_slice == 1)
	  && (output_width_slice == 2) && (input_width_slice == 3))
	specific = 6;
      if ((output_height_slice == 1) && (input_height_slice == 1)
	  && (output_width_slice == 1) && (input_width_slice == 1))
	specific = 4;
      if ((input_height_slice == 2) && (output_height_slice == 1)
	  && (input_width_slice == 2) && (output_width_slice == 1))
	specific = 2;
      if ((input_height_slice == 8) && (output_height_slice == 3))
	specific = 9;
      if ((input_height_slice == 8) && (output_height_slice == 3)
	  && (input_width_slice == 2) && (output_width_slice == 1))
	specific = 8;
      if (specific)
	mjpeg_info ("Specific downscaling routing number %u", specific);

      // To determine scaled value of pixels in the case of the resample algorithm, we have to divide a long int by 
      // the long int "diviseur". So, to speed up downscaling, we tabulate all possible results of this division 
      // using the divide vector and the function yuvscaler_nearest_integer_division. 
      if (!
	  (divide =
	   (uint8_t *) malloc ((1 + 255 * diviseur) * sizeof (uint8_t) +
			       ALIGNEMENT)))
	mjpeg_error_exit1
	  ("Could not allocate memory for divide table. STOP!");
      mjpeg_debug ("before alignement: divide=%p", divide);
      // alignement instructions
      if (((unsigned long) divide % ALIGNEMENT) != 0)
	divide =
	  (uint8_t *) ((((unsigned long) divide / ALIGNEMENT) + 1) *
		       ALIGNEMENT);
      mjpeg_debug ("after alignement: divide=%p", divide);

      u_c_p = divide;
      for (i = 0; i <= 255 * diviseur; i++)
	*(u_c_p++) = yuvscaler_nearest_integer_division (i, diviseur);

      // Calculate averaging coefficient
      // For the height
      height_coeff =
	malloc ((input_height_slice + 1) * output_height_slice *
		sizeof (unsigned int));
      average_coeff (input_height_slice, output_height_slice, height_coeff);

      // For the width
      width_coeff =
	malloc ((input_width_slice + 1) * output_width_slice *
		sizeof (unsigned int));
      average_coeff (input_width_slice, output_width_slice, width_coeff);

    }
  // END OF RESAMPLE RESAMPLE RESAMPLE      

   
   

  // BICUBIC BICUBIC BICUBIC  
  if (algorithm == 1)
    {
       
       

      // SPECIFIC
      // Is a specific downscaling speed enhanced treatment available?
       
       // We only downscale on height, not width.
       // Ex: 16/9 to 4/3 conversion
      if ((output_width_slice == 1) && (input_width_slice == 1))
	specific = 5;

       // We only downscale on width, not height
       // Ex: Full size to SVCD 
      if ((output_height_slice == 1) && (input_height_slice == 1))
	specific = 1;

       if (specific)
	 mjpeg_info ("Specific downscaling routing number %u", specific);
       
//       specific=0;
       // Let us tabulate several values which are explained below:
       // 
       // Given the scaling factor "height_scale" on height and "width_scale" on width, to an output pixel of coordinates (out_col,out_line)
       // corresponds an input pixel of coordinates (in_col,in_line), where in_col = out_col/width_scale and in_line = out_line/height_scale.
       // As pixel coordinates are integer values, we take for in_col and out_col the nearest smaller integer
       // value: in_col = floor(out_col/width_scale) and in_line = floor(out_line/height_scale).
       // The input pixel of coordinates (in_col,in_line) is called the base input pixel
       // Thus, we make an error conventionnally named "b" for columns and "a" for lines
       // with b = out_col/width_scale - floor(out_col/width_scale) and a = out_line/height_scale - floor(out_line/height_scale). 
       // Please note that a and b are inside range [0,1[. 
       // 
       // For upscaling along w (resp. h), we need to take into account the 4 nearest neighbors along w (resp. h) of the base input pixel.
       // For downscaling along w (resp. h), we need to take into account AT LEAST 6 nearest neighbors of the base input pxel. 
       // And the real number of neighbors pixel from the base input pixel to be taken into account depends on the scaling ratios. 
       // We have to take into account "width_neighbors" neighbors on the width and "height_neighbors" on the height; 
       // with width_neighbors = 2*nearest_higher_integer(2/width_scale),  or 4 if upscaling (output_width_slice>input_width_slice)
       // and width_offset=(width_neighbors/2)-1;
       // with height_neighbors = 2*nearest_higher_integer(2/height_scale), or 4 if upscaling (output_height_slice>input_height_slice)
       // and height_offset=(height_neighbors/2)-1;
       // 
       // *****************
       // The general formula giving the value of the output pixel as a function of the input pixels is:
       // OutputPixel(out_col,out_line)=
       // Sum(h=-height_offset,...(height_neigbors-height_offset-1))Sum(w=-width_offset,...(width_neigbors-width_offset-1))
       // InputPixel(in_col+w,in_line+h)*BicubicCoefficient((b-w)*scale_width)*BicubicCoefficient((a-h)*scale_height)*scale_height*scale_width
       // *****************
       // Please note that [theoretically] (a-h)*scale_height is [-2:2], as well as (b-w)*scale_width. 
       // But, as height_neigbors is the nearest higher integer, the practical range for "(a-h)*scale_height" and "(b-w)*scale_width" is
       // extended from theorital [-2:2] to [-3:3] => "(a-h)*scale_height" and "(b-w)*scale_width" are considered 0 outside of [-2:2].
       // Please note also that for upscaling only, scale_height and scale_width are artifially taken as 1.0 in the formula.
       // 
       // For an easier implementation, it is preferable that h and w start from 0. Therefore, in the general formula, we will replace
       // "h" by "h-height_offset" and "w" by "w-width_offset".
       // 
       // Moreover, the output pixel value depends on at least the 4x4 nearest neighbors from the base input pixel in the input image. 
       // As a consequence, if the base input pixel is at on the border of the image, the bicubic algorithm will try to find values
       // outside the input image => to avoid this, we will pad the input image height_offset pixel on the top, width_offset pixels on the left,
       // (and right_offset pixels on the right and bottom_offset pixels at the bottom). 
       // Therefore, in the general formula, we will replace InputPixel(x,y) by PaddedInputPixel(x+width_offset,y+height_offset).
       // 
       // *****************
       // Finally, the general formula may be rewritten as:
       // OutputPixel(out_col,out_line)=
       // Sum(h=0,...(height_neigbors-1))Sum(w=0...(width_neigbors-1))
       // PaddedInputPixel(in_col+w,in_line+h)*BicubicCoefficient((b-w+width_offset)*scale_width)*BicubicCoefficient((a-h+height_offset)*scale_height)*scale_height*scale_width
       // *****************
       // 
       // 
       // *****************
       // IMPLEMENTATION
       // *****************
       // To insure a fast implementation of the general formula, we will pre-calculate all possible values of 
       // BicubicCoefficient((b-w+width_offset)*scale_width)*scale_width, and tabulate them as cspline_w:
       // cspline_w[w,out_col]=BicubicCoefficient((b[out_col]-w+width_offset)*scale_width)*scale_width. 
       // And the same stands for height:
       // cspline_h[h,out_line]=BicubicCoefficient((a[out_line]-h+height_offset)*scale_height)*scale_height
       // 
       // To be continued ...
      
       height_scale=(float)output_height_slice/(float)input_height_slice;
       if (height_scale>1.0)
	 height_scale=1.0;
       
       width_scale=(float)output_width_slice/(float)input_width_slice;
       if (width_scale>1.0)
	 width_scale=1.0;

       width_neighbors = (2 * input_width_slice ) / output_width_slice; 
       if (((2 * input_width_slice ) % output_width_slice)!=0)
	 width_neighbors++;
       width_neighbors*=2;
       if (width_neighbors < 4)
	 width_neighbors = 4;
       width_offset = left_offset = width_neighbors/2-1;
       width_pad=width_neighbors - 1;
       right_offset=width_neighbors/2;

       height_neighbors = (2 * input_height_slice ) / output_height_slice; 
       if (((2 * input_height_slice ) % output_height_slice)!=0)
	 height_neighbors++;
       height_neighbors*=2;
       if (height_neighbors < 4)
	 height_neighbors = 4;
       height_offset = top_offset = height_neighbors/2-1;
       height_pad=height_neighbors - 1;
       bottom_offset=height_neighbors/2;

       mjpeg_debug("height_scale=%f, width_scale=%f, width_neighbors=%d, height_neighbors=%d",height_scale,width_scale,width_neighbors,height_neighbors);
      // Memory allocations

       
#ifdef HAVE_ASM_MMX
      if (!(mmx_res =
	       (int32_t *) malloc (2 * sizeof (int32_t) + ALIGNEMENT)))
	mjpeg_error_exit1
	  ("Could not allocate memory for mmx registers. STOP!");
      // alignement instructions
      if (((unsigned long int) mmx_res % ALIGNEMENT) != 0)
	mmx_res =
	  (int32_t *) ((((unsigned long int) mmx_res / ALIGNEMENT) + 1) *
		       ALIGNEMENT);
       
       if (mmx==1)
	 {
	    if (width_neighbors <= MAXWIDTHNEIGHBORS)
	      {
		 mjpeg_info("MMX accelerated treatment activated");
		 mmx = 1;
	      }
	    else 
	      {
		 mmx=0;
		 mjpeg_warn("MMX accelerated treatment not available for downscaling ratio larger than 4 to 1");
		 mjpeg_warn("If you still want to use an MMX treatment (not really useful for such a large downscaling ratio");
		 mjpeg_warn("please use multiple yuvscaler downscaling to achieve the desired downscaling ratio");
	      }
	 }
#endif


// Il faudrait peut-tre aligner correctement tous ces pointeurs, en particulier cspline_w_neighbors et cspline_h_neighbors
// qui sont amplement utiliss dans les routines de scaling => il faut aussi aligner cspline_w et cspline_h
      if (
	  !(cspline_w =            (int16_t *) malloc ( width_neighbors  * output_active_width  * sizeof (int16_t))) ||
	  !(cspline_h =            (int16_t *) malloc ( height_neighbors * output_active_height * sizeof (int16_t))) ||
	  !(in_col =          (unsigned int *) malloc ( output_active_width  * sizeof (unsigned int))) ||
	  !(b =                      (float *) malloc ( output_active_width  * sizeof (float))) ||
	  !(in_line =         (unsigned int *) malloc ( output_active_height * sizeof (unsigned int))) ||
	  !(a =                      (float *) malloc ( output_active_height * sizeof (float)))
	  )
	mjpeg_error_exit1
	  ("Could not allocate memory for bicubic tables. STOP!");

       // Initialisation of bicubic tables
       pointer=cspline_h;
       for (out_line = 0; out_line < output_active_height; out_line++)
	 {
	    in_line[out_line] = (out_line * input_height_slice) / output_height_slice;
	    //	    mjpeg_debug("in_line[%u]=%u",out_line,in_line[out_line]);
	    a[out_line] = 
	      (float) ((out_line * input_height_slice) % output_height_slice) /
	      (float) output_height_slice;
	    somme=0;
	    for (h=0;h<height_neighbors;h++)
	      {
		 cspline_value=cubic_spline ((a[out_line] + height_offset -h)*height_scale, bicubic_div_height)*height_scale;
		 mjpeg_debug("cspline_value=%d,cspline=%d,a[%u]=%g,height_offset=%d,height_scale=%g,h=%lu",cspline_value,cubic_spline ((a[out_line] + height_offset -h)*height_scale, bicubic_div_height),out_line,a[out_line],height_offset,height_scale,h);
		 somme+=cspline_value;
		 *(pointer++)=cspline_value;
	      }
	    if (cspline_value!=0)
	      zero_height_neighbors=0;
	    // Normalisation test and normalisation of cspline 
	    if (somme != bicubic_div_height) 
	      *(pointer-2) += bicubic_div_height-somme; 
	 }
       
       pointer=cspline_w;
       for (out_col = 0; out_col < output_active_width; out_col++)
	 {
	    in_col[out_col] = (out_col * input_width_slice) / output_width_slice;
	    b[out_col] = 
	      (float) ((out_col * input_width_slice) % output_width_slice) /
	      (float) output_width_slice;
	    somme=0;
	    for (w=0;w<width_neighbors;w++)
	      {
//		 mjpeg_debug("b[%u]=%g,width_offset=%d,width_scale=%g,w=%lu",out_col,b[out_col],width_offset,width_scale,w);
		 cspline_value=cubic_spline ((b[out_col] + width_offset -w)*width_scale, bicubic_div_width)*width_scale;
		 mjpeg_debug("cspline_value=%d,b[%u]=%g,height_offset=%d,height_scale=%g,w=%lu",cspline_value,out_col,b[out_col],height_offset,height_scale,w);
		 somme+=cspline_value;
		 *(pointer++)=cspline_value;
	      }
	    if (cspline_value!=0)
	      zero_width_neighbors=0;
	    // Normalisation test and normalisation of cspline 
	    if (somme != bicubic_div_width) 
	      *(pointer-2) += bicubic_div_width-somme; 
	 }
       
// Added +2*ALIGNEMENT for MMX scaling routines that loads a higher number of pixels than necessary (memory overflow) 
      if (interlaced == Y4M_ILACE_NONE)
	{
	  if (!(padded_input =
		(uint8_t *) malloc ((input_useful_width + width_neighbors) *
				    (input_useful_height + height_neighbors)+2*ALIGNEMENT)))
	    mjpeg_error_exit1
	      ("Could not allocate memory for padded_input table. STOP!");
	}
      else
	{
	  if (!(padded_top =
		(uint8_t *) malloc ((input_useful_width + width_neighbors) *
				    (input_useful_height / 2 + height_neighbors)+2*ALIGNEMENT)) ||
	      !(padded_bottom =
		(uint8_t *) malloc ((input_useful_width + width_neighbors) *
				    (input_useful_height / 2 + height_neighbors)+2*ALIGNEMENT)))
	    mjpeg_error_exit1
	      ("Could not allocate memory for padded_top|bottom tables. STOP!");
	}
       if (!(intermediate = (int32_t *) malloc(output_active_width*(input_useful_height + height_neighbors+1)*sizeof(int32_t)))) 
	     mjpeg_error_exit1
	     ("Could not allocate memory for intermediate. STOP!");
       
    }
   
   // END OF BICUBIC BICUBIC BICUBIC     


  // Pointers allocations
  if (!(input = malloc (((input_width * input_height * 3) / 2) + ALIGNEMENT)) ||
      !(output = malloc (((output_width * output_height * 3) / 2) + ALIGNEMENT))
      )
    mjpeg_error_exit1
      ("Could not allocate memory for input or output tables. STOP!");

  // input and output pointers alignement
  mjpeg_debug ("before alignement: input=%p output=%p", input, output);
  if (((unsigned long) input % ALIGNEMENT) != 0)
    input =
      (uint8_t *) ((((unsigned long) input / ALIGNEMENT) + 1) * ALIGNEMENT);
  if (((unsigned long) output % ALIGNEMENT) != 0)
    output =
      (uint8_t *) ((((unsigned long) output / ALIGNEMENT) + 1) * ALIGNEMENT);
  mjpeg_debug ("after alignement: input=%p output=%p", input, output);


  // if skip_col==1
  if (!(frame_y_p = (uint8_t **) malloc (display_height * sizeof (uint8_t *)))
      || !(frame_u_p =
	   (uint8_t **) malloc (display_height / 2 * sizeof (uint8_t *)))
      || !(frame_v_p =
	   (uint8_t **) malloc (display_height / 2 * sizeof (uint8_t *))))
    mjpeg_error_exit1
      ("Could not allocate memory for frame_y_p, frame_u_p or frame_v_p tables. STOP!");

  // Incorporate blacks lines and columns directly into output matrix since this will never change. 
  // BLACK pixel in YUV = (16,128,128)
  if (black == 1)
    {
      u_c_p = output;
      // Y component
      for (i = 0; i < output_black_line_above * output_width; i++)
	*(u_c_p++) = blacky;
      if (black_col == 0)
	u_c_p += output_active_height * output_width;
      else
	{
	  for (i = 0; i < output_active_height; i++)
	    {
	      for (j = 0; j < output_black_col_left; j++)
		*(u_c_p++) = blacky;
	      u_c_p += output_active_width;
	      for (j = 0; j < output_black_col_right; j++)
		*(u_c_p++) = blacky;
	    }
	}
      for (i = 0; i < output_black_line_under * output_width; i++)
	*(u_c_p++) = blacky;

      // U component
      //   u_c_p=output+output_width*output_height;
      for (i = 0; i < output_black_line_above / 2 * output_width / 2; i++)
	*(u_c_p++) = blackuv;
      if (black_col == 0)
	u_c_p += output_active_height / 2 * output_width / 2;
      else
	{
	  for (i = 0; i < output_active_height / 2; i++)
	    {
	      for (j = 0; j < output_black_col_left / 2; j++)
		*(u_c_p++) = blackuv;
	      u_c_p += output_active_width / 2;
	      for (j = 0; j < output_black_col_right / 2; j++)
		*(u_c_p++) = blackuv;
	    }
	}
      for (i = 0; i < output_black_line_under / 2 * output_width / 2; i++)
	*(u_c_p++) = blackuv;

      // V component
      //   u_c_p=output+(output_width*output_height*5)/4;
      for (i = 0; i < output_black_line_above / 2 * output_width / 2; i++)
	*(u_c_p++) = blackuv;
      if (black_col == 0)
	u_c_p += output_active_height / 2 * output_width / 2;
      else
	{
	  for (i = 0; i < output_active_height / 2; i++)
	    {
	      for (j = 0; j < output_black_col_left / 2; j++)
		*(u_c_p++) = blackuv;
	      u_c_p += output_active_width / 2;
	      for (j = 0; j < output_black_col_right / 2; j++)
		*(u_c_p++) = blackuv;
	    }
	}
      for (i = 0; i < output_black_line_under / 2 * output_width / 2; i++)
	*(u_c_p++) = blackuv;
    }

  // MONOCHROME FRAMES
  if (mono == 1)
    {
      // the U and V components of output frame will always be 128
      u_c_p = output + output_width * output_height;
      for (i = 0; i < 2 * output_width / 2 * output_height / 2; i++)
	*(u_c_p++) = blackuv;
    }


  // Various initialisatiosn for variables concerning input and output   
  out_nb_col_slice = output_active_width / output_width_slice;
  out_nb_line_slice = output_active_height / output_height_slice;
  input_y =
    input + input_discard_line_above * input_width + input_discard_col_left;
  input_u =
    input + input_width * input_height +
    input_discard_line_above / 2 * input_width / 2 +
    input_discard_col_left / 2;
  input_v =
    input + (input_height * input_width * 5) / 4 +
    input_discard_line_above / 2 * input_width / 2 +
    input_discard_col_left / 2;
  output_y =
    output + output_black_line_above * output_width + output_black_col_left;
  output_u =
    output + output_width * output_height +
    output_black_line_above / 2 * output_width / 2 +
    output_black_col_left / 2;
  output_v =
    output + (output_width * output_height * 5) / 4 +
    output_black_line_above / 2 * output_width / 2 +
    output_black_col_left / 2;

  // Other initialisations for frame output
  frame_y =
    output + output_skip_line_above * output_width + output_skip_col_left;
  frame_u =
    output + output_width * output_height +
    output_skip_line_above / 2 * output_width / 2 + output_skip_col_left / 2;
  frame_v =
    output + (output_width * output_height * 5) / 4 +
    output_skip_line_above / 2 * output_width / 2 + output_skip_col_left / 2;
  if (skip_col == 1)
    {
      for (i = 0; i < display_height; i++)
	frame_y_p[i] = frame_y + i * output_width;
      for (i = 0; i < display_height / 2; i++)
	{
	  frame_u_p[i] = frame_u + i * output_width / 2;
	  frame_v_p[i] = frame_v + i * output_width / 2;
	}
    }

  nb_pixels = (input_width * input_height * 3) / 2;

  mjpeg_debug ("End of Initialisation");
  // END OF INITIALISATION
  // END OF INITIALISATION
  // END OF INITIALISATION


  // SCALE AND OUTPUT FRAMES 
  // Output file header
  y4m_copy_stream_info (&out_streaminfo, &in_streaminfo);
  y4m_si_set_width (&out_streaminfo, display_width);
  y4m_si_set_height (&out_streaminfo, display_height);
  y4m_si_set_interlace (&out_streaminfo, interlaced);
  y4m_si_set_sampleaspect (&out_streaminfo,
			   yuvscaler_calculate_output_sar (output_width_slice,
							   output_height_slice,
							   input_width_slice,
							   input_height_slice,
							   y4m_si_get_sampleaspect
							   (&in_streaminfo)));
  if (no_header == 0)
    y4m_write_stream_header (output_fd, &out_streaminfo);
  y4m_log_stream_info (mjpeg_loglev_t("info"), "output: ", &out_streaminfo);
   
  
   

  // Master loop : continue until there is no next frame in stdin
  while ((err = yuvscaler_y4m_read_frame
	  (input_fd, &in_streaminfo, &frameinfo, nb_pixels, input)) == Y4M_OK)
    {
      mjpeg_info ("Frame number %ld", frame_num);

      // Blackout if necessary
      if (input_black == 1)
	blackout (input_y, input_u, input_v);
      frame_num++;

      // Output Frame Header
      if (y4m_write_frame_header (output_fd, &out_streaminfo, &frameinfo) != Y4M_OK)
	goto out_error;


      // ***************
      // SCALE THE FRAME
      // ***************
      // RESAMPLE ALGORITHM       
      // ***************
      if (algorithm == 0)
	{
	  if (specific) 
	     {
		average_specific (input_y, output_y, height_coeff,width_coeff, 0);
		if (!mono) 
		  {
		     average_specific (input_u, output_u, height_coeff,
				       width_coeff, 1);
		     average_specific (input_v, output_v, height_coeff,
				       width_coeff, 1);
		  }
	     }
	   else 
	     {
		average (input_y, output_y, height_coeff, width_coeff, 0);
		if (!mono) 
		  {
		  average (input_u, output_u, height_coeff, width_coeff, 1);
		  average (input_v, output_v, height_coeff, width_coeff, 1);
		  }
	     }
	}
      // ***************
      // RESAMPLE ALGO
      // ***************
      // BICIBIC ALGO
      // ***************
      if (algorithm == 1)
	{
	   // INPUT FRAME PADDING BEFORE BICUBIC INTERPOLATION
	   // PADDING IS DONE SEPARATELY FOR EACH COMPONENT
	   // 
	   if (interlaced != Y4M_ILACE_NONE)
	     {
		padding_interlaced (padded_top, padded_bottom, input_y, 0,left_offset,top_offset,right_offset,bottom_offset,width_pad);
		cubic_scale_interlaced (padded_top, padded_bottom, output_y, 
					in_col, in_line,
					cspline_w, width_neighbors, zero_width_neighbors,
					cspline_h, height_neighbors, zero_height_neighbors,
					0);
		if (!mono) 
		  {
		     padding_interlaced (padded_top, padded_bottom, input_u, 1,left_offset,top_offset,right_offset,bottom_offset,width_pad);
		     cubic_scale_interlaced (padded_top, padded_bottom, output_u, 
					     in_col, in_line,
					     cspline_w, width_neighbors,zero_width_neighbors,
					     cspline_h, height_neighbors,zero_height_neighbors,
					     1);
		     padding_interlaced (padded_top, padded_bottom, input_v, 1,left_offset,top_offset,right_offset,bottom_offset,width_pad);
		     cubic_scale_interlaced (padded_top, padded_bottom, output_v, 
					     in_col, in_line,
					     cspline_w, width_neighbors,zero_width_neighbors,
					     cspline_h, height_neighbors,zero_height_neighbors,
					     1);
		  }
	     }
	   else
	     {
		padding (padded_input, input_y, 0,left_offset,top_offset,right_offset,bottom_offset,width_pad);
		cubic_scale (padded_input, output_y, 
			     in_col, in_line,
			     cspline_w, width_neighbors,  zero_width_neighbors,
			     cspline_h, height_neighbors, zero_height_neighbors,
			     0);
		if (!mono) 
		  {
		     padding (padded_input, input_u, 1,left_offset,top_offset,right_offset,bottom_offset,width_pad);
		     cubic_scale (padded_input, output_u, 
				  in_col, in_line,
				  cspline_w, width_neighbors, zero_width_neighbors,
				  cspline_h, height_neighbors, zero_height_neighbors,
				  1);
		     padding (padded_input, input_v, 1,left_offset,top_offset,right_offset,bottom_offset,width_pad);
		     cubic_scale (padded_input, output_v, 
				  in_col, in_line,
				  cspline_w, width_neighbors, zero_width_neighbors,
				  cspline_h, height_neighbors, zero_height_neighbors,
				  1);
		  }
	     }
	}
      // ***************
      // BICIBIC ALGO
      // ***************
      // END OF SCALE THE FRAME
      // **********************

      // OUTPUT FRAME CONTENTS
      if (skip == 0)
	{
	  // Here, display=output_active 
	  if (y4m_write
	      (output_fd, output,
	       (display_width * display_height * 3) / 2) != Y4M_OK)
	    goto out_error;
	}
      else
	{
	  // skip == 1
	  if (skip_col == 0)
	    {
	      // output_active_width==display_width, component per component frame output
	      if (y4m_write
		  (output_fd, frame_y,
		   display_width * display_height) != Y4M_OK)
		goto out_error;
	      if (y4m_write
		  (output_fd, frame_u,
		   display_width / 2 * display_height / 2) != Y4M_OK)
		goto out_error;
	      if (y4m_write
		  (output_fd, frame_v,
		   display_width / 2 * display_height / 2) != Y4M_OK)
		goto out_error;
	    }
	  else
	    {
	      // output_active_width > display_width, line per line frame output for each component
	      for (i = 0; i < display_height; i++)
		{
		  if (y4m_write (output_fd, frame_y_p[i], display_width)
		      != Y4M_OK)
		    goto out_error;
		}
	      for (i = 0; i < display_height / 2; i++)
		{
		  if (y4m_write
		      (output_fd, frame_u_p[i], display_width / 2) != Y4M_OK)
		    goto out_error;
		}
	      for (i = 0; i < display_height / 2; i++)
		{
		  if (y4m_write
		      (output_fd, frame_v_p[i], display_width / 2) != Y4M_OK)
		    goto out_error;

		}
	    }
	}
    }
  // End of master loop => no more frame in stdin

  if (err != Y4M_ERR_EOF)
    mjpeg_error_exit1 ("Couldn't read frame number %ld!", frame_num);
  else
    mjpeg_info ("Normal exit: end of stream with frame number %ld!",
		frame_num);
  y4m_fini_stream_info (&in_streaminfo);
  y4m_fini_stream_info (&out_streaminfo);
  y4m_fini_frame_info (&frameinfo);
  return 0;

out_error:
  mjpeg_error_exit1 ("Unable to write to output - aborting!");
  return 1;
}


// *************************************************************************************
unsigned int
pgcd (unsigned int num1, unsigned int num2)
{
  // Calculates the biggest common divider between num1 and num2, after Euclid's
  // pgcd(a,b)=pgcd(b,a%b)
  // My thanks to Chris Atenasio <chris@crud.net>
  unsigned int c, bigger, smaller;

  if (num2 < num1)
    {
      smaller = num2;
      bigger = num1;
    }
  else
    {
      smaller = num1;
      bigger = num2;
    }

  while (smaller)
    {
      c = bigger % smaller;
      bigger = smaller;
      smaller = c;
    }
  return (bigger);
}

// *************************************************************************************

//      if ((output_width_slice == 1) && (input_width_slice == 1)
//	  && (input_height_slice == 4) && (output_height_slice == 3))
//	specific = 7;

//      if ((output_height_slice == 1) && (input_height_slice == 1)
//	  && (output_width_slice == 2) && (input_width_slice == 3))
//	specific = 6;
       
       
//       if ((input_height_slice == 2) && (output_height_slice == 1))
//	 specific = 3;
       // Full size to VCD
//      if ((input_height_slice == 2) && (output_height_slice == 1)
//	  && (input_width_slice == 2) && (output_width_slice == 1))
//	specific = 2;
//      if ((input_height_slice == 8) && (output_height_slice == 3))
//	specific = 9;
//      if ((input_height_slice == 8) && (output_height_slice == 3)
//	  && (input_width_slice == 2) && (output_width_slice == 1))
//	specific = 8;

     
      // alignement instructions
/*       if (((unsigned int) cspline_w % ALIGNEMENT) != 0)
	 cspline_w =
	 (int16_t *) ((((unsigned int) cspline_w / ALIGNEMENT) + 1) *
		       ALIGNEMENT);
       if (((unsigned int) cspline_h % ALIGNEMENT) != 0)
	 cspline_h =
	 (int16_t *) ((((unsigned int) cspline_h / ALIGNEMENT) + 1) *
		       ALIGNEMENT);
       if (((unsigned int) cspline_w_neighbors % ALIGNEMENT) != 0)
	 cspline_w_neighbors =
	 (int16_t **) ((((unsigned int) cspline_w_neighbors / ALIGNEMENT) + 1) *
		       ALIGNEMENT);
       if (((unsigned int) cspline_h_neighbors % ALIGNEMENT) != 0)
	 cspline_h_neighbors =
	 (int16_t **) ((((unsigned int) cspline_h_neighbors / ALIGNEMENT) + 1) *
		       ALIGNEMENT);
*/


/* 
 * Local variables:
 *  tab-width: 8
 *  indent-tabs-mode: nil
 * End:
 */