aboutsummaryrefslogtreecommitdiffhomepage
path: root/libvo/vo_quartz.c
blob: 63092dd16dfbb55101dbad40d312ee27031a853d (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
/*
	vo_quartz.c
	
	by Nicolas Plourde <nicolasplourde@gmail.com>
	
	Copyright (c) Nicolas Plourde - April 2004

	YUV support Copyright (C) 2004 Romain Dolbeau <romain@dolbeau.org>
	
	MPlayer Mac OSX Quartz video out module.
	
	todo:	-screen overlay output
			-clear window background after live resize
			-fit osd in black bar when available
			-RGB32 lost HW accel in fullscreen
			-(add sugestion here)
 */

//SYS
#include <stdio.h>

//OSX
#include <Carbon/Carbon.h>
#include <QuickTime/QuickTime.h>

//MPLAYER
#include "config.h"
#include "fastmemcpy.h"
#include "video_out.h"
#include "video_out_internal.h"
#include "aspect.h"
#include "mp_msg.h"
#include "m_option.h"

#include "input/input.h"
#include "input/mouse.h"

#include "vo_quartz.h"

static vo_info_t info = 
{
	"Mac OSX (Quartz)",
	"quartz",
	"Nicolas Plourde <nicolasplourde@hotmail.com>, Romain Dolbeau <romain@dolbeau.org>",
	""
};

LIBVO_EXTERN(quartz)

static uint32_t image_depth;
static uint32_t image_format;
static uint32_t image_size;
static uint32_t image_buffer_size;
static char *image_data;

static ImageSequence seqId;
static CodecType image_qtcodec;
static PlanarPixmapInfoYUV420 *P = NULL;
static struct
{
	ImageDescriptionHandle desc;
	Handle extension_colr;
	Handle extension_fiel;
	Handle extension_clap;
	Handle extension_pasp;
} yuv_qt_stuff;
static MatrixRecord matrix;
static int EnterMoviesDone = 0;
static int get_image_done = 0;

extern int vo_rootwin;
extern int vo_ontop;
extern int vo_fs; // user want fullscreen
static int vo_quartz_fs; // we are in fullscreen
extern float monitor_aspect;
extern int vo_keepaspect; //keep aspect ratio when resizing
extern float movie_aspect;
static float old_movie_aspect;
extern float vo_panscan;

static int winLevel = 1;
int levelList[] =
{
    kCGDesktopWindowLevelKey,
    kCGNormalWindowLevelKey,
    kCGScreenSaverWindowLevelKey
};

static int int_pause = 0;
static float winAlpha = 1;

static int device_width;
static int device_height;
static int device_id;

static short fs_res_x=0;
static short fs_res_y=0;

static WindowRef theWindow = NULL;
static WindowGroupRef winGroup = NULL;
static CGContextRef context;
static CGRect bounds;
static GDHandle deviceHdl;

static CGDataProviderRef dataProviderRef;
static CGImageAlphaInfo alphaInfo;
static CGImageRef image;

static Rect imgRect; // size of the original image (unscaled)
static Rect dstRect; // size of the displayed image (after scaling)
static Rect winRect; // size of the window containg the displayed image (include padding)
static Rect oldWinRect; // size of the window containg the displayed image (include padding) when NOT in FS mode
static Rect deviceRect; // size of the display device
static Rect oldWinBounds;

static MenuRef windMenu;
static MenuRef movMenu;
static MenuRef aspectMenu;

static int border = 15;
enum
{
	kQuitCmd			= 1,
	kHalfScreenCmd		= 2,
	kNormalScreenCmd	= 3,
	kDoubleScreenCmd	= 4,
	kFullScreenCmd		= 5,
	kKeepAspectCmd		= 6,
	kAspectOrgCmd		= 7,
	kAspectFullCmd		= 8,
	kAspectWideCmd		= 9,
	kPanScanCmd		= 10
};

#include "osdep/keycodes.h"
extern void mplayer_put_key(int code);

extern void vo_draw_text(int dxs,int dys,void (*draw_alpha)(int x0,int y0, int w,int h, unsigned char* src, unsigned char *srca, int stride));

//PROTOTYPE/////////////////////////////////////////////////////////////////
void window_resized();
void window_ontop();
void window_fullscreen();
void window_panscan();

static inline int convert_key(UInt32 key, UInt32 charcode)
{
	switch(key)
    {
		case QZ_IBOOK_ENTER:
		case QZ_RETURN: return KEY_ENTER;
		case QZ_ESCAPE: return KEY_ESC;
		case QZ_BACKSPACE: return KEY_BACKSPACE;
		case QZ_LALT: return KEY_BACKSPACE;
		case QZ_LCTRL: return KEY_BACKSPACE;
		case QZ_LSHIFT: return KEY_BACKSPACE;
		case QZ_F1: return KEY_F+1;
		case QZ_F2: return KEY_F+2;
		case QZ_F3: return KEY_F+3;
		case QZ_F4: return KEY_F+4;
		case QZ_F5: return KEY_F+5;
		case QZ_F6: return KEY_F+6;
		case QZ_F7: return KEY_F+7;
		case QZ_F8: return KEY_F+8;
		case QZ_F9: return KEY_F+9;
		case QZ_F10: return KEY_F+10;
		case QZ_F11: return KEY_F+11;
		case QZ_F12: return KEY_F+12;
		case QZ_INSERT: return KEY_INSERT;
		case QZ_DELETE: return KEY_DELETE;
		case QZ_HOME: return KEY_HOME;
		case QZ_END: return KEY_END;
		case QZ_KP_PLUS: return '+';
		case QZ_KP_MINUS: return '-';
		case QZ_TAB: return KEY_TAB;
		case QZ_PAGEUP: return KEY_PAGE_UP;
		case QZ_PAGEDOWN: return KEY_PAGE_DOWN;  
		case QZ_UP: return KEY_UP;
		case QZ_DOWN: return KEY_DOWN;
		case QZ_LEFT: return KEY_LEFT;
		case QZ_RIGHT: return KEY_RIGHT;
		case QZ_KP_MULTIPLY: return '*';
		case QZ_KP_DIVIDE: return '/';
		case QZ_KP_ENTER: return KEY_BACKSPACE;
		case QZ_KP_PERIOD: return KEY_KPDEC;
		case QZ_KP0: return KEY_KP0;
		case QZ_KP1: return KEY_KP1;
		case QZ_KP2: return KEY_KP2;
		case QZ_KP3: return KEY_KP3;
		case QZ_KP4: return KEY_KP4;
		case QZ_KP5: return KEY_KP5;
		case QZ_KP6: return KEY_KP6;
		case QZ_KP7: return KEY_KP7;
		case QZ_KP8: return KEY_KP8;
		case QZ_KP9: return KEY_KP9;
		default: return charcode;
    }
}

static OSStatus MainWindowEventHandler(EventHandlerCallRef nextHandler, EventRef event, void *userData);
static OSStatus MainWindowCommandHandler(EventHandlerCallRef nextHandler, EventRef event, void *userData);

static void draw_alpha(int x0, int y0, int w, int h, unsigned char *src, unsigned char *srca, int stride)
{
	switch (image_format)
	{
		case IMGFMT_RGB32:
			vo_draw_alpha_rgb32(w,h,src,srca,stride,image_data+4*(y0*imgRect.right+x0),4*imgRect.right);
			break;
		case IMGFMT_YV12:
		case IMGFMT_IYUV:
		case IMGFMT_I420:
			vo_draw_alpha_yv12(w,h,src,srca,stride, ((char*)P) + P->componentInfoY.offset + x0 + y0 * imgRect.right, imgRect.right);
			break;
		case IMGFMT_UYVY:
			vo_draw_alpha_uyvy(w,h,src,srca,stride,((char*)P) + (x0 + y0 * imgRect.right) * 2,imgRect.right*2);
			break;
		case IMGFMT_YUY2:
			vo_draw_alpha_yuy2(w,h,src,srca,stride,((char*)P) + (x0 + y0 * imgRect.right) * 2,imgRect.right*2);
			break;
	}
}

//default window event handler
static OSStatus MainWindowEventHandler(EventHandlerCallRef nextHandler, EventRef event, void *userData)
{
    OSStatus result = noErr;
	UInt32 class = GetEventClass (event);
	UInt32 kind = GetEventKind (event); 

	result = CallNextEventHandler(nextHandler, event);
	
	if(class == kEventClassKeyboard)
	{
		char macCharCodes;
		UInt32 macKeyCode;
		UInt32 macKeyModifiers;
	
		GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(macCharCodes), NULL, &macCharCodes);
		GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, sizeof(macKeyCode), NULL, &macKeyCode);
		GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(macKeyModifiers), NULL, &macKeyModifiers);
		
		if(macKeyModifiers != 256)
		{
			if (kind == kEventRawKeyRepeat || kind == kEventRawKeyDown)
			{
				int key = convert_key(macKeyCode, macCharCodes);
				if(key != -1)
					mplayer_put_key(key);
			}
		}
		else if(macKeyModifiers == 256)
		{
			switch(macCharCodes)
			{
				case '[': SetWindowAlpha(theWindow, winAlpha-=0.05); break;
				case ']': SetWindowAlpha(theWindow, winAlpha+=0.05); break;		
			}	
		}
		else
			result = eventNotHandledErr;
	}
	else if(class == kEventClassMouse)
	{
		WindowPtr tmpWin;
		Point mousePos;

		GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, 0, sizeof(Point), 0, &mousePos);

		switch (kind)
		{
			case kEventMouseDown:
			{
				EventMouseButton button;
				short part;

				GetEventParameter(event, kEventParamMouseButton, typeMouseButton, 0, sizeof(EventMouseButton), 0, &button);
				
				part = FindWindow(mousePos,&tmpWin);
				
				if(part == inMenuBar)
				{
					MenuSelect(mousePos);
					HiliteMenu(0);
				}
				else if(part == inContent)
				{
					switch(button)
					{ 
						case 1: mplayer_put_key(MOUSE_BTN0);break;
						case 2: mplayer_put_key(MOUSE_BTN2);break;
						case 3: mplayer_put_key(MOUSE_BTN1);break;
				
						default:result = eventNotHandledErr;break;
					}
				}
			}		
			break;
			
			case kEventMouseWheelMoved:
			{
				int wheel;
				short part;

				GetEventParameter(event, kEventParamMouseWheelDelta, typeSInt32, 0, sizeof(int), 0, &wheel);

				part = FindWindow(mousePos,&tmpWin);
				
				if(part == inContent)
				{
					if(wheel > 0)
						mplayer_put_key(MOUSE_BTN3);
					else
						mplayer_put_key(MOUSE_BTN4);
				}
			}
			break;
			
			default:result = eventNotHandledErr;break;
		}
	}
	
    return result;
}

//default window command handler
static OSStatus MainWindowCommandHandler(EventHandlerCallRef nextHandler, EventRef event, void *userData)
{
    OSStatus result = noErr;
	uint32_t d_width;
	uint32_t d_height;
	UInt32 class = GetEventClass (event);
	UInt32 kind = GetEventKind (event); 

	result = CallNextEventHandler(nextHandler, event);
	
	aspect(&d_width,&d_height,A_NOZOOM);

	if(class == kEventClassCommand)
	{
		HICommand theHICommand;
		GetEventParameter( event, kEventParamDirectObject, typeHICommand, NULL, sizeof( HICommand ), NULL, &theHICommand );
		
		switch ( theHICommand.commandID )
		{
			case kHICommandQuit:
				mplayer_put_key(KEY_ESC);
				break;
				
			case kHalfScreenCmd:
					if(vo_quartz_fs)
					{
						vo_fs = (!(vo_fs)); window_fullscreen();
					}
						
					SizeWindow(theWindow, (d_width/2), ((d_width/movie_aspect)/2)+border, 1);
					window_resized();
				break;

			case kNormalScreenCmd:
					if(vo_quartz_fs)
					{
						vo_fs = (!(vo_fs)); window_fullscreen();
					}
						
					SizeWindow(theWindow, d_width, (d_width/movie_aspect)+border, 1);
					window_resized();
				break;

			case kDoubleScreenCmd:
					if(vo_quartz_fs)
					{
						vo_fs = (!(vo_fs)); window_fullscreen();
					}
						
					SizeWindow(theWindow, (d_width*2), ((d_width/movie_aspect)*2)+border, 1);
					window_resized();
				break;

			case kFullScreenCmd:
				vo_fs = (!(vo_fs)); window_fullscreen();
				break;

			case kKeepAspectCmd:
				vo_keepaspect = (!(vo_keepaspect));
				CheckMenuItem (aspectMenu, 1, vo_keepaspect);
				break;
				
			case kAspectOrgCmd:
				movie_aspect = old_movie_aspect;
				SizeWindow(theWindow, dstRect.right, (dstRect.right/movie_aspect)+border,1);
				window_resized();
				break;
				
			case kAspectFullCmd:
				movie_aspect = 4.0f/3.0f;
				SizeWindow(theWindow, dstRect.right, (dstRect.right/movie_aspect)+border,1);
				window_resized();
				break;
				
			case kAspectWideCmd:
				movie_aspect = 16.0f/9.0f;
				SizeWindow(theWindow, dstRect.right, (dstRect.right/movie_aspect)+border,1);
				window_resized();
				break;
				
			case kPanScanCmd:
				vo_panscan = (!(vo_panscan));
				CheckMenuItem (aspectMenu, 2, vo_panscan);
				break;
			
			default:
				result = eventNotHandledErr;
				break;
		}
	}
	else if(class == kEventClassWindow)
	{
		WindowRef     window;
		Rect          rectPort = {0,0,0,0};
		
		GetEventParameter(event, kEventParamDirectObject, typeWindowRef, NULL, sizeof(WindowRef), NULL, &window);
	
		if(window)
		{
			GetPortBounds(GetWindowPort(window), &rectPort);
		}   
	
		switch (kind)
		{
			case kEventWindowClosed:
				theWindow = NULL;
				mplayer_put_key(KEY_ESC);
				break;
				
			//resize window
			case kEventWindowBoundsChanged:
				window_resized();
				flip_page();
				break;
			
			default:
				result = eventNotHandledErr;
				break;
		}
	}
	
    return result;
}

static void quartz_CreateWindow(uint32_t d_width, uint32_t d_height, WindowAttributes windowAttrs) 
{
	CFStringRef		titleKey;
	CFStringRef		windowTitle; 
	OSStatus	       	result;
	
	MenuItemIndex index;
	CFStringRef movMenuTitle;
	CFStringRef aspMenuTitle;
 
	SetRect(&winRect, 0, 0, d_width, d_height);
	SetRect(&oldWinRect, 0, 0, d_width, d_height);
	SetRect(&dstRect, 0, 0, d_width, d_height);
	
	//Create Window Menu
	CreateStandardWindowMenu(0, &windMenu);
	InsertMenu(windMenu, 0);
	
	//Create Movie Menu
	CreateNewMenu (1004, 0, &movMenu);
	movMenuTitle = CFSTR("Movie");
	SetMenuTitleWithCFString(movMenu, movMenuTitle);
	
	AppendMenuItemTextWithCFString(movMenu, CFSTR("Half Size"), 0, kHalfScreenCmd, &index);
	SetMenuItemCommandKey(movMenu, index, 0, '0');
	
	AppendMenuItemTextWithCFString(movMenu, CFSTR("Normal Size"), 0, kNormalScreenCmd, &index);
	SetMenuItemCommandKey(movMenu, index, 0, '1');
	
	AppendMenuItemTextWithCFString(movMenu, CFSTR("Double Size"), 0, kDoubleScreenCmd, &index);
	SetMenuItemCommandKey(movMenu, index, 0, '2');
	
	AppendMenuItemTextWithCFString(movMenu, CFSTR("Full Size"), 0, kFullScreenCmd, &index);
	SetMenuItemCommandKey(movMenu, index, 0, 'F');
	
	AppendMenuItemTextWithCFString(movMenu, NULL, kMenuItemAttrSeparator, NULL, &index);

	AppendMenuItemTextWithCFString(movMenu, CFSTR("Aspect Ratio"), 0, NULL, &index);
	
	////Create Aspect Ratio Sub Menu
	CreateNewMenu (0, 0, &aspectMenu);
	aspMenuTitle = CFSTR("Aspect Ratio");
	SetMenuTitleWithCFString(aspectMenu, aspMenuTitle);
	SetMenuItemHierarchicalMenu(movMenu, 6, aspectMenu);
	
	AppendMenuItemTextWithCFString(aspectMenu, CFSTR("Keep"), 0, kKeepAspectCmd, &index);
	CheckMenuItem (aspectMenu, 1, vo_keepaspect);
	AppendMenuItemTextWithCFString(aspectMenu, CFSTR("Pan-Scan"), 0, kPanScanCmd, &index);
	CheckMenuItem (aspectMenu, 2, vo_panscan);
	AppendMenuItemTextWithCFString(aspectMenu, NULL, kMenuItemAttrSeparator, NULL, &index);
	AppendMenuItemTextWithCFString(aspectMenu, CFSTR("Original"), 0, kAspectOrgCmd, &index);
	AppendMenuItemTextWithCFString(aspectMenu, CFSTR("4:3"), 0, kAspectFullCmd, &index);
	AppendMenuItemTextWithCFString(aspectMenu, CFSTR("16:9"), 0, kAspectWideCmd, &index);
		
	InsertMenu(movMenu, GetMenuID(windMenu)); //insert before Window menu
	
	DrawMenuBar();
  
	//create window
	CreateNewWindow(kDocumentWindowClass, windowAttrs, &winRect, &theWindow);
	
	CreateWindowGroup(0, &winGroup);
	SetWindowGroup(theWindow, winGroup);

	//Set window title
	titleKey	= CFSTR("MPlayer - The Movie Player");
	windowTitle = CFCopyLocalizedString(titleKey, NULL);
	result		= SetWindowTitleWithCFString(theWindow, windowTitle);
	CFRelease(titleKey);
	CFRelease(windowTitle);
  
	//Install event handler
    const EventTypeSpec commands[] = {
        { kEventClassWindow, kEventWindowClosed },
		{ kEventClassWindow, kEventWindowBoundsChanged },
        { kEventClassCommand, kEventCommandProcess }
    };

    const EventTypeSpec events[] = {
		{ kEventClassKeyboard, kEventRawKeyDown },
		{ kEventClassKeyboard, kEventRawKeyRepeat },
		{ kEventClassMouse, kEventMouseDown },
		{ kEventClassMouse, kEventMouseWheelMoved }
    };

    
	InstallApplicationEventHandler (NewEventHandlerUPP (MainWindowEventHandler), GetEventTypeCount(events), events, NULL, NULL);	
	InstallWindowEventHandler (theWindow, NewEventHandlerUPP (MainWindowCommandHandler), GetEventTypeCount(commands), commands, theWindow, NULL);
}

static uint32_t config(uint32_t width, uint32_t height, uint32_t d_width, uint32_t d_height, uint32_t flags, char *title, uint32_t format)
{
	WindowAttributes	windowAttrs;
	OSErr				qterr;
	int i;

	//Get Main device info///////////////////////////////////////////////////


	deviceHdl = GetMainDevice();
	
	for(i=0; i<device_id; i++)
	{
		deviceHdl = GetNextDevice(deviceHdl);
		
		if(deviceHdl == NULL)
		{
			mp_msg(MSGT_VO, MSGL_FATAL, "Quartz error: Device ID %d do not exist, falling back to main device.\n", device_id);
			deviceHdl = GetMainDevice();
			break;
		}
	}
	
	deviceRect = (*deviceHdl)->gdRect;
	device_width = deviceRect.right-deviceRect.left;
	device_height = deviceRect.bottom-deviceRect.top;
	
	monitor_aspect = (float)device_width/(float)device_height;

	//misc mplayer setup/////////////////////////////////////////////////////
	SetRect(&imgRect, 0, 0, width, height);
	switch (image_format) 
	{
		case IMGFMT_RGB32:
			image_depth = 32;
			break;
		case IMGFMT_YV12:
		case IMGFMT_IYUV:
        case IMGFMT_I420:
        case IMGFMT_UYVY:
        case IMGFMT_YUY2:
			image_depth = 16;
			break;
	}
	image_size = ((imgRect.right*imgRect.bottom*image_depth)+7)/8;

	vo_fs = flags & VOFLAG_FULLSCREEN;
	
	//get movie aspect
	panscan_init();
	aspect_save_orig(width,height);
	aspect_save_prescale(d_width,d_height);
	aspect_save_screenres(device_width, device_height);
	
	aspect(&d_width,&d_height,A_NOZOOM);
	
	movie_aspect = (float)d_width/(float)d_height;
	old_movie_aspect = movie_aspect;
	
	if(image_data)
		free(image_data);
	
	image_data = malloc(image_size);

	//Create player window//////////////////////////////////////////////////
	windowAttrs =   kWindowStandardDocumentAttributes
					| kWindowStandardHandlerAttribute
					| kWindowCompositingAttribute
					| kWindowLiveResizeAttribute;
					
 	if (theWindow == NULL)
	{
		quartz_CreateWindow(d_width, d_height+border, windowAttrs);
		
		if (theWindow == NULL)
		{
			mp_msg(MSGT_VO, MSGL_FATAL, "Quartz error: Couldn't create window !!!!!\n");
			return -1;
		}
	}
	else 
	{
		HideWindow(theWindow);
		ChangeWindowAttributes(theWindow, ~windowAttrs, windowAttrs);
		SetRect(&winRect, 0, 0, d_width, d_height);
		SetRect(&oldWinRect, 0, 0, d_width, d_height);
		SizeWindow (theWindow, d_width, d_height, 1);
 	}
	
	//Show window
	SetThemeWindowBackground( theWindow, kThemeBrushModelessDialogBackgroundActive, TRUE);
	RepositionWindow(theWindow, NULL, kWindowCenterOnMainScreen);
	ShowWindow (theWindow);
	
	switch (image_format) 
	{
		case IMGFMT_RGB32:
		{
			CreateCGContextForPort (GetWindowPort (theWindow), &context);
			
			dataProviderRef = CGDataProviderCreateWithData (0, image_data, imgRect.right * imgRect.bottom * 4, 0);
			
			image = CGImageCreate   (imgRect.right,
									 imgRect.bottom,
									 8,
									 image_depth,
									 ((imgRect.right*32)+7)/8,
									 CGColorSpaceCreateDeviceRGB(),
									 kCGImageAlphaNoneSkipFirst,
									 dataProviderRef, 0, 1, kCGRenderingIntentDefault);
			break;
		}
			
		case IMGFMT_YV12:
		case IMGFMT_IYUV:
		case IMGFMT_I420:
		case IMGFMT_UYVY:
		case IMGFMT_YUY2:
		{
		 	get_image_done = 0;

			if (!EnterMoviesDone)
			{
				qterr = EnterMovies();
				EnterMoviesDone = 1;
			}
			else
				qterr = 0;
	
			if (qterr)
			{
				mp_msg(MSGT_VO, MSGL_FATAL, "Quartz error: EnterMovies (%d)\n", qterr);
				return -1;
			}
	
	
			SetIdentityMatrix(&matrix);
	
			if ((d_width != width) || (d_height != height))
			{
				ScaleMatrix(&matrix, FixDiv(Long2Fix(d_width),Long2Fix(width)), FixDiv(Long2Fix(d_height),Long2Fix(height)), 0, 0);
			}		

			yuv_qt_stuff.desc = (ImageDescriptionHandle)NewHandleClear( sizeof(ImageDescription) );
		
			yuv_qt_stuff.extension_colr = NewHandleClear(sizeof(NCLCColorInfoImageDescriptionExtension));
			((NCLCColorInfoImageDescriptionExtension*)(*yuv_qt_stuff.extension_colr))->colorParamType = kVideoColorInfoImageDescriptionExtensionType;
			((NCLCColorInfoImageDescriptionExtension*)(*yuv_qt_stuff.extension_colr))->primaries = 2;
			((NCLCColorInfoImageDescriptionExtension*)(*yuv_qt_stuff.extension_colr))->transferFunction = 2;
			((NCLCColorInfoImageDescriptionExtension*)(*yuv_qt_stuff.extension_colr))->matrix = 2;
		
			yuv_qt_stuff.extension_fiel = NewHandleClear(sizeof(FieldInfoImageDescriptionExtension));
			((FieldInfoImageDescriptionExtension*)(*yuv_qt_stuff.extension_fiel))->fieldCount = 1;
			((FieldInfoImageDescriptionExtension*)(*yuv_qt_stuff.extension_fiel))->fieldOrderings = 0;
		
			yuv_qt_stuff.extension_clap = NewHandleClear(sizeof(CleanApertureImageDescriptionExtension));
			((CleanApertureImageDescriptionExtension*)(*yuv_qt_stuff.extension_clap))->cleanApertureWidthN = imgRect.right;
			((CleanApertureImageDescriptionExtension*)(*yuv_qt_stuff.extension_clap))->cleanApertureWidthD = 1;
			((CleanApertureImageDescriptionExtension*)(*yuv_qt_stuff.extension_clap))->cleanApertureHeightN = imgRect.bottom;
			((CleanApertureImageDescriptionExtension*)(*yuv_qt_stuff.extension_clap))->cleanApertureHeightD = 1;
			((CleanApertureImageDescriptionExtension*)(*yuv_qt_stuff.extension_clap))->horizOffN = 0;
			((CleanApertureImageDescriptionExtension*)(*yuv_qt_stuff.extension_clap))->horizOffD = 1;
			((CleanApertureImageDescriptionExtension*)(*yuv_qt_stuff.extension_clap))->vertOffN = 0;
			((CleanApertureImageDescriptionExtension*)(*yuv_qt_stuff.extension_clap))->vertOffD = 1;
        
			yuv_qt_stuff.extension_pasp = NewHandleClear(sizeof(PixelAspectRatioImageDescriptionExtension));
			((PixelAspectRatioImageDescriptionExtension*)(*yuv_qt_stuff.extension_pasp))->hSpacing = 1;
			((PixelAspectRatioImageDescriptionExtension*)(*yuv_qt_stuff.extension_pasp))->vSpacing = 1;

			(*yuv_qt_stuff.desc)->idSize = sizeof(ImageDescription);
			(*yuv_qt_stuff.desc)->cType = image_qtcodec;
			(*yuv_qt_stuff.desc)->version = 2;
			(*yuv_qt_stuff.desc)->revisionLevel = 0;
			(*yuv_qt_stuff.desc)->vendor = 'mpla';
			(*yuv_qt_stuff.desc)->width = imgRect.right;
			(*yuv_qt_stuff.desc)->height = imgRect.bottom;
			(*yuv_qt_stuff.desc)->hRes = Long2Fix(72);
			(*yuv_qt_stuff.desc)->vRes = Long2Fix(72);
			(*yuv_qt_stuff.desc)->temporalQuality = 0;
			(*yuv_qt_stuff.desc)->spatialQuality = codecLosslessQuality;
			(*yuv_qt_stuff.desc)->frameCount = 1;
			(*yuv_qt_stuff.desc)->dataSize = 0;
			(*yuv_qt_stuff.desc)->depth = 24;
			(*yuv_qt_stuff.desc)->clutID = -1;
	  
			qterr = AddImageDescriptionExtension(yuv_qt_stuff.desc, yuv_qt_stuff.extension_colr, kColorInfoImageDescriptionExtension);
			if (qterr)
			{
				mp_msg(MSGT_VO, MSGL_ERR, "Quartz error: AddImageDescriptionExtension [colr] (%d)\n", qterr);
			}
			
			qterr = AddImageDescriptionExtension(yuv_qt_stuff.desc, yuv_qt_stuff.extension_fiel, kFieldInfoImageDescriptionExtension);
			if (qterr)
			{
				mp_msg(MSGT_VO, MSGL_ERR, "Quartz error: AddImageDescriptionExtension [fiel] (%d)\n", qterr);
			}
		
			qterr = AddImageDescriptionExtension(yuv_qt_stuff.desc, yuv_qt_stuff.extension_clap, kCleanApertureImageDescriptionExtension);
			if (qterr)
			{
				mp_msg(MSGT_VO, MSGL_ERR, "Quartz error: AddImageDescriptionExtension [clap] (%d)\n", qterr);
			}
		
			qterr = AddImageDescriptionExtension(yuv_qt_stuff.desc, yuv_qt_stuff.extension_pasp, kCleanApertureImageDescriptionExtension);
			if (qterr)
			{
				mp_msg(MSGT_VO, MSGL_ERR, "Quartz error: AddImageDescriptionExtension [pasp] (%d)\n", qterr);
			}
			if (P != NULL) { // second or subsequent movie
				free(P);
			}
			P = calloc(sizeof(PlanarPixmapInfoYUV420) + image_size, 1);
			switch (image_format)
			{
				case IMGFMT_YV12:
				case IMGFMT_IYUV:
				case IMGFMT_I420:
					P->componentInfoY.offset = sizeof(PlanarPixmapInfoYUV420);
					P->componentInfoCb.offset = P->componentInfoY.offset + image_size / 2;
					P->componentInfoCr.offset = P->componentInfoCb.offset + image_size / 4;
					P->componentInfoY.rowBytes = imgRect.right;
					P->componentInfoCb.rowBytes =  imgRect.right / 2;
					P->componentInfoCr.rowBytes =  imgRect.right / 2;
					image_buffer_size = image_size + sizeof(PlanarPixmapInfoYUV420);
					break;
				case IMGFMT_UYVY:
				case IMGFMT_YUY2:
					image_buffer_size = image_size;
					break;
			}

			qterr = DecompressSequenceBeginS(&seqId,
					   yuv_qt_stuff.desc,
					   (char *)P,
					   image_buffer_size,
					   GetWindowPort(theWindow),
					   NULL,
					   NULL,
					   ((d_width != width) || (d_height != height)) ? 
					   &matrix : NULL,
					   srcCopy,
					   NULL,
					   0,
					   codecLosslessQuality,
					   bestSpeedCodec);

			if (qterr)
			{
				mp_msg(MSGT_VO, MSGL_FATAL, "Quartz error: DecompressSequenceBeginS (%d)\n", qterr);
				return -1;
			}
		}
		break;
	}
	
	if(vo_fs)
		window_fullscreen();
		
	if(vo_ontop)
		window_ontop();
		
	if(vo_rootwin)
	{
		vo_fs = TRUE;
		winLevel = 0;
		SetWindowGroupLevel(winGroup, CGWindowLevelForKey(levelList[winLevel]));
		window_fullscreen();
	}
	
	return 0;
}

static void check_events(void)
{
	EventRef theEvent;
	EventTargetRef theTarget;
	OSStatus	theErr;
	
	//Get event
	theTarget = GetEventDispatcherTarget();
    theErr = ReceiveNextEvent(0, 0, kEventDurationNoWait,true, &theEvent);
    if(theErr == noErr && theEvent != NULL)
	{
		SendEventToEventTarget (theEvent, theTarget);
		ReleaseEvent(theEvent);
	}

	//update activity every 30 seconds to prevent
	//screensaver from starting up.
	DateTimeRec d;
	unsigned long curTime;
	static unsigned long lastTime = 0;
	
	GetTime(&d);
	DateToSeconds( &d, &curTime);
	
	if( ( (curTime - lastTime) >= 30) || (lastTime == 0))
	{
		UpdateSystemActivity(UsrActivity);
		lastTime = curTime;
	}
}

static void draw_osd(void)
{
	vo_draw_text(imgRect.right,imgRect.bottom,draw_alpha);
}

static void flip_page(void)
{
	if(theWindow == NULL)
		return;
		
	switch (image_format) 
	{
		case IMGFMT_RGB32:
		{
			CGContextDrawImage (context, bounds, image);
			CGContextFlush (context);
		}
		break;
			
		case IMGFMT_YV12:
		case IMGFMT_IYUV:
		case IMGFMT_I420:
		case IMGFMT_UYVY:
		case IMGFMT_YUY2:
			if (EnterMoviesDone)
			{
				OSErr qterr;
				CodecFlags flags = 0;
				qterr = DecompressSequenceFrameWhen(seqId,
													(char *)P,
													image_buffer_size,
													0, //codecFlagUseImageBuffer,
													&flags,
													NULL,
													NULL);
				if (qterr)
				{
					mp_msg(MSGT_VO, MSGL_ERR, "Quartz error: DecompressSequenceFrameWhen in flip_page (%d) flags:0x%08x\n", qterr, flags);
				}
			}
		break;
	}
}

static uint32_t draw_slice(uint8_t *src[], int stride[], int w,int h,int x,int y)
{
	switch (image_format)
	{
  		case IMGFMT_YV12:
  		case IMGFMT_I420:
 			memcpy_pic(((char*)P) + P->componentInfoY.offset + x + imgRect.right * y, src[0], w, h, imgRect.right, stride[0]);
  			x=x/2;y=y/2;w=w/2;h=h/2;
  
 			memcpy_pic(((char*)P) + P->componentInfoCb.offset + x + imgRect.right / 2 * y, src[1], w, h, imgRect.right / 2, stride[1]);
 			memcpy_pic(((char*)P) + P->componentInfoCr.offset + x + imgRect.right / 2 * y, src[2], w, h, imgRect.right / 2, stride[2]);
  			return 0;
  
  		case IMGFMT_IYUV:
 			memcpy_pic(((char*)P) + P->componentInfoY.offset + x + imgRect.right * y, src[0], w, h, imgRect.right, stride[0]);
  			x=x/2;y=y/2;w=w/2;h=h/2;
  			
 			memcpy_pic(((char*)P) + P->componentInfoCr.offset + x + imgRect.right / 2 * y, src[1], w, h, imgRect.right / 2, stride[1]);
 			memcpy_pic(((char*)P) + P->componentInfoCb.offset + x + imgRect.right / 2 * y, src[2], w, h, imgRect.right / 2, stride[2]);
  			return 0;
	}
	return -1;
}

static uint32_t draw_frame(uint8_t *src[])
{
	switch (image_format)
	{
		case IMGFMT_RGB32:
			memcpy(image_data,src[0],image_size);
			return 0;
			
		case IMGFMT_UYVY:
		case IMGFMT_YUY2:
			memcpy_pic(((char*)P), src[0], imgRect.right * 2, imgRect.bottom, imgRect.right * 2, imgRect.right * 2);
			return 0;
	}
	return -1;
}

static uint32_t query_format(uint32_t format)
{
	image_format = format;
	image_qtcodec = 0;

	if (format == IMGFMT_RGB32)
	{
		return VFCAP_CSP_SUPPORTED | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
    }
    
    if ((format == IMGFMT_YV12) || (format == IMGFMT_IYUV) || (format == IMGFMT_I420))
	{
		image_qtcodec = kMpegYUV420CodecType; //kYUV420CodecType ?;
		return VFCAP_CSP_SUPPORTED | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN | VFCAP_ACCEPT_STRIDE;
    }

    if (format == IMGFMT_YUY2)
	{
		image_qtcodec = kComponentVideoUnsigned;
		return VFCAP_CSP_SUPPORTED | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
    }
    
    if (format == IMGFMT_UYVY)
	{
		image_qtcodec = k422YpCbCr8CodecType;
		return VFCAP_CSP_SUPPORTED | VFCAP_OSD | VFCAP_HWSCALE_UP | VFCAP_HWSCALE_DOWN;
	}

    return 0;
}

static void uninit(void)
{
	OSErr qterr;
	
	switch (image_format)
	{
		case IMGFMT_YV12:
		case IMGFMT_IYUV:
		case IMGFMT_I420:
		case IMGFMT_UYVY:
		case IMGFMT_YUY2:
		{
			if (EnterMoviesDone)
			{
				qterr = CDSequenceEnd(seqId);
				if (qterr)
				{
					mp_msg(MSGT_VO, MSGL_ERR, "Quartz error: CDSequenceEnd (%d)\n", qterr);
				}
			}
			break;
		}
		default:
			break;
	}

	ShowMenuBar();
}

static uint32_t preinit(const char *arg)
{
	int parse_err = 0;
	
    if(arg) 
    {
        char *parse_pos = (char *)&arg[0];
        while (parse_pos[0] && !parse_err) 
		{
			if (strncmp (parse_pos, "device_id=", 10) == 0)
			{
				parse_pos = &parse_pos[10];
                device_id = strtol(parse_pos, &parse_pos, 0);
            }
            if (strncmp (parse_pos, "fs_res=", 7) == 0)
            {
				parse_pos = &parse_pos[7];
				fs_res_x = strtol(parse_pos, &parse_pos, 0);
				parse_pos = &parse_pos[1];
				fs_res_y = strtol(parse_pos, &parse_pos, 0);
            }
            if (parse_pos[0] == ':') parse_pos = &parse_pos[1];
            else if (parse_pos[0]) parse_err = 1;
        }
    }
	
#ifndef MACOSX_FINDER_SUPPORT
	//this chunk of code is heavily based off SDL_macosx.m from SDL 
	//it uses an Apple private function to request foreground operation

	void CPSEnableForegroundOperation(ProcessSerialNumber* psn);
	ProcessSerialNumber myProc, frProc;
	Boolean sameProc;
	
	if (GetFrontProcess(&frProc) == noErr)
	{
		if (GetCurrentProcess(&myProc) == noErr)
		{
			if (SameProcess(&frProc, &myProc, &sameProc) == noErr && !sameProc)
			{
				CPSEnableForegroundOperation(&myProc);
			}
			SetFrontProcess(&myProc);
		}
	}
#endif

    return 0;
}

static uint32_t draw_yuv_image(mp_image_t *mpi)
{
	// ATM we're only called for planar IMGFMT
	// drawing is done directly in P
	// and displaying is in flip_page.
	return get_image_done ? VO_TRUE : VO_FALSE;  
}

static uint32_t get_yuv_image(mp_image_t *mpi)
{
	if(mpi->type!=MP_IMGTYPE_EXPORT) return VO_FALSE;
  
	if(mpi->imgfmt!=image_format) return VO_FALSE;
  
	if(mpi->flags&MP_IMGFLAG_PLANAR)
	{
		if (mpi->num_planes != 3)
		{
			mp_msg(MSGT_VO, MSGL_ERR, "Quartz error: only 3 planes allowed in get_yuv_image for planar (%d) \n", mpi->num_planes);
			return VO_FALSE;
		}

		mpi->planes[0]=((char*)P) + P->componentInfoY.offset;
		mpi->stride[0]=imgRect.right;
		mpi->width=imgRect.right;

		if(mpi->flags&MP_IMGFLAG_SWAPPED)
		{
			// I420
			mpi->planes[1]=((char*)P) + P->componentInfoCb.offset;
			mpi->planes[2]=((char*)P) + P->componentInfoCr.offset;
			mpi->stride[1]=imgRect.right/2;
			mpi->stride[2]=imgRect.right/2;
		} 
		else 
		{
			// YV12
			mpi->planes[1]=((char*)P) + P->componentInfoCr.offset;
			mpi->planes[2]=((char*)P) + P->componentInfoCb.offset;
			mpi->stride[1]=imgRect.right/2;
			mpi->stride[2]=imgRect.right/2;
		}
		
		mpi->flags|=MP_IMGFLAG_DIRECT;
		get_image_done = 1;
		return VO_TRUE;
	}
	else 
	{ 
		// doesn't work yet
		if (mpi->num_planes != 1)
		{
			mp_msg(MSGT_VO, MSGL_ERR, "Quartz error: only 1 plane allowed in get_yuv_image for packed (%d) \n", mpi->num_planes);
			return VO_FALSE;
		}

		mpi->planes[0] = (char*)P;
		mpi->stride[0] = imgRect.right * 2;
		mpi->width=imgRect.right;
		mpi->flags|=MP_IMGFLAG_DIRECT;
		get_image_done = 1;
		return VO_TRUE;
	}
	return VO_FALSE;
}

static uint32_t control(uint32_t request, void *data, ...)
{
	switch (request)
	{
		case VOCTRL_PAUSE: return (int_pause=1);
		case VOCTRL_RESUME: return (int_pause=0);
		case VOCTRL_FULLSCREEN: vo_fs = (!(vo_fs)); window_fullscreen(); return VO_TRUE;
		case VOCTRL_ONTOP: vo_ontop = (!(vo_ontop)); window_ontop(); return VO_TRUE;
		case VOCTRL_QUERY_FORMAT: return query_format(*((uint32_t*)data));
		case VOCTRL_GET_PANSCAN: return VO_TRUE;
		case VOCTRL_SET_PANSCAN: window_panscan(); return VO_TRUE;
			
		case VOCTRL_GET_IMAGE:
			switch (image_format)
			{
				case IMGFMT_YV12:
				case IMGFMT_IYUV:
				case IMGFMT_I420:
				case IMGFMT_UYVY:
				case IMGFMT_YUY2:
					return get_yuv_image(data);
					break;
				default:
					break;
			}
		case VOCTRL_DRAW_IMAGE:
			switch (image_format)
			{
				case IMGFMT_YV12:
				case IMGFMT_IYUV:
				case IMGFMT_I420:
				case IMGFMT_UYVY:
				case IMGFMT_YUY2:
					return draw_yuv_image(data);
					break;
				default:
					break;
			}
	}
	return VO_NOTIMPL;
}

void window_resized()
{
	float aspectX;
	float aspectY;
	
	int padding = 0;
	
	uint32_t d_width;
	uint32_t d_height;
	
	CGRect tmpBounds;

	GetPortBounds( GetWindowPort(theWindow), &winRect );

	if(vo_keepaspect)
	{
	aspect( &d_width, &d_height, A_NOZOOM);
	d_height = ((float)d_width/movie_aspect);
	
	aspectX = (float)((float)winRect.right/(float)d_width);
	aspectY = (float)((float)(winRect.bottom-border)/(float)d_height);
	
	if((d_height*aspectX)>(winRect.bottom-border))
	{
		padding = (winRect.right - d_width*aspectY)/2;
		SetRect(&dstRect, padding, 0, d_width*aspectY+padding, d_height*aspectY);
	}
	else
	{
		padding = ((winRect.bottom-border) - d_height*aspectX)/2;
		SetRect(&dstRect, 0, padding, (d_width*aspectX), d_height*aspectX+padding);
	}
	}
	else
	{
		SetRect(&dstRect, 0, 0, winRect.right, winRect.bottom-border);
	}

	//Clear Background
	SetThemeWindowBackground( theWindow, kThemeBrushUtilityWindowBackgroundInactive, TRUE);
	tmpBounds = CGRectMake( 0, border, winRect.right, winRect.bottom);
	CreateCGContextForPort(GetWindowPort(theWindow),&context);
	CGContextClearRect(context, tmpBounds);
	
	switch (image_format)
	{
		case IMGFMT_RGB32:
		{
			bounds = CGRectMake(dstRect.left, dstRect.top+border, dstRect.right-dstRect.left, dstRect.bottom-dstRect.top);
			CreateCGContextForPort (GetWindowPort (theWindow), &context);
			break;
		}
		case IMGFMT_YV12:
		case IMGFMT_IYUV:
		case IMGFMT_I420:
		case IMGFMT_UYVY:
		case IMGFMT_YUY2:
		{
			long scale_X = FixDiv(Long2Fix(dstRect.right - dstRect.left),Long2Fix(imgRect.right));
			long scale_Y = FixDiv(Long2Fix(dstRect.bottom - dstRect.top),Long2Fix(imgRect.bottom));
			
			SetIdentityMatrix(&matrix);
			if (((dstRect.right - dstRect.left)   != imgRect.right) || ((dstRect.bottom - dstRect.right) != imgRect.bottom))
			{
				ScaleMatrix(&matrix, scale_X, scale_Y, 0, 0);
				
				if (padding > 0)
				{
					TranslateMatrix(&matrix, Long2Fix(dstRect.left), Long2Fix(dstRect.top));
				}
			}
			
			SetDSequenceMatrix(seqId, &matrix);
			break;
		}
		default:
			break;
	}
}

void window_ontop()
{
	if(!vo_quartz_fs)
	{
	//Cycle between level
	winLevel++;
	if(winLevel>2)
		winLevel = 0;
		
	//hide menu bar and mouse cursor if in fullscreen and quiting wallpaper mode
	if(vo_fs)
	{
		if(winLevel != 0)
		{
			if(device_id == 0)
			{
				HideMenuBar();
				HideCursor();
			}
		}
		else
		{
			ShowMenuBar();
			ShowCursor();
		}
	}

	}
	SetWindowGroupLevel(winGroup, CGWindowLevelForKey(levelList[winLevel]));
}

void window_fullscreen()
{
	static Ptr restoreState = NULL;

	//go fullscreen
	if(vo_fs)
	{
		if(winLevel != 0)
		{
			if(device_id == 0)
			{
				HideMenuBar();
				HideCursor();
			}
			
			if(fs_res_x != 0 || fs_res_y != 0)
			{
				BeginFullScreen( &restoreState, deviceHdl, &fs_res_x, &fs_res_y, NULL, NULL, NULL);
				
				//Get Main device info///////////////////////////////////////////////////
				deviceRect = (*deviceHdl)->gdRect;
        
				device_width = deviceRect.right;
				device_height = deviceRect.bottom;
			}
		}

		//save old window size
 		if (!vo_quartz_fs)
		{
			GetWindowPortBounds(theWindow, &oldWinRect);
			GetWindowBounds(theWindow, kWindowContentRgn, &oldWinBounds);
		}
		
		//go fullscreen
		border = 0;
		panscan_calc();
		ChangeWindowAttributes(theWindow, kWindowNoShadowAttribute, kWindowResizableAttribute);
		MoveWindow(theWindow, deviceRect.left-(vo_panscan_x >> 1), deviceRect.top-(vo_panscan_y >> 1), 1);
		SizeWindow(theWindow, device_width+vo_panscan_x, device_height+vo_panscan_y,1);

		vo_quartz_fs = 1;
	}
	else //go back to windowed mode
	{
		if(restoreState != NULL)
		{
			EndFullScreen(restoreState, NULL);
		
			//Get Main device info///////////////////////////////////////////////////
			deviceRect = (*deviceHdl)->gdRect;
        
			device_width = deviceRect.right;
			device_height = deviceRect.bottom;
			restoreState = NULL;
		}
		ShowMenuBar();

		//show mouse cursor
		ShowCursor();
		
		//revert window to previous setting
		border = 15;
		ChangeWindowAttributes(theWindow, kWindowResizableAttribute, kWindowNoShadowAttribute);
		SizeWindow(theWindow, oldWinRect.right, oldWinRect.bottom,1);
		MoveWindow(theWindow, oldWinBounds.left, oldWinBounds.top, 1);

 		vo_quartz_fs = 0;
	}
	
}

void window_panscan()
{
	panscan_calc();
	
	if(vo_panscan > 0)
		CheckMenuItem (aspectMenu, 2, 1);
	else
		CheckMenuItem (aspectMenu, 2, 0);
	
	if(vo_quartz_fs)
	{
		MoveWindow(theWindow, deviceRect.left-(vo_panscan_x >> 1), deviceRect.top-(vo_panscan_y >> 1), 1);
		SizeWindow(theWindow, device_width+vo_panscan_x, device_height+vo_panscan_y,1);
	}
}