summaryrefslogtreecommitdiff
path: root/src/nv_video.c
blob: fc654fd4548a0dff022052c61990e9eb5826fb81 (plain)
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

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

#include "xf86.h"
#include "xf86_OSproc.h"
#include "xf86Resources.h"
#include "compiler.h"
#include "xf86PciInfo.h"
#include "xf86Pci.h"
#include "xf86fbman.h"
#include "regionstr.h"

#include "xf86xv.h"
#include <X11/extensions/Xv.h>
#include "xaa.h"
#include "xaalocal.h"
#include "exa.h"
#include "damage.h"
#include "dixstruct.h"
#include "fourcc.h"

#include "nv_include.h"
#include "nv_dma.h"

#define IMAGE_MAX_W 2046
#define IMAGE_MAX_H 2046

#define OFF_DELAY 	500  /* milliseconds */
#define FREE_DELAY 	5000

#define OFF_TIMER 	0x01
#define FREE_TIMER	0x02
#define CLIENT_VIDEO_ON	0x04

#define TIMER_MASK      (OFF_TIMER | FREE_TIMER)

#define NUM_BLIT_PORTS 32

typedef struct _NVPortPrivRec {
	short		brightness;
	short		contrast;
	short		saturation;
	short		hue;
	RegionRec	clip;
	CARD32		colorKey;
	Bool		autopaintColorKey;
	Bool		doubleBuffer;
	CARD32		videoStatus;
	int		currentBuffer;
	Time		videoTime;
	Bool		grabbedByV4L;
	Bool		iturbt_709;
	Bool		blitter;
	Bool		SyncToVBlank;
	NVAllocRec *	video_mem;
	int		pitch;
	int		offset;
} NVPortPrivRec, *NVPortPrivPtr;

#define GET_OVERLAY_PRIVATE(pNv) \
	(NVPortPrivPtr)((pNv)->overlayAdaptor->pPortPrivates[0].ptr)

#define GET_BLIT_PRIVATE(pNv) \
	(NVPortPrivPtr)((pNv)->blitAdaptor->pPortPrivates[0].ptr)

#define MAKE_ATOM(a) MakeAtom(a, sizeof(a) - 1, TRUE)

static Atom xvBrightness, xvContrast, xvColorKey, xvSaturation, 
            xvHue, xvAutopaintColorKey, xvSetDefaults, xvDoubleBuffer,
            xvITURBT709, xvSyncToVBlank;

/* client libraries expect an encoding */
static XF86VideoEncodingRec DummyEncoding =
{ 
	0,
	"XV_IMAGE",
	IMAGE_MAX_W, IMAGE_MAX_H,
	{1, 1}
};

#define NUM_FORMATS_ALL 6

XF86VideoFormatRec NVFormats[NUM_FORMATS_ALL] = 
{
	{15, TrueColor}, {16, TrueColor}, {24, TrueColor},
	{15, DirectColor}, {16, DirectColor}, {24, DirectColor}
};

#define NUM_OVERLAY_ATTRIBUTES 9
XF86AttributeRec NVOverlayAttributes[NUM_OVERLAY_ATTRIBUTES] =
{
	{XvSettable | XvGettable, 0, 1, "XV_DOUBLE_BUFFER"},
	{XvSettable | XvGettable, 0, (1 << 24) - 1, "XV_COLORKEY"},
	{XvSettable | XvGettable, 0, 1, "XV_AUTOPAINT_COLORKEY"},
	{XvSettable             , 0, 0, "XV_SET_DEFAULTS"},
	{XvSettable | XvGettable, -512, 511, "XV_BRIGHTNESS"},
	{XvSettable | XvGettable, 0, 8191, "XV_CONTRAST"},
	{XvSettable | XvGettable, 0, 8191, "XV_SATURATION"},
	{XvSettable | XvGettable, 0, 360, "XV_HUE"},
	{XvSettable | XvGettable, 0, 1, "XV_ITURBT_709"}
};

#define NUM_BLIT_ATTRIBUTES 2
XF86AttributeRec NVBlitAttributes[NUM_BLIT_ATTRIBUTES] =
{
	{XvSettable             , 0, 0, "XV_SET_DEFAULTS"},
	{XvSettable | XvGettable, 0, 1, "XV_SYNC_TO_VBLANK"}
};


#define NUM_IMAGES_YUV 4
#define NUM_IMAGES_ALL 5

#define FOURCC_RGB 0x0000003
#define XVIMAGE_RGB \
   { \
        FOURCC_RGB, \
        XvRGB, \
        LSBFirst, \
        { 0x03, 0x00, 0x00, 0x00, \
          0x00,0x00,0x00,0x10,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71}, \
        32, \
        XvPacked, \
        1, \
        24, 0x00ff0000, 0x0000ff00, 0x000000ff, \
        0, 0, 0, \
        0, 0, 0, \
        0, 0, 0, \
        {'B','G','R','X',\
          0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, \
        XvTopToBottom \
   }

static XF86ImageRec NVImages[NUM_IMAGES_ALL] =
{
	XVIMAGE_YUY2,
	XVIMAGE_YV12,
	XVIMAGE_UYVY,
	XVIMAGE_I420,
	XVIMAGE_RGB
};

/**
 * NVSetPortDefaults
 * set attributes of port "pPriv" to compiled-in (except for colorKey) defaults
 * 
 * @param pScrn screen to get the default colorKey from
 * @param pPriv port to reset to defaults
 */
static void 
NVSetPortDefaults (ScrnInfoPtr pScrn, NVPortPrivPtr pPriv)
{
	NVPtr pNv = NVPTR(pScrn);

	pPriv->brightness		= 0;
	pPriv->contrast			= 4096;
	pPriv->saturation		= 4096;
	pPriv->hue			= 0;
	pPriv->colorKey			= pNv->videoKey;
	pPriv->autopaintColorKey	= TRUE;
	pPriv->doubleBuffer		= TRUE;
	pPriv->iturbt_709		= FALSE;
}

/**
 * NVResetVideo
 * writes the current attributes from the overlay port to the hardware
 */
void 
NVResetVideo (ScrnInfoPtr pScrn)
{
	NVPtr          pNv     = NVPTR(pScrn);
	NVPortPrivPtr  pPriv   = GET_OVERLAY_PRIVATE(pNv);
	int            satSine, satCosine;
	double         angle;

	angle = (double)pPriv->hue * 3.1415927 / 180.0;

	satSine = pPriv->saturation * sin(angle);
	if (satSine < -1024)
		satSine = -1024;
	satCosine = pPriv->saturation * cos(angle);
	if (satCosine < -1024)
		satCosine = -1024;

	nvWriteVIDEO(pNv, NV_PVIDEO_LUMINANCE(0), (pPriv->brightness << 16) |
						   pPriv->contrast);
	nvWriteVIDEO(pNv, NV_PVIDEO_LUMINANCE(1), (pPriv->brightness << 16) |
						   pPriv->contrast);
	nvWriteVIDEO(pNv, NV_PVIDEO_CHROMINANCE(0), (satSine << 16) |
						    (satCosine & 0xffff));
	nvWriteVIDEO(pNv, NV_PVIDEO_CHROMINANCE(1), (satSine << 16) |
						    (satCosine & 0xffff));
	nvWriteVIDEO(pNv, NV_PVIDEO_COLOR_KEY, pPriv->colorKey);
}

/**
 * NVStopOverlay
 * Tell the hardware to stop the overlay
 */
static void 
NVStopOverlay (ScrnInfoPtr pScrn)
{
	NVPtr pNv = NVPTR(pScrn);

	nvWriteVIDEO(pNv, NV_PVIDEO_STOP, 1);
}

/**
 * NVAllocateOverlayMemory
 * allocates memory
 * 
 * - why does the funciton have "Overlay" in its name? It does not
 * have anything "Overlay"-specific in its function body and it is called by
 * non-"Overlay"-specific functions.
 * TODO: rename to something like NVAllocateVideoMemory or NVAllocateXvMemory
 * - the function only (re-)allocates memory if it absolutely necessary,
 * that is, if the requested size is larger than the current size. that means,
 * that the size of allocated memory never shrinks, even if the requested
 * does. from a performance point of view this is most likely the best
 * alternative. but how often does the requested size of memory for video
 * playback change? whenever video-size/scaling changes? probably not very
 * often. so maybe sacrifice a tiny bit of performance (whenever the video is
 * rescaled) and not waste (RAM-)resources?
 * - the function makes assumptions about the XAA fb manager being used. isn't
 * there a way to check? what aboaut EXA?
 * 
 * @param pScrn screen which requests the memory
 * @param mem pointer to previously allocated memory for reallocation
 * @param size size of requested memory segment
 * @return pointer to the allocated memory
 */
static NVAllocRec *
NVAllocateOverlayMemory(ScrnInfoPtr pScrn, NVAllocRec *mem, int size)
{
	NVPtr pNv = NVPTR(pScrn);

	/* The code assumes the XAA fb manager is being used here,
	 * which allocates in pixels.  We allocate in bytes so we
	 * need to adjust the size here.
	 */
	size *= (pScrn->bitsPerPixel >> 3);

	if(mem) {
		if(mem->size >= size) // if(mem->size == size)
			return mem;
		NVFreeMemory(pNv, mem);
	}

	return NVAllocateMemory(pNv, NOUVEAU_MEM_FB, size); /* align 32? */
}

/**
 * NVFreeOverlayMemory
 * frees memory held by the overlay port
 * this function (unlike NVAllocateOverlayMemory) is "Overlay"-specific
 * 
 * @param pScrn screen whose overlay port wants to free memory
 */
static void
NVFreeOverlayMemory(ScrnInfoPtr pScrn)
{
	NVPtr         pNv   = NVPTR(pScrn);
	NVPortPrivPtr pPriv = GET_OVERLAY_PRIVATE(pNv);

	if(pPriv->video_mem) {
		NVFreeMemory(pNv, pPriv->video_mem);
		pPriv->video_mem = NULL;
	}
}

/**
 * NVFreeBlitMemory
 * frees memory held by the blit port
 * 
 * @param pScrn screen whose blit port wants to free memory
 */
static void
NVFreeBlitMemory(ScrnInfoPtr pScrn)
{
	NVPtr         pNv   = NVPTR(pScrn);
	NVPortPrivPtr pPriv = GET_BLIT_PRIVATE(pNv);

	if(pPriv->video_mem) {
		NVFreeMemory(pNv, pPriv->video_mem);
		pPriv->video_mem = NULL;
	}
}

/**
 * NVVideoTimerCallback
 * callback function which perform cleanup tasks (stop overlay, free memory).
 * within the driver it is only called once from NVBlockHandler in nv_driver.c
 */
static void
NVVideoTimerCallback(ScrnInfoPtr pScrn, Time currentTime)
{
	NVPtr         pNv = NVPTR(pScrn);
	NVPortPrivPtr pOverPriv = NULL;
	NVPortPrivPtr pBlitPriv = NULL;
	Bool needCallback = FALSE;

	if (!pScrn->vtSema)
		return; 

	if (pNv->overlayAdaptor) {
		pOverPriv = GET_OVERLAY_PRIVATE(pNv);
		if (!pOverPriv->videoStatus)
			pOverPriv = NULL;
	}

	if (pNv->blitAdaptor) {
		pBlitPriv = GET_BLIT_PRIVATE(pNv);
		if (!pBlitPriv->videoStatus)
			pBlitPriv = NULL;
	}

	if (pOverPriv) {
		if (pOverPriv->videoTime < currentTime) {
			if (pOverPriv->videoStatus & OFF_TIMER) {
				NVStopOverlay(pScrn);
				pOverPriv->videoStatus = FREE_TIMER;
				pOverPriv->videoTime = currentTime + FREE_DELAY;
				needCallback = TRUE;
			} else
			if (pOverPriv->videoStatus & FREE_TIMER) {
				NVFreeOverlayMemory(pScrn);
				pOverPriv->videoStatus = 0;
			}
		} else {
			needCallback = TRUE;
		}
	}

	if (pBlitPriv) {
		if (pBlitPriv->videoTime < currentTime) {
			NVFreeBlitMemory(pScrn);
			pBlitPriv->videoStatus = 0;              
		} else {
			needCallback = TRUE;
		}
	}

	pNv->VideoTimerCallback = needCallback ? NVVideoTimerCallback : NULL;
}

/**
 * NVPutOverlayImage
 * program hardware to overlay image into front buffer
 * 
 * @param pScrn screen
 * @param src_offset
 * @param id colorspace of image
 * @param src_pitch
 * @param dstBox
 * @param x1
 * @param y1
 * @param x2
 * @param y2
 * @param width
 * @param height
 * @param src_w
 * @param src_h
 * @param drw_w
 * @param drw_h
 * @param clipBoxes
 */
static void
NVPutOverlayImage(ScrnInfoPtr pScrn, int offset, int id,
		  int dstPitch, BoxPtr dstBox,
		  int x1, int y1, int x2, int y2,
		  short width, short height,
		  short src_w, short src_h,
		  short drw_w, short drw_h,
		  RegionPtr clipBoxes)
{
	NVPtr         pNv    = NVPTR(pScrn);
	NVPortPrivPtr pPriv  = GET_OVERLAY_PRIVATE(pNv);
	int           buffer = pPriv->currentBuffer;

	/* paint the color key */
	if(pPriv->autopaintColorKey && (pPriv->grabbedByV4L ||
		!REGION_EQUAL(pScrn->pScreen, &pPriv->clip, clipBoxes))) {
		/* we always paint V4L's color key */
		if (!pPriv->grabbedByV4L)
			REGION_COPY(pScrn->pScreen, &pPriv->clip, clipBoxes);
		xf86XVFillKeyHelper(pScrn->pScreen, pPriv->colorKey, clipBoxes);
	}

	if(pNv->CurrentLayout.mode->Flags & V_DBLSCAN) {
		dstBox->y1 <<= 1;
		dstBox->y2 <<= 1;
		drw_h <<= 1;
	}

	nvWriteVIDEO(pNv, NV_PVIDEO_BASE(buffer)     , offset);
	nvWriteVIDEO(pNv, NV_PVIDEO_SIZE_IN(buffer)  , (height << 16) | width);
	nvWriteVIDEO(pNv, NV_PVIDEO_POINT_IN(buffer) ,
			  ((y1 << 4) & 0xffff0000) | (x1 >> 12));
	nvWriteVIDEO(pNv, NV_PVIDEO_DS_DX(buffer)    , (src_w << 20) / drw_w);
	nvWriteVIDEO(pNv, NV_PVIDEO_DT_DY(buffer)    , (src_h << 20) / drw_h);
	nvWriteVIDEO(pNv, NV_PVIDEO_POINT_OUT(buffer),
			  (dstBox->y1 << 16) | dstBox->x1);
	nvWriteVIDEO(pNv, NV_PVIDEO_SIZE_OUT(buffer) ,
			  ((dstBox->y2 - dstBox->y1) << 16) |
			   (dstBox->x2 - dstBox->x1));

	dstPitch |= NV_PVIDEO_FORMAT_DISPLAY_COLOR_KEY;   /* use color key */
	if(id != FOURCC_UYVY)
		dstPitch |= NV_PVIDEO_FORMAT_COLOR_LE_CR8YB8CB8YA8;
	if(pPriv->iturbt_709)
		dstPitch |= NV_PVIDEO_FORMAT_MATRIX_ITURBT709;

	nvWriteVIDEO(pNv, NV_PVIDEO_FORMAT(buffer), dstPitch);
	nvWriteVIDEO(pNv, NV_PVIDEO_STOP, 0);
	nvWriteVIDEO(pNv, NV_PVIDEO_BUFFER, buffer ? 0x10 : 0x1);

	pPriv->videoStatus = CLIENT_VIDEO_ON;
}

#ifndef ExaOffscreenMarkUsed
extern void ExaOffscreenMarkUsed(PixmapPtr);
#endif
#ifndef exaGetDrawablePixmap
extern PixmapPtr exaGetDrawablePixmap(DrawablePtr);
#endif
#ifndef exaPixmapIsOffscreen
extern Bool exaPixmapIsOffscreen(PixmapPtr p);
#endif
/* To support EXA 2.0, 2.1 has this in the header */
#ifndef exaMoveInPixmap
extern void exaMoveInPixmap(PixmapPtr pPixmap);
#endif

/**
 * NVPutBlitImage
 * 
 * @param pScrn screen
 * @param src_offset
 * @param id colorspace of image
 * @param src_pitch
 * @param dstBox
 * @param x1
 * @param y1
 * @param x2
 * @param y2
 * @param width
 * @param height
 * @param src_w
 * @param src_h
 * @param drw_w
 * @param drw_h
 * @param clipBoxes
 * @param pDraw
 */
static void
NVPutBlitImage(ScrnInfoPtr pScrn, int src_offset, int id,
	       int src_pitch, BoxPtr dstBox,
	       int x1, int y1, int x2, int y2,
	       short width, short height,
	       short src_w, short src_h,
	       short drw_w, short drw_h,
	       RegionPtr clipBoxes,
	       DrawablePtr pDraw)
{
	NVPtr          pNv   = NVPTR(pScrn);
	NVPortPrivPtr  pPriv = GET_BLIT_PRIVATE(pNv);
	BoxPtr         pbox;
	int            nbox;
	CARD32         dsdx, dtdy;
	CARD32         dst_size, dst_point;
	CARD32         src_point, src_format;

	if (pNv->useEXA) {
		ScreenPtr pScreen = pScrn->pScreen;
		PixmapPtr pPix    = exaGetDrawablePixmap(pDraw);
		int dst_format;

		/* Try to get the dest drawable into vram */
		if (!exaPixmapIsOffscreen(pPix)) {
			exaMoveInPixmap(pPix);
			ExaOffscreenMarkUsed(pPix);
		}

		/* If we failed, draw directly onto the screen pixmap.
		 * Not sure if this is the best approach, maybe failing
		 * with BadAlloc would be better?
		 */
		if (!exaPixmapIsOffscreen(pPix)) {
			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
				"XV: couldn't move dst surface into vram\n");
			pPix = pScreen->GetScreenPixmap(pScreen);
		}

		NVAccelGetCtxSurf2DFormatFromPixmap(pPix, &dst_format);
		NVAccelSetCtxSurf2D(pPix, pPix, dst_format);

#ifdef COMPOSITE
		/* Adjust coordinates if drawing to an offscreen pixmap */
		if (pPix->screen_x || pPix->screen_y) {
			REGION_TRANSLATE(pScrn->pScreen, clipBoxes,
							     -pPix->screen_x,
							     -pPix->screen_y);
			dstBox->x1 -= pPix->screen_x;
			dstBox->x2 -= pPix->screen_x;
			dstBox->y1 -= pPix->screen_y;
			dstBox->y2 -= pPix->screen_y;
		}

		DamageDamageRegion((DrawablePtr)pPix, clipBoxes);
#endif
	} else {
		if (pNv->CurrentLayout.depth == 15) {
			NVDmaStart(pNv, NvSubContextSurfaces,
					SURFACE_FORMAT, 1);
			NVDmaNext (pNv, SURFACE_FORMAT_X1R5G5B5);
		}
	}

	pbox = REGION_RECTS(clipBoxes);
	nbox = REGION_NUM_RECTS(clipBoxes);

	dsdx = (src_w << 20) / drw_w;
	dtdy = (src_h << 20) / drw_h;

	dst_size  = ((dstBox->y2 - dstBox->y1) << 16) |
		     (dstBox->x2 - dstBox->x1);
	dst_point = (dstBox->y1 << 16) | dstBox->x1;

	src_pitch |= (STRETCH_BLIT_SRC_FORMAT_ORIGIN_CENTER << 16) |
		    (STRETCH_BLIT_SRC_FORMAT_FILTER_BILINEAR << 24);
	src_point = ((y1 << 4) & 0xffff0000) | (x1 >> 12);

	switch(id) {
	case FOURCC_RGB:
		src_format = STRETCH_BLIT_FORMAT_X8R8G8B8;
		break;
	case FOURCC_UYVY:
		src_format = STRETCH_BLIT_FORMAT_UYVY;
		break;
	default:
		src_format = STRETCH_BLIT_FORMAT_YUYV;
		break;
	}

	if(pPriv->SyncToVBlank) {
		NVDmaKickoff(pNv);
		NVWaitVSync(pScrn);
	}

	if(pNv->BlendingPossible) {
		NVDmaStart(pNv, NvSubScaledImage, STRETCH_BLIT_FORMAT, 2);
		NVDmaNext (pNv, src_format);
		NVDmaNext (pNv, STRETCH_BLIT_OPERATION_COPY);
	} else {
		NVDmaStart(pNv, NvSubScaledImage, STRETCH_BLIT_FORMAT, 1);
		NVDmaNext (pNv, src_format);
	}

	while(nbox--) {
		NVDmaStart(pNv, NvSubRectangle, RECT_SOLID_COLOR, 1);
		NVDmaNext (pNv, 0);

		NVDmaStart(pNv, NvSubScaledImage, STRETCH_BLIT_CLIP_POINT, 6);
		NVDmaNext (pNv, (pbox->y1 << 16) | pbox->x1); 
		NVDmaNext (pNv, ((pbox->y2 - pbox->y1) << 16) |
				 (pbox->x2 - pbox->x1));
		NVDmaNext (pNv, dst_point);
		NVDmaNext (pNv, dst_size);
		NVDmaNext (pNv, dsdx);
		NVDmaNext (pNv, dtdy);

		NVDmaStart(pNv, NvSubScaledImage, STRETCH_BLIT_SRC_SIZE, 4);
		NVDmaNext (pNv, (height << 16) | width);
		NVDmaNext (pNv, src_pitch);
		NVDmaNext (pNv, src_offset);
		NVDmaNext (pNv, src_point);
		pbox++;
	}

	if (!pNv->useEXA) {
		if(pNv->CurrentLayout.depth == 15) {
			NVDmaStart(pNv, NvSubContextSurfaces,
					SURFACE_FORMAT, 1);
			NVDmaNext (pNv, SURFACE_FORMAT_R5G6B5);
		}
	}

	NVDmaKickoff(pNv);

	if (pNv->useEXA)
		exaMarkSync(pScrn->pScreen);
	else
		SET_SYNC_FLAG(pNv->AccelInfoRec);

	pPriv->videoStatus = FREE_TIMER;
	pPriv->videoTime = currentTime.milliseconds + FREE_DELAY;
	pNv->VideoTimerCallback = NVVideoTimerCallback;
}

/*
 * StopVideo
 */
static void
NVStopOverlayVideo(ScrnInfoPtr pScrn, pointer data, Bool Exit)
{
	NVPtr         pNv   = NVPTR(pScrn);
	NVPortPrivPtr pPriv = (NVPortPrivPtr)data;

	if(pPriv->grabbedByV4L) return;

	REGION_EMPTY(pScrn->pScreen, &pPriv->clip);

	if(Exit) {
		if (pPriv->videoStatus & CLIENT_VIDEO_ON)
			NVStopOverlay(pScrn);
		NVFreeOverlayMemory(pScrn);
		pPriv->videoStatus = 0;
	} else {
		if (pPriv->videoStatus & CLIENT_VIDEO_ON) {
			pPriv->videoStatus = OFF_TIMER | CLIENT_VIDEO_ON;
			pPriv->videoTime = currentTime.milliseconds + OFF_DELAY;
			pNv->VideoTimerCallback = NVVideoTimerCallback;
		}
	}
}

/**
 * NVStopBlitVideo
 * TODO ?
 */
static void
NVStopBlitVideo(ScrnInfoPtr pScrn, pointer data, Bool Exit)
{
}

/**
 * NVSetOverlayPortAttribute
 * sets the attribute "attribute" of port "data" to value "value"
 * calls NVResetVideo(pScrn) to apply changes to hardware
 * 
 * @param pScrenInfo
 * @param attribute attribute to set
 * @param value value to which attribute is to be set
 * @param data port from which the attribute is to be set
 * 
 * @return Success, if setting is successful
 * BadValue/BadMatch, if value/attribute are invalid
 * @see NVResetVideo(ScrnInfoPtr pScrn)
 */
static int
NVSetOverlayPortAttribute(ScrnInfoPtr pScrn, Atom attribute,
			  INT32 value, pointer data)
{
	NVPortPrivPtr pPriv = (NVPortPrivPtr)data;

	if (attribute == xvBrightness) {
		if ((value < -512) || (value > 512))
			return BadValue;
		pPriv->brightness = value;
	} else
	if (attribute == xvDoubleBuffer) {
		if ((value < 0) || (value > 1))
			return BadValue;
		pPriv->doubleBuffer = value;
	} else
	if (attribute == xvContrast) {
		if ((value < 0) || (value > 8191))
			return BadValue;
		pPriv->contrast = value;
	} else
	if (attribute == xvHue) {
		value %= 360;
		if (value < 0)
			value += 360;
		pPriv->hue = value;
	} else
	if (attribute == xvSaturation) {
		if ((value < 0) || (value > 8191))
			return BadValue;
		pPriv->saturation = value;
	} else
	if (attribute == xvColorKey) {
		pPriv->colorKey = value;
		REGION_EMPTY(pScrn->pScreen, &pPriv->clip);
	} else
	if (attribute == xvAutopaintColorKey) {
		if ((value < 0) || (value > 1))
			return BadValue;
		pPriv->autopaintColorKey = value;
	} else
	if (attribute == xvITURBT709) {
		if ((value < 0) || (value > 1))
			return BadValue;
		pPriv->iturbt_709 = value;
	} else
	if (attribute == xvSetDefaults) {
		NVSetPortDefaults(pScrn, pPriv);
	} else
		return BadMatch;

	NVResetVideo(pScrn);
	return Success;
}

/**
 * NVGetOverlayPortAttribute
 * 
 * @param pScrn unused
 * @param attribute attribute to be read
 * @param value value of attribute will be stored in this pointer
 * @param data port from which attribute will be read
 * @return Success, if queried attribute exists
 */
static int
NVGetOverlayPortAttribute(ScrnInfoPtr pScrn, Atom attribute,
			  INT32 *value, pointer data)
{
	NVPortPrivPtr pPriv = (NVPortPrivPtr)data;

	if (attribute == xvBrightness)
		*value = pPriv->brightness;
	else if (attribute == xvDoubleBuffer)
		*value = (pPriv->doubleBuffer) ? 1 : 0;
	else if (attribute == xvContrast)
		*value = pPriv->contrast;
	else if (attribute == xvSaturation)
		*value = pPriv->saturation;
	else if (attribute == xvHue)
		*value = pPriv->hue;
	else if (attribute == xvColorKey)
		*value = pPriv->colorKey;
	else if (attribute == xvAutopaintColorKey)
		*value = (pPriv->autopaintColorKey) ? 1 : 0;
	else if (attribute == xvITURBT709)
		*value = (pPriv->iturbt_709) ? 1 : 0;
	else
		return BadMatch;

	return Success;
}

/**
 * NVSetBlitPortAttribute
 * sets the attribute "attribute" of port "data" to value "value"
 * supported attributes:
 * - xvSyncToVBlank (values: 0,1)
 * - xvSetDefaults (values: NA; SyncToVBlank will be set, if hardware supports it)
 * 
 * @param pScrenInfo
 * @param attribute attribute to set
 * @param value value to which attribute is to be set
 * @param data port from which the attribute is to be set
 * 
 * @return Success, if setting is successful
 * BadValue/BadMatch, if value/attribute are invalid
 */
static int
NVSetBlitPortAttribute(ScrnInfoPtr pScrn, Atom attribute,
		       INT32 value, pointer data)
{
	NVPortPrivPtr pPriv = (NVPortPrivPtr)data;
	NVPtr           pNv = NVPTR(pScrn);

	if ((attribute == xvSyncToVBlank) && pNv->WaitVSyncPossible) {
		if ((value < 0) || (value > 1))
			return BadValue;
		pPriv->SyncToVBlank = value;
	} else
	if (attribute == xvSetDefaults) {
		pPriv->SyncToVBlank = pNv->WaitVSyncPossible;
	} else
		return BadMatch;

	return Success;
}

/**
 * NVGetBlitPortAttribute
 * reads the value of attribute "attribute" from port "data" into INT32 "*value"
 * currently only one attribute supported: xvSyncToVBlank
 * 
 * @param pScrn unused
 * @param attribute attribute to be read
 * @param value value of attribute will be stored here
 * @param data port from which attribute will be read
 * @return Success, if queried attribute exists
 */
static int
NVGetBlitPortAttribute(ScrnInfoPtr pScrn, Atom attribute,
		       INT32 *value, pointer data)
{
	NVPortPrivPtr pPriv = (NVPortPrivPtr)data;

	if(attribute == xvSyncToVBlank)
		*value = (pPriv->SyncToVBlank) ? 1 : 0;
	else
		return BadMatch;

	return Success;
}


/**
 * QueryBestSize
 * used by client applications to ask the driver:
 * how would you actually scale a video of dimensions
 * vid_w, vid_h, if i wanted you to scale it to dimensions
 * drw_w, drw_h?
 * function stores actual scaling size in pointers p_w, p_h.
 * 
 * - currently the image cannot be scaled to less than
 * 1/8th of the original size in either dimension. why?
 * - what happens if the client requests a scaling to a larger value than
 * the hardware is capable of (IMAGE_MAX_W, IMAGE_MAX_H)?
 * 
 * @param pScrn unused
 * @param motion unused
 * @param vid_w width of source video
 * @param vid_h height of source video
 * @param drw_w desired scaled width as requested by client
 * @param drw_h desired scaled height as requested by client
 * @param p_w actual scaled width as the driver is capable of
 * @param p_h actual scaled height as the driver is capable of
 * @param data unused
 */
static void
NVQueryBestSize(ScrnInfoPtr pScrn, Bool motion,
		short vid_w, short vid_h, 
		short drw_w, short drw_h, 
		unsigned int *p_w, unsigned int *p_h, 
		pointer data)
{
	if(vid_w > (drw_w << 3))
		drw_w = vid_w >> 3;
	if(vid_h > (drw_h << 3))
		drw_h = vid_h >> 3;

	*p_w = drw_w;
	*p_h = drw_h; 
}

/**
 * NVCopyData420
 * used by NVPutImage() function to copy (image)data from
 * system RAM to VRAM and change data order.
 * 
 * @param src1 source buffer of luma
 * @param src2 source buffer of chroma1
 * @param src3 source buffer of chroma2
 * @param dst1 destination buffer
 * @param srcPitch pitch of src1
 * @param srcPitch2 pitch of src2, src3
 * @param dstPitch pitch of dst1
 * @param h number of lines to copy
 * @param w length of lines to copy
 */
static inline void NVCopyData420(unsigned char *src1, unsigned char *src2,
			  unsigned char *src3, unsigned char *dst1,
			  int srcPitch, int srcPitch2,
			  int dstPitch,
			  int h, int w)
{
	CARD32 *dst;
	CARD8 *s1, *s2, *s3;
	int i, j;

	w >>= 1;

	for (j = 0; j < h; j++) {
		dst = (CARD32*)dst1;
		s1 = src1;  s2 = src2;  s3 = src3;
		i = w;

		while (i > 4) { // wouldn't it be better to write (i >= 4) ?
#if X_BYTE_ORDER == X_BIG_ENDIAN
		dst[0] = (s1[0] << 24) | (s1[1] << 8) | (s3[0] << 16) | s2[0];
		dst[1] = (s1[2] << 24) | (s1[3] << 8) | (s3[1] << 16) | s2[1];
		dst[2] = (s1[4] << 24) | (s1[5] << 8) | (s3[2] << 16) | s2[2];
		dst[3] = (s1[6] << 24) | (s1[7] << 8) | (s3[3] << 16) | s2[3];
#else
		dst[0] = s1[0] | (s1[1] << 16) | (s3[0] << 8) | (s2[0] << 24);
		dst[1] = s1[2] | (s1[3] << 16) | (s3[1] << 8) | (s2[1] << 24);
		dst[2] = s1[4] | (s1[5] << 16) | (s3[2] << 8) | (s2[2] << 24);
		dst[3] = s1[6] | (s1[7] << 16) | (s3[3] << 8) | (s2[3] << 24);
#endif
		dst += 4; s2 += 4; s3 += 4; s1 += 8;
		i -= 4;
		}

		while (i--) {
#if X_BYTE_ORDER == X_BIG_ENDIAN
		dst[0] = (s1[0] << 24) | (s1[1] << 8) | (s3[0] << 16) | s2[0];
#else
		dst[0] = s1[0] | (s1[1] << 16) | (s3[0] << 8) | (s2[0] << 24);
#endif
		dst++; s2++; s3++;
		s1 += 2;
		}

		dst1 += dstPitch;
		src1 += srcPitch;
		if (j & 1) {
			src2 += srcPitch2;
			src3 += srcPitch2;
		}
	}
}


/**
 * NVPutImage
 * PutImage is "the" important function of the Xv extention.
 * a client (e.g. video player) calls this function for every
 * image (of the video) to be displayed. this function then
 * scales and displays the image.
 * 
 * @param pScrn screen which hold the port where the image is put
 * @param src_x
 * @param src_y
 * @param src_w
 * @param src_h
 * @param drw_x
 * @param drw_y
 * @param drw_w
 * @param drw_h
 * @param id colorspace of image
 * @param buf pointer to buffer containing the source image
 * @param width
 * @param height
 * @param Sync unused
 * @param clipBoxes
 * @param data pointer to port 
 * @param pDraw
 */
static int
NVPutImage(ScrnInfoPtr  pScrn, short src_x, short src_y,
				   short drw_x, short drw_y,
				   short src_w, short src_h, 
				   short drw_w, short drw_h,
				   int id,
				   unsigned char *buf, 
				   short width, short height, 
				   Bool         Sync,
				   RegionPtr    clipBoxes,
				   pointer      data,
				   DrawablePtr  pDraw
)
{
	NVPortPrivPtr pPriv = (NVPortPrivPtr)data;
	NVPtr pNv = NVPTR(pScrn);
	INT32 xa, xb, ya, yb;
	int newSize, offset, s2offset, s3offset;
	int srcPitch, srcPitch2, dstPitch;
	int top, left, right, bottom, npixels, nlines, bpp;
	Bool skip = FALSE;
	BoxRec dstBox;
	CARD32 tmp;
	int line_len;
	
	/* s2offset, s3offset - byte offsets into U and V plane of the
	 *                      source where copying starts.  YV12 is indeed one plane of Y and two subsampled planes of U and V
	 * offset - byte offset to the first line of the destination.
	 * dst_start - byte address to the first displayed pel.
	 */

	if (pPriv->grabbedByV4L)
		return Success;

	/* make the compiler happy */
	s2offset = s3offset = srcPitch2 = 0;

	if (!pPriv->blitter) { /* overlay hardware scaler limitation */
		if (src_w > (drw_w << 3))
			drw_w = src_w >> 3;
		if (src_h > (drw_h << 3))
			drw_h = src_h >> 3;
	}

	/* Clip */
	xa = src_x;
	xb = src_x + src_w;
	ya = src_y;
	yb = src_y + src_h;

	dstBox.x1 = drw_x;
	dstBox.x2 = drw_x + drw_w;
	dstBox.y1 = drw_y;
	dstBox.y2 = drw_y + drw_h;

	if (!xf86XVClipVideoHelper(&dstBox, &xa, &xb, &ya, &yb, clipBoxes,
				   width, height))
		return Success;

	if (!pPriv->blitter) {
		dstBox.x1 -= pScrn->frameX0;
		dstBox.x2 -= pScrn->frameX0;
		dstBox.y1 -= pScrn->frameY0;
		dstBox.y2 -= pScrn->frameY0;
	}

	
	/* determine required memory size */
	bpp = pScrn->bitsPerPixel >> 3; // bytes per pixel

	switch(id) {
	case FOURCC_YV12:
	case FOURCC_I420:
		srcPitch = (width + 3) & ~3;	/* of luma */
		s2offset = srcPitch * height;
		srcPitch2 = ((width >> 1) + 3) & ~3; /*of chroma*/
		s3offset = (srcPitch2 * (height >> 1)) + s2offset;
		dstPitch = ((width << 1) + 63) & ~63;
		break;
	case FOURCC_UYVY:
	case FOURCC_YUY2:
		srcPitch = width << 1;
		dstPitch = ((width << 1) + 63) & ~63;
		break;
	case FOURCC_RGB:
		srcPitch = width << 2;
		dstPitch = ((width << 2) + 63) & ~63;
		break;
	default:
		return BadImplementation;
	}
	/* dstPitch = number of bytes per row
	 but the allocation is done is pixel, hence the division to get the real number of bytes */
	newSize = height * dstPitch / bpp;
	
	if (pPriv->doubleBuffer) // double buffering ...
                newSize <<= 1; // ... means double the amount of VRAM needed
	
	pPriv->video_mem = NVAllocateOverlayMemory(pScrn, pPriv->video_mem, 
							      newSize);
	if (!pPriv->video_mem)
		return BadAlloc;

	offset = pPriv->video_mem->offset;
	if (pPriv->doubleBuffer) {
		int mask = 1 << (pPriv->currentBuffer << 2);

		/* overwrite the newest buffer if there's not one free */
		if (nvReadVIDEO(pNv, NV_PVIDEO_BUFFER) & mask) {
			if (!pPriv->currentBuffer)
				offset += (height + 1) * dstPitch;
			skip = TRUE;
		} else

		if (pPriv->currentBuffer)
			offset += (height + 1) * dstPitch;
	}


	/* We need to enlarge the copied rectangle by a pixel so the HW
	 * filtering doesn't pick up junk laying outside of the source */
	/* fixed point arithmetic */
	left = (xa - 0x00010000) >> 16;
	if (left < 0) left = 0;
	top = (ya - 0x00010000) >> 16;
	if (top < 0) top = 0;
	right = (xb + 0x0001ffff) >> 16;
	if (right > width) right = width;
	bottom = (yb + 0x0001ffff) >> 16;
	if (bottom > height) bottom = height;

	if(pPriv->blitter) NVSync(pScrn);

	
	switch(id) {
	case FOURCC_YV12:
	case FOURCC_I420:
		left &= ~1;
		npixels = ((right + 1) & ~1) - left;
		top &= ~1;
		nlines = ((bottom + 1) & ~1) - top;

		offset += (left << 1) + (top * dstPitch);
		tmp = ((top >> 1) * srcPitch2) + (left >> 1);
		s2offset += tmp;
		s3offset += tmp;
		if (id == FOURCC_I420) {
			tmp = s2offset;
			s2offset = s3offset;
			s3offset = tmp;
		}
		line_len = dstPitch;
		break;
	case FOURCC_UYVY:
	case FOURCC_YUY2:
		left &= ~1;
		npixels = ((right + 1) & ~1) - left;
		nlines = bottom - top;

		left <<= 1;
		buf += (top * srcPitch) + left;
		offset += left + (top * dstPitch);
		line_len = width << 1;
		break;
	case FOURCC_RGB:
		npixels = right - left;
		nlines = bottom - top;
		left <<= 2;
		buf += (top * srcPitch) + left;
		offset += left + (top * dstPitch);
		line_len = width << 2;
		break;
	default:
		return BadImplementation;
	}



	/*Below is *almost* a copypaste from NvAccelUploadM2MF, cannot use it directly because of YV12 -> YUY2 conversion */	

	NVDmaStart(pNv, NvSubMemFormat, MEMFORMAT_DMA_OBJECT_IN, 2);
	NVDmaNext (pNv, NvDmaTT);
	NVDmaNext (pNv, NvDmaFB);
	pNv->M2MFDirection = 1;
	int lc;
		
		/* Determine max amount of data we can DMA at once */
		if (nlines * line_len <= pNv->GARTScratch->size) {
			lc = nlines;
		} else {
			lc = pNv->GARTScratch->size / line_len;
		}
		
	while (nlines) { /*actually Xv doesn't like looping here much, especially for YV12*/
		char *dst = pNv->GARTScratch->map;
		
		/* Upload to GART */
		switch(id) {
		case FOURCC_YV12:
		case FOURCC_I420:
		
			NVCopyData420(buf + (top * srcPitch) + left,
				buf + s2offset, buf + s3offset,
				dst, srcPitch, srcPitch2,
				dstPitch, nlines, npixels);
			buf += srcPitch * lc; /*typically this will NOT WORK WITH YV12 so you need to have a large enough scratch zone.*/
			
			break;
		case FOURCC_UYVY:
		case FOURCC_YUY2:
		case FOURCC_RGB:
			memcpy(dst, buf, srcPitch * lc);
			buf += srcPitch * lc;
			break;
		default:
			return BadImplementation;
		}
		
			
		/* DMA to VRAM */
		NVNotifierReset(pScrn, pNv->Notifier0);
		NVDmaStart(pNv, NvSubMemFormat,
				NV_MEMORY_TO_MEMORY_FORMAT_NOTIFY, 1);
		NVDmaNext (pNv, 0);

		NVDmaStart(pNv, NvSubMemFormat,
				NV_MEMORY_TO_MEMORY_FORMAT_OFFSET_IN, 8);
		NVDmaNext (pNv, (uint32_t)pNv->GARTScratch->offset);
		NVDmaNext (pNv, (uint32_t)offset);
		NVDmaNext (pNv, line_len);
		NVDmaNext (pNv, dstPitch);
		NVDmaNext (pNv, line_len);
		NVDmaNext (pNv, lc);
		NVDmaNext (pNv, (1<<8)|1);
		NVDmaNext (pNv, 0);

		NVDmaKickoff(pNv);
		if (!NVNotifierWaitStatus(pScrn, pNv->Notifier0, 0, 0))
			//you lost
			return FALSE;

		nlines -= lc;
	}
	
	
	
	

	if (!skip) {
		if (pPriv->blitter) {
			NVPutBlitImage(pScrn, offset, id,
				       dstPitch, &dstBox,
				       xa, ya, xb, yb,
				       width, height,
				       src_w, src_h, drw_w, drw_h,
				       clipBoxes, pDraw);
		} else {
			NVPutOverlayImage(pScrn, offset, id,
					  dstPitch, &dstBox, 
					  xa, ya, xb, yb,
					  width, height,
					  src_w, src_h, drw_w, drw_h,
					  clipBoxes);
			pPriv->currentBuffer ^= 1;
		}
	}
	return Success;
}

/**
 * QueryImageAttributes
 * 
 * calculates
 * - size (memory required to store image),
 * - pitches,
 * - offsets
 * of image
 * depending on colorspace (id) and dimensions (w,h) of image
 * values of
 * - w,
 * - h
 * may be adjusted as needed
 * 
 * @param pScrn unused
 * @param id colorspace of image
 * @param w pointer to width of image
 * @param h pointer to height of image
 * @param pitches pitches[i] = length of a scanline in plane[i]
 * @param offsets offsets[i] = offset of plane i from the beginning of the image
 * @return size of the memory required for the XvImage queried
 */
static int
NVQueryImageAttributes(ScrnInfoPtr pScrn, int id, 
		       unsigned short *w, unsigned short *h, 
		       int *pitches, int *offsets)
{
	int size, tmp;

	if (*w > IMAGE_MAX_W)
		*w = IMAGE_MAX_W;
	if (*h > IMAGE_MAX_H)
		*h = IMAGE_MAX_H;

	*w = (*w + 1) & ~1; // width rounded up to an even number
	if (offsets)
		offsets[0] = 0;

	switch (id) {
	case FOURCC_YV12:
	case FOURCC_I420:
		*h = (*h + 1) & ~1; // height rounded up to an even number
		size = (*w + 3) & ~3; // width rounded up to a multiple of 4
		if (pitches)
			pitches[0] = size; // width rounded up to a multiple of 4
		size *= *h;
		if (offsets)
			offsets[1] = size; // number of pixels in "rounded up" image
		tmp = ((*w >> 1) + 3) & ~3; // width/2 rounded up to a multiple of 4
		if (pitches)
			pitches[1] = pitches[2] = tmp; // width/2 rounded up to a multiple of 4
		tmp *= (*h >> 1); // 1/4*number of pixels in "rounded up" image
		size += tmp; // 5/4*number of pixels in "rounded up" image
		if (offsets)
			offsets[2] = size; // 5/4*number of pixels in "rounded up" image
		size += tmp; // = 3/2*number of pixels in "rounded up" image
		break;
	case FOURCC_UYVY:
	case FOURCC_YUY2:
		size = *w << 1; // 2*width
		if (pitches)
			pitches[0] = size; // 2*width
		size *= *h; // 2*width*height
		break;
	case FOURCC_RGB:
		size = *w << 2; // 4*width (32 bit per pixel)
		if (pitches)
			pitches[0] = size; // 4*width
		size *= *h; // 4*width*height
		break;
	default:
		*w = *h = size = 0;
		break;
	}

	return size;
}

/***** Exported offscreen surface stuff ****/


static int
NVAllocSurface(ScrnInfoPtr pScrn, int id,
	       unsigned short w, unsigned short h,
	       XF86SurfacePtr surface)
{
	NVPtr pNv = NVPTR(pScrn);
	NVPortPrivPtr pPriv = GET_OVERLAY_PRIVATE(pNv); 
	int size, bpp;

	bpp = pScrn->bitsPerPixel >> 3;

	if (pPriv->grabbedByV4L)
		return BadAlloc;

	if ((w > IMAGE_MAX_W) || (h > IMAGE_MAX_H))
		return BadValue;

	w = (w + 1) & ~1;
	pPriv->pitch = ((w << 1) + 63) & ~63;
	size = h * pPriv->pitch / bpp;

	pPriv->video_mem = NVAllocateOverlayMemory(pScrn,
						   pPriv->video_mem,
						   size);
	if (!pPriv->video_mem)
		return BadAlloc;

	pPriv->offset = 0;
	
	surface->width = w;
	surface->height = h;
	surface->pScrn = pScrn;
	surface->pitches = &pPriv->pitch; 
	surface->offsets = &pPriv->offset;
	surface->devPrivate.ptr = (pointer)pPriv;
	surface->id = id;

	/* grab the video */
	NVStopOverlay(pScrn);
	pPriv->videoStatus = 0;
	REGION_EMPTY(pScrn->pScreen, &pPriv->clip);
	pPriv->grabbedByV4L = TRUE;

	return Success;
}

static int
NVStopSurface(XF86SurfacePtr surface)
{
	NVPortPrivPtr pPriv = (NVPortPrivPtr)(surface->devPrivate.ptr);

	if (pPriv->grabbedByV4L && pPriv->videoStatus) {
		NVStopOverlay(surface->pScrn);
		pPriv->videoStatus = 0;
	}

	return Success;
}

static int 
NVFreeSurface(XF86SurfacePtr surface)
{
	NVPortPrivPtr pPriv = (NVPortPrivPtr)(surface->devPrivate.ptr);

	if (pPriv->grabbedByV4L) {
		NVStopSurface(surface);
		NVFreeOverlayMemory(surface->pScrn);
		pPriv->grabbedByV4L = FALSE;
	}

	return Success;
}

static int
NVGetSurfaceAttribute(ScrnInfoPtr pScrn, Atom attribute, INT32 *value)
{
	NVPtr pNv = NVPTR(pScrn);
	NVPortPrivPtr pPriv = GET_OVERLAY_PRIVATE(pNv);

	return NVGetOverlayPortAttribute(pScrn, attribute,
					 value, (pointer)pPriv);
}

static int
NVSetSurfaceAttribute(ScrnInfoPtr pScrn, Atom attribute, INT32 value)
{
	NVPtr pNv = NVPTR(pScrn);
	NVPortPrivPtr pPriv = GET_OVERLAY_PRIVATE(pNv);

	return NVSetOverlayPortAttribute(pScrn, attribute,
					 value, (pointer)pPriv);
}

static int
NVDisplaySurface(XF86SurfacePtr surface,
		 short src_x, short src_y, 
		 short drw_x, short drw_y,
		 short src_w, short src_h, 
		 short drw_w, short drw_h,
		 RegionPtr clipBoxes)
{
	ScrnInfoPtr pScrn = surface->pScrn;
	NVPortPrivPtr pPriv = (NVPortPrivPtr)(surface->devPrivate.ptr);
	INT32 xa, xb, ya, yb;
	BoxRec dstBox;

	if (!pPriv->grabbedByV4L)
		return Success;

	if (src_w > (drw_w << 3))
		drw_w = src_w >> 3;
	if (src_h > (drw_h << 3))
		drw_h = src_h >> 3;

	/* Clip */
	xa = src_x;
	xb = src_x + src_w;
	ya = src_y;
	yb = src_y + src_h;

	dstBox.x1 = drw_x;
	dstBox.x2 = drw_x + drw_w;
	dstBox.y1 = drw_y;
	dstBox.y2 = drw_y + drw_h;

	if(!xf86XVClipVideoHelper(&dstBox, &xa, &xb, &ya, &yb, clipBoxes, 
				  surface->width, surface->height))
		return Success;

	dstBox.x1 -= pScrn->frameX0;
	dstBox.x2 -= pScrn->frameX0;
	dstBox.y1 -= pScrn->frameY0;
	dstBox.y2 -= pScrn->frameY0;

	pPriv->currentBuffer = 0;

	NVPutOverlayImage(pScrn, surface->offsets[0], surface->id,
			  surface->pitches[0], &dstBox, xa, ya, xb, yb,
			  surface->width, surface->height, src_w, src_h,
			  drw_w, drw_h, clipBoxes);

	return Success;
}

/**
 * NVSetupBlitVideo
 * this function does all the work setting up a blit port
 * 
 * @return blit port
 */
static XF86VideoAdaptorPtr
NVSetupBlitVideo (ScreenPtr pScreen)
{
	ScrnInfoPtr         pScrn = xf86Screens[pScreen->myNum];
	NVPtr               pNv       = NVPTR(pScrn);
	XF86VideoAdaptorPtr adapt;
	NVPortPrivPtr       pPriv;
	int i;

	if (!(adapt = xcalloc(1, sizeof(XF86VideoAdaptorRec) +
					sizeof(NVPortPrivRec) +
					(sizeof(DevUnion) * NUM_BLIT_PORTS)))) {
		return NULL;
	}

	adapt->type		= XvWindowMask | XvInputMask | XvImageMask;
	adapt->flags		= 0;
	adapt->name		= "NV Video Blitter";
	adapt->nEncodings	= 1;
	adapt->pEncodings	= &DummyEncoding;
	adapt->nFormats		= NUM_FORMATS_ALL;
	adapt->pFormats		= NVFormats;
	adapt->nPorts		= NUM_BLIT_PORTS;
	adapt->pPortPrivates	= (DevUnion*)(&adapt[1]);

	pPriv = (NVPortPrivPtr)(&adapt->pPortPrivates[NUM_BLIT_PORTS]);
	for(i = 0; i < NUM_BLIT_PORTS; i++)
		adapt->pPortPrivates[i].ptr = (pointer)(pPriv);

	if(pNv->WaitVSyncPossible) {
		adapt->pAttributes = NVBlitAttributes;
		adapt->nAttributes = NUM_BLIT_ATTRIBUTES;
	} else {
		adapt->pAttributes = NULL;
		adapt->nAttributes = 0;
	}

	adapt->pImages			= NVImages;
	adapt->nImages			= NUM_IMAGES_ALL;
	adapt->PutVideo			= NULL;
	adapt->PutStill			= NULL;
	adapt->GetVideo			= NULL;
	adapt->GetStill			= NULL;
	adapt->StopVideo		= NVStopBlitVideo;
	adapt->SetPortAttribute		= NVSetBlitPortAttribute;
	adapt->GetPortAttribute		= NVGetBlitPortAttribute;
	adapt->QueryBestSize		= NVQueryBestSize;
	adapt->PutImage			= NVPutImage;
	adapt->QueryImageAttributes	= NVQueryImageAttributes;

	pPriv->videoStatus		= 0;
	pPriv->grabbedByV4L		= FALSE;
	pPriv->blitter			= TRUE;
	pPriv->doubleBuffer		= FALSE;
	pPriv->SyncToVBlank		= pNv->WaitVSyncPossible;

	pNv->blitAdaptor		= adapt;
	xvSyncToVBlank			= MAKE_ATOM("XV_SYNC_TO_VBLANK");

	return adapt;
}

/**
 * NV10SetupOverlayVideo
 * this function does all the work setting up an overlay port
 * 
 * @return overlay port
 * @see NVResetVideo(ScrnInfoPtr pScrn)
 */
static XF86VideoAdaptorPtr 
NV10SetupOverlayVideo(ScreenPtr pScreen)
{
	ScrnInfoPtr         pScrn = xf86Screens[pScreen->myNum];
	NVPtr               pNv       = NVPTR(pScrn);
	XF86VideoAdaptorPtr adapt;
	NVPortPrivPtr       pPriv;

	if (!(adapt = xcalloc(1, sizeof(XF86VideoAdaptorRec) + 
					sizeof(NVPortPrivRec) + 
					sizeof(DevUnion)))) {
		return NULL;
	}

	adapt->type		= XvWindowMask | XvInputMask | XvImageMask;
	adapt->flags		= VIDEO_OVERLAID_IMAGES|VIDEO_CLIP_TO_VIEWPORT;
	adapt->name		= "NV Video Overlay";
	adapt->nEncodings	= 1;
	adapt->pEncodings	= &DummyEncoding;
	adapt->nFormats		= NUM_FORMATS_ALL;
	adapt->pFormats		= NVFormats;
	adapt->nPorts		= 1;
	adapt->pPortPrivates	= (DevUnion*)(&adapt[1]);

	pPriv = (NVPortPrivPtr)(&adapt->pPortPrivates[1]);
	adapt->pPortPrivates[0].ptr	= (pointer)(pPriv);

	adapt->pAttributes		= NVOverlayAttributes;
	adapt->nAttributes		= NUM_OVERLAY_ATTRIBUTES;
	adapt->pImages			= NVImages;
	adapt->nImages			= NUM_IMAGES_YUV;
	adapt->PutVideo			= NULL;
	adapt->PutStill			= NULL;
	adapt->GetVideo			= NULL;
	adapt->GetStill			= NULL;
	adapt->StopVideo		= NVStopOverlayVideo;
	adapt->SetPortAttribute		= NVSetOverlayPortAttribute;
	adapt->GetPortAttribute		= NVGetOverlayPortAttribute;
	adapt->QueryBestSize		= NVQueryBestSize;
	adapt->PutImage			= NVPutImage;
	adapt->QueryImageAttributes	= NVQueryImageAttributes;

	pPriv->videoStatus		= 0;
	pPriv->currentBuffer		= 0;
	pPriv->grabbedByV4L		= FALSE;
	pPriv->blitter			= FALSE;

	NVSetPortDefaults (pScrn, pPriv);

	/* gotta uninit this someplace */
	REGION_NULL(pScreen, &pPriv->clip);

	pNv->overlayAdaptor	= adapt;

	xvBrightness		= MAKE_ATOM("XV_BRIGHTNESS");
	xvDoubleBuffer		= MAKE_ATOM("XV_DOUBLE_BUFFER");
	xvContrast		= MAKE_ATOM("XV_CONTRAST");
	xvColorKey		= MAKE_ATOM("XV_COLORKEY");
	xvSaturation		= MAKE_ATOM("XV_SATURATION");
	xvHue			= MAKE_ATOM("XV_HUE");
	xvAutopaintColorKey	= MAKE_ATOM("XV_AUTOPAINT_COLORKEY");
	xvSetDefaults		= MAKE_ATOM("XV_SET_DEFAULTS");
	xvITURBT709		= MAKE_ATOM("XV_ITURBT_709");

	NVResetVideo(pScrn);

	return adapt;
}

XF86OffscreenImageRec NVOffscreenImages[2] = {
	{
		&NVImages[0],
		VIDEO_OVERLAID_IMAGES | VIDEO_CLIP_TO_VIEWPORT,
		NVAllocSurface,
		NVFreeSurface,
		NVDisplaySurface,
		NVStopSurface,
		NVGetSurfaceAttribute,
		NVSetSurfaceAttribute,
		IMAGE_MAX_W, IMAGE_MAX_H,
		NUM_OVERLAY_ATTRIBUTES - 1,
		&NVOverlayAttributes[1]
	},
	{
		&NVImages[2],
		VIDEO_OVERLAID_IMAGES | VIDEO_CLIP_TO_VIEWPORT,
		NVAllocSurface,
		NVFreeSurface,
		NVDisplaySurface,
		NVStopSurface,
		NVGetSurfaceAttribute,
		NVSetSurfaceAttribute,
		IMAGE_MAX_W, IMAGE_MAX_H,
		NUM_OVERLAY_ATTRIBUTES - 1,
		&NVOverlayAttributes[1]
	}
};

static void
NVInitOffscreenImages (ScreenPtr pScreen)
{
	xf86XVRegisterOffscreenImages(pScreen, NVOffscreenImages, 2);
}

/**
 * NVChipsetHasOverlay
 * 
 * newer chips don't support overlay anymore.
 * overlay feature is emulated via textures.
 * 
 * @param pNv 
 * @return true, if chipset supports overlay
 */
static Bool
NVChipsetHasOverlay(NVPtr pNv)
{
	switch (pNv->Architecture) {
	case NV_ARCH_10:
	case NV_ARCH_20:
	case NV_ARCH_30:
		return TRUE;
	case NV_ARCH_40:
		if ((pNv->Chipset & 0xfff0) == CHIPSET_NV40)
			return TRUE;
		break;
	default:
		break;
	}

	return FALSE;
}

/**
 * NVSetupOverlayVideo
 * check if chipset supports Overlay and CompositeExtension is disabled.
 * if so, setup overlay port
 * 
 * @return overlay port
 * @see NVChipsetHasOverlay(NVPtr pNv)
 * @see NV10SetupOverlayVideo(ScreenPtr pScreen)
 * @see NVInitOffscreenImages(ScreenPtr pScreen)
 */
static XF86VideoAdaptorPtr
NVSetupOverlayVideo(ScreenPtr pScreen)
{
	ScrnInfoPtr          pScrn = xf86Screens[pScreen->myNum];
	XF86VideoAdaptorPtr  overlayAdaptor = NULL;
	NVPtr                pNv   = NVPTR(pScrn);

	if (!NVChipsetHasOverlay(pNv))
		return NULL;

	/*XXX: Do we still want to provide the overlay anyway, but make the
	 *     blit adaptor the default if composite is enabled?
	 */
#ifdef COMPOSITE
/*	if (!noCompositeExtension) {
		xf86DrvMsg(pScrn->scrnIndex, X_INFO,
			"XV: Video overlay not available, composite enabled\n");
		return NULL;
	}*/
#endif
	overlayAdaptor = NV10SetupOverlayVideo(pScreen);
	if (overlayAdaptor)
		NVInitOffscreenImages(pScreen);

	return overlayAdaptor;
}

/**
 * NVInitVideo
 * tries to initialize one new overlay port and one new blit port
 * and add them to the list of ports on screen "pScreen".
 * 
 * @param pScreen
 * @see NVSetupOverlayVideo(ScreenPtr pScreen)
 * @see NVSetupBlitVideo(ScreenPtr pScreen)
 */
void NVInitVideo (ScreenPtr pScreen)
{
	ScrnInfoPtr          pScrn = xf86Screens[pScreen->myNum];
	XF86VideoAdaptorPtr *adaptors, *newAdaptors = NULL;
	XF86VideoAdaptorPtr  overlayAdaptor = NULL;
	XF86VideoAdaptorPtr  blitAdaptor = NULL;
	int                  num_adaptors;

	if (pScrn->bitsPerPixel == 8)
		return;

	overlayAdaptor = NVSetupOverlayVideo(pScreen);
	blitAdaptor    = NVSetupBlitVideo(pScreen);

	num_adaptors = xf86XVListGenericAdaptors(pScrn, &adaptors);
	if(blitAdaptor || overlayAdaptor) {
		int size = num_adaptors;

		if(overlayAdaptor) size++;
		if(blitAdaptor)    size++;

		newAdaptors = xalloc(size * sizeof(XF86VideoAdaptorPtr *));
		if(newAdaptors) {
			if(num_adaptors) {
				memcpy(newAdaptors, adaptors, num_adaptors *
						sizeof(XF86VideoAdaptorPtr));
			}

			if(overlayAdaptor) {
				newAdaptors[num_adaptors] = overlayAdaptor;
				num_adaptors++;
			}

			if(blitAdaptor) {
				newAdaptors[num_adaptors] = blitAdaptor;
				num_adaptors++;
			}

			adaptors = newAdaptors;
		}
	}

	if (num_adaptors)
		xf86XVScreenInit(pScreen, adaptors, num_adaptors);
	if (newAdaptors)
		xfree(newAdaptors);
}