-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing7.html
executable file
·1266 lines (978 loc) · 46.7 KB
/
listing7.html
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>CIVideoDemoGL - /VideoView.m</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html">Reference Library</a> > <a href="../../samplecode/index.html">Sample Code</a> > <a href="../../samplecode/QuickTime/index.html">QuickTime</a> > <a href="../../samplecode/QuickTime/idxMovieBasics-date.html">Movie Basics</a> > <A HREF="javascript:location.replace('index.html');">CIVideoDemoGL</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">CIVideoDemoGL</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/VideoView.m</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/main.m</option>
<option value="listing2.html">/TimeCodeOverlay.h</option>
<option value="listing3.html">/TimeCodeOverlay.m</option>
<option value="listing4.html">/VideoController.h</option>
<option value="listing5.html">/VideoController.m</option>
<option value="listing6.html">/VideoView.h</option>
<option value="listing7.html">/VideoView.m</option></select>
</p>
</form>
<p><strong><a href="CIVideoDemoGL.zip">Download Sample</a></strong> (“CIVideoDemoGL.zip”, 98.4K)<BR>
<strong><a href="CIVideoDemoGL.dmg">Download Sample</a></strong> (“CIVideoDemoGL.dmg”, 151.9K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox">/*
File: VideoView.m
Abstract: NSOpenGLView subclass that handles the rendering off the movie.
Version: 1.0.3
© Copyright 2005-2007 Apple Inc., All rights reserved.
IMPORTANT: This Apple software is supplied to
you by Apple Computer, Inc. ("Apple") in
consideration of your agreement to the following
terms, and your use, installation, modification
or redistribution of this Apple software
constitutes acceptance of these terms. If you do
not agree with these terms, please do not use,
install, modify or redistribute this Apple
software.
In consideration of your agreement to abide by
the following terms, and subject to these terms,
Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this
original Apple software (the "Apple Software"),
to use, reproduce, modify and redistribute the
Apple Software, with or without modifications, in
source and/or binary forms; provided that if you
redistribute the Apple Software in its entirety
and without modifications, you must retain this
notice and the following text and disclaimers in
all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or
logos of Apple Computer, Inc. may be used to
endorse or promote products derived from the
Apple Software without specific prior written
permission from Apple. Except as expressly
stated in this notice, no other rights or
licenses, express or implied, are granted by
Apple herein, including but not limited to any
patent rights that may be infringed by your
derivative works or by other works in which the
Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS
IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR
IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING
THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE
OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY
SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF
THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER
UNDER THEORY OF CONTRACT, TORT (INCLUDING
NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN
IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
#import "VideoView.h"
#import "VideoController.h"
#include <mach/mach_time.h>
@interface VideoView (private)
- (CVReturn)renderTime:(const CVTimeStamp *)timeStamp;
- (GLenum)readbackFrameIntoBuffer:(void*)buffer alignment:(int)alignment width:(int)width height:(int)height offsetX:(int)offsetX offsetY:(int)offsetY;
- (OSErr)exportFrame:(MovieExportGetDataParams *)theParams;
@end
#pragma mark--callbacks--
static CVReturn renderCallback(CVDisplayLinkRef displayLink,
const CVTimeStamp *inNow,
const CVTimeStamp *inOutputTime,
CVOptionFlags flagsIn,
CVOptionFlags *flagsOut,
void *displayLinkContext)
{
return [(VideoView*)displayLinkContext renderTime:inOutputTime];
}
//--------------------------------------------------------------------------------------------------
// Handle requests for information about the output video data
static OSErr QTMoovProcs_VideoTrackPropertyProc (void *theRefcon, long theTrackID, OSType thePropertyType, void *thePropertyValue)
{
#pragma unused(theRefcon, theTrackID)
OSErr myErr = noErr;
switch (thePropertyType) {
case movieExportUseConfiguredSettings:
*(Boolean *)thePropertyValue = true;
break;
default:
myErr = paramErr; // non-zero value means: use default value provided by export component
break;
}
return(myErr);
}
//--------------------------------------------------------------------------------------------------
// Provide the output audio data.
static OSErr QTMoovProcs_VideoTrackDataProc(void *theRefcon, MovieExportGetDataParams *theParams)
{
return [(VideoView*)theRefcon exportFrame:theParams];
}
//--------------------------------------------------------------------------------------------------
// Drive the UI during the iPod export process
static pascal OSErr QTMoovProcs_PodExportProgress(Movie theMovie, short message, short whatOperation, Fixed percentDone, long refcon)
{
VideoController *controller = (VideoController *)refcon;
if (nil == controller) return paramErr;
switch (message) {
case movieProgressOpen:
[NSApp beginSheet: [controller progressSheet] modalForWindow: [[controller videoView] window] modalDelegate: nil didEndSelector: nil contextInfo: nil];
[[controller progressIndicator] setDoubleValue:0.0];
[[controller progressIndicator] display];
break;
case movieProgressUpdatePercent:
{
[[controller progressIndicator] setDoubleValue:Fix2X(percentDone)];
[[controller progressIndicator] display];
}
break;
case movieProgressClose:
[[controller progressIndicator] setDoubleValue:Fix2X(percentDone)];
[[controller progressIndicator] display];
[NSApp endSheet: [controller progressSheet]];
[[controller progressSheet] orderOut:controller];
break;
}
return noErr;
}
#pragma mark-
@implementation VideoView
//--------------------------------------------------------------------------------------------------
- (BOOL)isOpaque
{
return YES;
}
//--------------------------------------------------------------------------------------------------
- (void)updateCIContext
{
[ciContext release];
// Create CIContext
ciContext = [[CIContext contextWithCGLContext:(CGLContextObj)[[self openGLContext] CGLContextObj]
pixelFormat:(CGLPixelFormatObj)[[self pixelFormat] CGLPixelFormatObj]
options:[NSDictionary dictionaryWithObjectsAndKeys:
(id)displayColorSpace, kCIContextOutputColorSpace,
(id)displayColorSpace, kCIContextWorkingColorSpace, nil]] retain];
}
// setup the display color space, this function in null safe
- (void)setDisplayColorSpace:(CGColorSpaceRef)inDisplayColorSpace
{
CGColorSpaceRetain(inDisplayColorSpace);
CGColorSpaceRelease(displayColorSpace);
displayColorSpace = inDisplayColorSpace;
}
- (void)updateColorProfile:(CGDirectDisplayID)did
{
CMProfileRef profile;
[self setDisplayColorSpace:NULL];
if ([delegate useTrickProfile] == NSOnState) {
CMProfileLocation loc = { cmPathBasedProfile };
NSString *path = [[NSBundle mainBundle] pathForResource:@"TrickGRBProfile" ofType:@"icc"];
// Copy the path the profile into the CMProfileLocation structure
strcpy(loc.u.pathLoc.path, [path cStringUsingEncoding:NSMacOSRomanStringEncoding]);
CMOpenProfile(&profile, &loc);
} else {
CMGetProfileByAVID((CMDisplayIDType)did, &profile);
}
if (NULL != profile) {
CGColorSpaceRef theDisplayColorSpace = CGColorSpaceCreateWithPlatformColorSpace(profile);
[self setDisplayColorSpace:theDisplayColorSpace];
CGColorSpaceRelease(theDisplayColorSpace);
CMCloseProfile(profile);
}
if (NULL != qtVisualContext) {
// Update the visual context output color space - if this attribute is not set, images may be in any color space
QTVisualContextSetAttribute(qtVisualContext, kQTVisualContextOutputColorSpaceKey, displayColorSpace);
}
[lock lock];
[self updateCIContext];
[lock unlock];
[self setNeedsDisplay:YES];
}
- (void)windowChangedScreen:(NSNotification*)inNotification
{
NSWindow *window = [inNotification object];
CGDirectDisplayID displayID = (CGDirectDisplayID)[[[[window screen] deviceDescription] objectForKey:@"NSScreenNumber"] intValue];
if ((displayID != NULL) && (viewDisplayID != displayID)) {
[self updateColorProfile:displayID];
if (NULL != displayLink) {
CVDisplayLinkSetCurrentCGDisplay(displayLink, displayID);
}
viewDisplayID = displayID;
}
}
//--------------------------------------------------------------------------------------------------
- (void)prepareOpenGL
{
CVReturn ret;
lock = [[NSRecursiveLock alloc] init];
// OpenGL setup
long swapInterval = 1;
// sync with screen refresh to avoid tearing
[[self openGLContext] setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
// Create CIFilters
colorCorrectionFilter = [[CIFilter filterWithName:@"CIColorControls"] retain]; // Color filter
[colorCorrectionFilter setDefaults]; // set the filter to its default values
effectFilter = [[CIFilter filterWithName:@"CIZoomBlur"] retain]; // Effect filter
[effectFilter setDefaults]; // set the filter to its default values
[effectFilter setValue:[NSNumber numberWithFloat:0.0] forKey:@"inputAmount"]; // set inputAmount to 0 our slider default
compositeFilter = [[CIFilter filterWithName:@"CISourceOverCompositing"] retain]; // Composite filter
// Create display link
CGOpenGLDisplayMask totalDisplayMask = 0;
int virtualScreen;
long displayMask, accelerated;
NSOpenGLPixelFormat *openGLPixelFormat = [self pixelFormat];
// build up list of displays from OpenGL's pixel format
for (virtualScreen = 0; virtualScreen < [openGLPixelFormat numberOfVirtualScreens]; virtualScreen++) {
[openGLPixelFormat getValues:&displayMask forAttribute:NSOpenGLPFAScreenMask forVirtualScreen:virtualScreen];
[openGLPixelFormat getValues:&accelerated forAttribute:NSOpenGLPFAAccelerated forVirtualScreen:virtualScreen];
if (accelerated) {
totalDisplayMask |= displayMask;
}
}
ret = CVDisplayLinkCreateWithOpenGLDisplayMask(totalDisplayMask, &displayLink);
// Set up display link callbacks
CVDisplayLinkSetOutputCallback(displayLink, renderCallback, self);
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowChangedScreen:) name:NSWindowDidMoveNotification object:[self window]];
}
//--------------------------------------------------------------------------------------------------
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[qtMovie release];
[colorCorrectionFilter release];
[effectFilter release];
[compositeFilter release];
[timeCodeOverlay release];
CVOpenGLTextureRelease(currentFrame);
if (qtVisualContext) QTVisualContextRelease(qtVisualContext);
[ciContext release];
[super dealloc];
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
- (void)update
{
[lock lock];
[super update];
[lock unlock];
}
//--------------------------------------------------------------------------------------------------
- (void)reshape // scrolled, moved or resized
{
NSRect frame = [self frame];
NSRect bounds = [self bounds];
GLfloat minX, minY, maxX, maxY;
minX = NSMinX(bounds);
minY = NSMinY(bounds);
maxX = NSMaxX(bounds);
maxY = NSMaxY(bounds);
[self update];
if(NSIsEmptyRect([self visibleRect])) {
glViewport(0, 0, 1, 1);
} else {
glViewport(0, 0, frame.size.width ,frame.size.height);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(minX, maxX, minY, maxY, -1.0, 1.0);
// if we are not playing, force an immediate draw otherwise it will update with the next frame
// coming through. This makes the resize performance better as it reduces the number of redraws
// espcially on the main thread
if(!CVDisplayLinkIsRunning(displayLink)){
[self display];
}
}
//--------------------------------------------------------------------------------------------------
- (void)drawRect:(NSRect)theRect
{
[lock lock];
[[self openGLContext] makeCurrentContext];
// clean the OpenGL context - not so important here but very important when you deal with transparency
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
// make sure we have a frame to render
if(!currentFrame) [self updateCurrentFrame];
// render the frame
[self renderCurrentFrame];
// flush our output to the screen - this will render with the next beamsync
glFlush();
[lock unlock];
}
//--------------------------------------------------------------------------------------------------
- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
{
return YES;
}
//--------------------------------------------------------------------------------------------------
- (void)mouseDown:(NSEvent *)theEvent
{
BOOL keepOn = YES;
NSPoint mouseLoc;
while (keepOn)
{
theEvent = [[self window] nextEventMatchingMask: NSLeftMouseUpMask | NSLeftMouseDraggedMask];
mouseLoc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
[self setFilterCenterFromMouseLocation:mouseLoc];
if ([theEvent type] == NSLeftMouseUp)
keepOn = NO;
};
return;
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
- (void)setQTMovie:(QTMovie*)inMovie
{
if (CVDisplayLinkIsRunning(displayLink)) [self togglePlay:nil];
[inMovie retain];
[qtMovie release];
[timeCodeOverlay release];
if (NULL != currentFrame) {
CVOpenGLTextureRelease(currentFrame);
currentFrame = NULL;
}
qtMovie = inMovie;
if (NULL == qtVisualContext) {
OSStatus error;
[[NSNotificationCenter defaultCenter] postNotificationName:NSWindowDidMoveNotification object:[self window]];
/* Create QT Visual context */
NSDictionary *targetDimensions = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:720.0], kQTVisualContextTargetDimensions_WidthKey,
[NSNumber numberWithFloat:480.0], kQTVisualContextTargetDimensions_HeightKey, nil];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: targetDimensions, kQTVisualContextTargetDimensionsKey,
displayColorSpace, kQTVisualContextOutputColorSpaceKey, nil];
error = QTOpenGLTextureContextCreate(kCFAllocatorDefault, (CGLContextObj)[[self openGLContext] CGLContextObj],
(CGLPixelFormatObj)[[self pixelFormat] CGLPixelFormatObj],
(CFDictionaryRef)attributes,
&qtVisualContext);
}
if (qtMovie) {
OSStatus error;
NSSize movieSize;
error = SetMovieVisualContext([qtMovie quickTimeMovie], qtVisualContext);
SetMoviePlayHints([qtMovie quickTimeMovie], hintsHighQuality, hintsHighQuality);
[[qtMovie attributeForKey: QTMovieCurrentSizeAttribute] getValue: &movieSize];
[qtMovie gotoBeginning];
MoviesTask([qtMovie quickTimeMovie], 0); // QTKit is not doing this automatically
movieDuration = [[[qtMovie movieAttributes] objectForKey:QTMovieDurationAttribute] QTTimeValue];
// Setup the timecode overlay
NSDictionary *fontAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:[NSFont labelFontOfSize:24.0f], NSFontAttributeName,
[NSColor colorWithCalibratedRed:1.0f green:0.2f blue:0.2f alpha:0.60f], NSForegroundColorAttributeName, nil];
timeCodeOverlay = [[TimeCodeOverlay alloc] initWithAttributes:fontAttributes targetSize:NSMakeSize(movieSize.width, movieSize.height / 4.0)]; // text overlay will go in the bottom quarter of the display
movieSize = [[qtMovie attributeForKey:QTMovieNaturalSizeAttribute] sizeValue];
NSRect windowFrame = [[self window] frame];
NSRect movieViewFrame = [self frame];
float deltaHeight = movieSize.height - movieViewFrame.size.height;
float deltaWidth = movieSize.width - movieViewFrame.size.width;
windowFrame.origin.y -= deltaHeight;
windowFrame.size.height += deltaHeight;
windowFrame.size.width += deltaWidth;
NSSize minimumSize = [[self window] minSize];
if (windowFrame.size.height > minimumSize.height && windowFrame.size.width > minimumSize.width) {
[[self window] setFrame:windowFrame display: YES animate: YES];
} else {
windowFrame.origin.y -= minimumSize.height - windowFrame.size.height;
windowFrame.size.height = minimumSize.height;
windowFrame.size.width = minimumSize.width;
[[self window] setFrame:windowFrame display: YES animate: YES];
}
[self setNeedsDisplay:YES];
}
}
//--------------------------------------------------------------------------------------------------
- (QTTime)currentTime
{
return [qtMovie currentTime];
}
//--------------------------------------------------------------------------------------------------
- (QTTime)movieDuration
{
return movieDuration;
}
//--------------------------------------------------------------------------------------------------
- (void)setTime:(QTTime)inTime
{
[qtMovie setCurrentTime:inTime];
if(CVDisplayLinkIsRunning(displayLink))
[self togglePlay:nil];
[self updateCurrentFrame];
[self display];
}
- (CGDirectDisplayID)viewDisplayID
{
return viewDisplayID;
}
//--------------------------------------------------------------------------------------------------
- (IBAction)setMovieTime:(id)sender
{
[self setTime:QTTimeFromString([sender stringValue])];
}
//--------------------------------------------------------------------------------------------------
- (IBAction)nextFrame:(id)sender
{
if(CVDisplayLinkIsRunning(displayLink))
[self togglePlay:nil];
[qtMovie stepForward];
[self updateCurrentFrame];
[self display];
}
//--------------------------------------------------------------------------------------------------
- (IBAction)prevFrame:(id)sender
{
if(CVDisplayLinkIsRunning(displayLink))
[self togglePlay:nil];
[qtMovie stepBackward];
[self updateCurrentFrame];
[self display];
}
//--------------------------------------------------------------------------------------------------
- (IBAction)scrub:(id)sender
{
if (CVDisplayLinkIsRunning(displayLink)) [self togglePlay:nil];
// Get movie time, duration
QTTime currentTime;
NSTimeInterval sliderTime = [sender floatValue];
//TimeValue tv;
currentTime.timeValue = movieDuration.timeValue * sliderTime;
currentTime.timeScale = movieDuration.timeScale;
currentTime.flags = 0;
[qtMovie setCurrentTime:currentTime];
MoviesTask([qtMovie quickTimeMovie], 0); // QTKit is not doing this automatically
[self updateCurrentFrame];
[self display];
}
//--------------------------------------------------------------------------------------------------
- (IBAction)togglePlay:(id)sender
{
if (CVDisplayLinkIsRunning(displayLink)) {
CVDisplayLinkStop(displayLink);
[qtMovie stop];
} else {
[qtMovie play];
CVDisplayLinkStart(displayLink);
}
}
//--------------------------------------------------------------------------------------------------
- (IBAction)setFilterParameter:(id)sender
{
[lock lock];
switch([sender tag])
{
case 0:
[colorCorrectionFilter setValue:[NSNumber numberWithFloat:[sender floatValue]] forKey:@"inputContrast"];
break;
case 1:
[colorCorrectionFilter setValue:[NSNumber numberWithFloat:[sender floatValue]] forKey:@"inputBrightness"];
break;
case 2:
[colorCorrectionFilter setValue:[NSNumber numberWithFloat:[sender floatValue]] forKey:@"inputSaturation"];
break;
case 3:
[effectFilter setValue:[NSNumber numberWithFloat:[sender floatValue]] forKey:@"inputAmount"];
break;
default:
break;
}
[lock unlock];
if(!CVDisplayLinkIsRunning(displayLink))
[self display];
}
//--------------------------------------------------------------------------------------------------
- (void)setFilterCenterFromMouseLocation:(NSPoint)where
{
CIVector *centerVector = nil;
[lock lock];
centerVector = [CIVector vectorWithX:where.x Y:where.y];
[effectFilter setValue:centerVector forKey:@"inputCenter"];
[lock unlock];
if(!CVDisplayLinkIsRunning(displayLink))
[self display];
}
//--------------------------------------------------------------------------------------------------
- (IBAction)saveFrameToFile:(id)sender
{
// this demonstrates exporting the current frame by using ImageIO to export a CGImage which is created from CoreImage
NSSavePanel *savePanel;
if(CVDisplayLinkIsRunning(displayLink))
[self togglePlay:nil];
savePanel = [NSSavePanel savePanel];
[savePanel setRequiredFileType:@"jpg"];
if([savePanel runModalForDirectory:nil file:@"MyVideoFrame"] == NSFileHandlingPanelOKButton)
{
// create an image destination (ImageIO's way of saying we want to save to a file format)
// note: public.jpeg denotes that we are saving to JPEG
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL((CFURLRef)[savePanel URL], (CFStringRef)@"public.jpeg", 1, nil);
if (imageDestination == NULL)
{
NSLog(@"problems creating image destination\n");
CFRelease(imageDestination);
return;
}
CGImageRef renderedImage = [ciContext createCGImage:[effectFilter valueForKey:@"outputImage"] fromRect:[[effectFilter valueForKey:@"outputImage"] extent]];
// add image to the ImageIO destination (specify the image we want to save)
CGImageDestinationAddImage(imageDestination, renderedImage, NULL);
// finalize: this saves the image to the JPEG format as data
if (!CGImageDestinationFinalize(imageDestination))
{
NSLog(@"problems writing JPEG file\n");
}
CFRelease(imageDestination);
CGImageRelease(renderedImage);
}
}
//--------------------------------------------------------------------------------------------------
-(void)reallyExportMovie:(NSSavePanel *)savePanel toPod:(BOOL)exportToPod
{
MovieExportComponent myExporter = NULL;
ComponentDescription myCompDesc;
Boolean myCancelled = false;
long trackID;
MovieExportGetPropertyUPP theAudioPropProcUPP = nil;
MovieExportGetDataUPP theAudioDataProcUPP = nil;
TimeScale audioScale = 0;
void *audioRefCon = 0;
OSErr err = noErr;
// Export into a Quicktime movie
myCompDesc.componentType = MovieExportType;
myCompDesc.componentSubType = MovieFileType;
myCompDesc.componentManufacturer = kAppleManufacturer;
myCompDesc.componentFlags = canMovieExportFromProcedures;
myCompDesc.componentFlagsMask = canMovieExportFromProcedures;
// open the selected movie export component
myExporter = OpenComponent(FindNextComponent(NULL, &myCompDesc));
if (myExporter == NULL) {
NSLog(@"could not find export compontent !");
return;
}
// Hey exporter, support modern audio features
Boolean useHighResolutionAudio = true;
QTSetComponentProperty(myExporter, kQTPropertyClass_MovieExporter,
kQTMovieExporterPropertyID_EnableHighResolutionAudioFeatures,
sizeof(Boolean),
&useHighResolutionAudio);
// create UPPs for the two app-defined export functions
MovieExportGetPropertyUPP theVideoPropProcUPP = NewMovieExportGetPropertyUPP(QTMoovProcs_VideoTrackPropertyProc);
MovieExportGetDataUPP theVideoDataProcUPP = NewMovieExportGetDataUPP(QTMoovProcs_VideoTrackDataProc);
MovieExportAddDataSource(myExporter, VideoMediaType,
movieDuration.timeScale, // use the original timescale
&trackID,
theVideoPropProcUPP,
theVideoDataProcUPP,
self);
// setup audio
NSArray *audioTracks = [qtMovie tracksOfMediaType:QTMediaTypeSound];
if ([audioTracks count] > 0) {
// we are setting up the audio for pass through
err = MovieExportNewGetDataAndPropertiesProcs(myExporter, SoundMediaType,
&audioScale,
[qtMovie quickTimeMovie],
[(QTTrack*)[audioTracks objectAtIndex:0] quickTimeTrack], // we only use the first audio here
0,
movieDuration.timeValue,
&theAudioPropProcUPP,
&theAudioDataProcUPP,
&audioRefCon);
if (err) {
NSLog(@"Can't get audio for export");
} else {
MovieExportAddDataSource(myExporter, SoundMediaType, audioScale, &trackID, theAudioPropProcUPP, theAudioDataProcUPP, audioRefCon);
}
}
if (NO == exportToPod) {
MovieExportDoUserDialog(myExporter, NULL, NULL, 0, movieDuration.timeValue, &myCancelled);
if (myCancelled) {
NSLog(@"User canceled export dialog");
DisposeMovieExportGetPropertyUPP(theVideoPropProcUPP);
DisposeMovieExportGetDataUPP(theVideoDataProcUPP);
if (theAudioPropProcUPP && theAudioDataProcUPP) {
MovieExportDisposeGetDataAndPropertiesProcs(myExporter, theAudioPropProcUPP, theAudioDataProcUPP, audioRefCon);
}
CloseComponent(myExporter);
return;
}
} else {
// Setup the Movie Export component with our preset export settings
QTAtomContainer settings;
PtrToHand(ExportSettings, (Handle *)&settings, sizeof(ExportSettings));
MovieExportSetSettingsFromAtomContainer(myExporter, settings);
QTDisposeAtomContainer(settings);
}
isExporting = YES;
cancelExport = NO;
OSType myDataType;
Handle myDataRef;
NSRect frame = [self frame];
// create the readback and flipping buffers - see note about flipping in exportFrame method
outputWidth = frame.size.width;
outputHeight = frame.size.height;
//outputWidth = 720;
//outputHeight = 480;
outputAlignment = 4;
contextRowBytes = outputWidth * outputAlignment;
contextPixels = calloc(contextRowBytes * outputHeight, sizeof(char));
flippedContextPixels = calloc(contextRowBytes * outputHeight, sizeof(char));
// setup the image description for the frame compression
outputImageDescription = (ImageDescriptionHandle)NewHandleClear(sizeof(ImageDescription));
(*outputImageDescription)->idSize = sizeof(ImageDescription);
#ifdef __BIG_ENDIAN__
(*outputImageDescription)->cType = k32ARGBPixelFormat;
#else
(*outputImageDescription)->cType = k32BGRAPixelFormat;
#endif
(*outputImageDescription)->vendor = kAppleManufacturer;
(*outputImageDescription)->spatialQuality = codecLosslessQuality;
(*outputImageDescription)->width = outputWidth;
(*outputImageDescription)->height = outputHeight;
(*outputImageDescription)->hRes = 72L<<16;
(*outputImageDescription)->vRes = 72L<<16;
(*outputImageDescription)->dataSize = contextRowBytes * outputHeight;
(*outputImageDescription)->frameCount = 1;
(*outputImageDescription)->depth = 32;
(*outputImageDescription)->clutID = -1;
// export the video data to the data reference
QTNewDataReferenceFromCFURL((CFURLRef)[savePanel URL], 0, &myDataRef, &myDataType );
MovieExportFromProceduresToDataRef(myExporter, myDataRef, myDataType);
// we are done with the .mov export so lets clean up
free(contextPixels);
contextPixels = nil;
free(flippedContextPixels);
flippedContextPixels = nil;
DisposeMovieExportGetPropertyUPP(theVideoPropProcUPP);
DisposeMovieExportGetDataUPP(theVideoDataProcUPP);
if (theAudioPropProcUPP && theAudioDataProcUPP) {
MovieExportDisposeGetDataAndPropertiesProcs(myExporter, theAudioPropProcUPP, theAudioDataProcUPP, audioRefCon);
}
if (outputImageDescription) DisposeHandle((Handle)outputImageDescription);
outputImageDescription = NULL;
CloseComponent(myExporter);
// do some extra work if we're exporting to iPod
if (!cancelExport && YES == exportToPod) {
Handle podExportDataRef;
OSType podExportDataRefType;
Movie theRecentlyExportedMovie;
short resID = movieInDataForkResID;
// open the movie we just exported
NewMovieFromDataRef(&theRecentlyExportedMovie, newMovieActive, &resID, myDataRef, myDataType);
// create a new data reference using the .m4v extention
CFMutableStringRef newFileName = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef)[savePanel filename]);
CFRange extension = CFStringFind(newFileName, CFSTR(".mov"), kCFCompareBackwards);
CFStringReplace(newFileName, extension, CFSTR(".m4v"));
QTNewDataReferenceFromFullPathCFString(newFileName, kQTNativeDefaultPathStyle, 0, &podExportDataRef, &podExportDataRefType);
// Delete any existing .m4v file with the same name
[[NSFileManager defaultManager] removeFileAtPath:(NSString *)newFileName handler:nil];
// find and open the iPod export component, if you wanted to export to ATV use the 'M4VH' fourCC
err = OpenADefaultComponent(MovieExportType, 'M4V ', &myExporter);
if (err == noErr && 0 != myExporter) {
// set the progress procedure for some basic UI
MovieExportSetProgressProc(myExporter, NewMovieProgressUPP(QTMoovProcs_PodExportProgress), (long)delegate);
// do the export
MovieExportToDataRef(myExporter, podExportDataRef, podExportDataRefType, theRecentlyExportedMovie, 0, 0, GetMovieDuration(theRecentlyExportedMovie));
// clean up
CloseComponent(myExporter);
DisposeHandle(podExportDataRef);
DisposeMovie(theRecentlyExportedMovie);
// delete the original .mov file which we don't need anymore
[[NSFileManager defaultManager] removeFileAtPath:[savePanel filename] handler:nil];
// open the .m4v in QuickTime Player -- just using openFile would result in iTunes starting up (not what I want to happen)
[[NSWorkspace sharedWorkspace] openFile:(NSString *)newFileName withApplication:@"QuickTime Player"];
}
} else if (!cancelExport) {
// open the movie in the QuickTime Player
[[NSWorkspace sharedWorkspace] openFile:[savePanel filename]];
}
// dispose the original data reference
DisposeHandle(myDataRef);
// got back to the beginning of the movie
QTTime currentTime = { 0, movieDuration.timeScale, 0 };
[qtMovie setCurrentTime: currentTime];
MoviesTask([qtMovie quickTimeMovie], 0); // QTKit is not doing this automatically
// render the frame
[self updateCurrentFrame];
[self display];
isExporting = NO;
}
- (IBAction)exportMovie:(id)sender
{
NSSavePanel *savePanel;
// stop the display link