File: CVFileInputController.mm

package info (click to toggle)
freej 0.10git20100110-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 32,080 kB
  • ctags: 22,705
  • sloc: cpp: 156,254; ansic: 25,531; sh: 13,538; perl: 4,624; makefile: 3,278; python: 2,889; objc: 1,284; asm: 1,125; ruby: 126
file content (337 lines) | stat: -rw-r--r-- 9,731 bytes parent folder | download
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
/*  FreeJ
 *  (c) Copyright 2009 Andrea Guzzo <xant@dyne.org>
 *
 * This source code is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Public License as published 
 * by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * This source code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * Please refer to the GNU Public License for more details.
 *
 * You should have received a copy of the GNU Public License along with
 * this source code; if not, write to:
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#import <CVFileInputController.h>
#import <CIAlphaFade.h>
#include <math.h>

/* Utility to set a SInt32 value in a CFDictionary
*/
static OSStatus SetNumberValue(CFMutableDictionaryRef inDict,
                        CFStringRef inKey,
                        SInt32 inValue)
{
    CFNumberRef number;

    number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &inValue);
    if (NULL == number) return coreFoundationUnknownErr;

    CFDictionarySetValue(inDict, inKey, number);

    CFRelease(number);

    return noErr;
}

@implementation CVFileInputController : CVLayerController

- (id)init
{
    isPlaying = NO;
        qtVisualContext = nil;
    return [super init];
}

- (void)dealloc
{
    if (qtMovie)
        [qtMovie release];
    if(qtVisualContext)
        QTVisualContextRelease(qtVisualContext);
    [super dealloc];
}

- (void)setupPixelBuffer
{
    OSStatus err;
    
    Context *ctx = [freej getContext];

    /* Create QT Visual context */
    
    // Pixel Buffer attributes
    CFMutableDictionaryRef pixelBufferOptions = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
                                                                          &kCFTypeDictionaryKeyCallBacks,
                                                                          &kCFTypeDictionaryValueCallBacks);
    
    // the pixel format we want (freej require BGRA pixel format)
    SetNumberValue(pixelBufferOptions, kCVPixelBufferPixelFormatTypeKey, k32ARGBPixelFormat);
    
    // size
    SetNumberValue(pixelBufferOptions, kCVPixelBufferWidthKey, ctx->screen->geo.w);
    SetNumberValue(pixelBufferOptions, kCVPixelBufferHeightKey, ctx->screen->geo.h);
    
    // alignment
    SetNumberValue(pixelBufferOptions, kCVPixelBufferBytesPerRowAlignmentKey, 1);
    // QT Visual Context attributes
    CFMutableDictionaryRef visualContextOptions = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
                                                                            &kCFTypeDictionaryKeyCallBacks,
                                                                            &kCFTypeDictionaryValueCallBacks);
    // set the pixel buffer attributes for the visual context
    CFDictionarySetValue(visualContextOptions,
                         kQTVisualContextPixelBufferAttributesKey,
                         pixelBufferOptions);
    CFRelease(pixelBufferOptions);
        err = QTOpenGLTextureContextCreate(kCFAllocatorDefault, glContext,
                    CGLGetPixelFormat(glContext), visualContextOptions, &qtVisualContext);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CFRelease(visualContextOptions);
    CGColorSpaceRelease(colorSpace);    
}

- (void)unloadMovie
{
    [lock lock];

    QTVisualContextTask(qtVisualContext);
    [qtMovie stop];
    [qtMovie release];
    qtMovie = NULL;

    [layerView clear];
    /* TODO - try a way to safely reset currentFrame and lastFrame 
     * (note that other threads can be trying to access them) 
     
    if (lastFrame)
        [lastFrame release];
    lastFrame = NULL;
    if (currentFrame)
        CVPixelBufferRelease(currentFrame);
    
     */

    [lock unlock];
}

- (BOOL)setQTMovie:(QTMovie*)inMovie
{    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    //Context *ctx = (Context *)[freej getContext];

    // no movie has been supplied... perhaps we are going to exit
    if (!inMovie)
        return NO;
    
    // if we own already a movie let's relase it before trying to open the new one
    if (qtMovie)
        [self unloadMovie];

    [lock lock];

    qtMovie = inMovie;

    if(qtMovie) { // ok the movie is here ... let's start the underlying QTMovie object
        OSStatus error;

        [self setupPixelBuffer];

        [qtMovie retain]; // we are going to need this for a while

        error = SetMovieVisualContext([qtMovie quickTimeMovie], qtVisualContext);
        [qtMovie gotoBeginning];
        //[qtMovie setMuted:YES]; // still no audio?
        
        NSArray *tracks = [qtMovie tracks];
        bool hasVideo = NO;
        for (NSUInteger i = 0; i < [tracks count]; i ++) {
            QTTrack *track = [tracks objectAtIndex:i];
            NSString *type = [track attributeForKey:QTTrackMediaTypeAttribute];
            if (![type isEqualToString:QTMediaTypeVideo]) {
                [track setEnabled:NO];
                DisposeMovieTrack([track quickTimeTrack]);
            } else {
                hasVideo = YES;
            }
        }
        if (!hasVideo) {
            qtMovie = nil;
            [lock unlock];
            return NO;
        }
        
        [qtMovie setAttribute:[NSNumber numberWithBool:YES] forKey:QTMovieLoopsAttribute];
        [self togglePlay]; // start playing the movie
        movieDuration = [[[qtMovie movieAttributes] objectForKey:QTMovieDurationAttribute] QTTimeValue];
    
        QTTime posterTime = [qtMovie duration];
        posterTime.timeValue /= 2;
        NSImage *poster = [qtMovie frameImageAtTime:posterTime];

        if (layerView)
            [layerView setPosterImage:poster];
        //[lock unlock];
       
        // register the layer within the freej context
        if (!layer) {
            layer = new CVLayer(self);
            layer->init();
        }
        NSArray* videoTracks = [qtMovie tracksOfMediaType:QTMediaTypeVideo];
        QTTrack* firstVideoTrack = [videoTracks objectAtIndex:0];
        QTMedia* media = [firstVideoTrack media];
        QTTime qtTimeDuration = [[media attributeForKey:QTMediaDurationAttribute] QTTimeValue];
        long sampleCount = [[media attributeForKey:QTMediaSampleCountAttribute] longValue];
        long timeScale = [[media attributeForKey:QTMediaTimeScaleAttribute] longValue];
        NSLog(@"timeScale: %lld timeValue: %lld", qtTimeDuration.timeScale, qtTimeDuration.timeValue);
        NSLog(@"duration: %@ sampleCount: %lld timeScale: %lld", QTStringFromTime(qtTimeDuration) , sampleCount, timeScale);
        NSLog(@"frames: %d\n", (qtTimeDuration.timeValue/timeScale)/sampleCount);
       // layer->fps.set([rate floatValue]);
    }

    [lock unlock];
    [pool release];
    return 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];
*/
}

- (IBAction)setMovieTime:(id)sender
{
    [self setTime:QTTimeFromString([sender stringValue])];
}

- (BOOL)togglePlay
{
    [lock lock];
    isPlaying = isPlaying?NO:YES;
    [lock unlock];
    return isPlaying;
}

- (CVTexture *)getTexture
{
    CVTexture *ret;
    bool gotNewFrame = newFrame;
    ret = [super getTexture];
    if (gotNewFrame) // task the qtvisualcontext if we got a new frame
        [(CVFileInputController *)self task];
    return ret;
}

- (BOOL)getFrameForTime:(const CVTimeStamp *)timeStamp
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    CVOpenGLBufferRef newPixelBuffer;
    BOOL rv = NO;
    // we can care ourselves about thread safety when accessing the QTKit api
    [QTMovie enterQTKitOnThread];

    [lock lock];

    if (!qtMovie)
        return NO;
    uint64_t ts = CVGetCurrentHostTime();
    QTTime now = [qtMovie currentTime];
   
    now.timeValue +=(((lastPTS?ts-lastPTS:0) * 600)/1000000000);
    now.timeScale = 600;

    QTTime duration = [qtMovie duration];
    if (QTTimeCompare(now, duration) == NSOrderedAscending)
        [qtMovie setCurrentTime:now];
    else 
        [qtMovie gotoBeginning];
    if(qtVisualContext)
    {        
        QTVisualContextCopyImageForTime(qtVisualContext,
        NULL,
        NULL,
        &newPixelBuffer);
      
        // rendering (aka: applying filters) is now done in getTexture()
        // implemented in CVLayerView (our parent)
        
        rv = YES;
        if (currentFrame) 
            CVOpenGLTextureRelease(currentFrame);
        currentFrame = newPixelBuffer;
        newFrame = YES;
        MoviesTask([qtMovie quickTimeMovie], 0);
    } 
    
    [lock unlock];
    [QTMovie exitQTKitOnThread];   
    lastPTS = ts;
    [pool release];
    return rv;
}


- (CVReturn)renderFrame
{
    NSAutoreleasePool *pool = nil;
    
    CVReturn rv = kCVReturnError;

    pool =[[NSAutoreleasePool alloc] init];

    if(qtMovie && [self getFrameForTime:nil])
    {
       
        // render preview if necessary
        [self renderPreview];
        rv = kCVReturnSuccess;
    } else {
        rv = kCVReturnError;
    }
    if (layer) 
        layer->vbuffer = currentFrame;
    [pool release];
    return rv;
}

- (void)task
{
    QTVisualContextTask(qtVisualContext);
}

- (bool)stepBackward
{
    [qtMovie stepBackward];
    return true;
}

- (bool)setpForward
{
    [qtMovie stepForward];
    return true;
}

//@synthesize qtMovie;

@end