cap_qtkit.mm 31.3 KB
Newer Older
1 2 3 4 5 6
/*
 *  CvCapture.mm
 *
 *  Created by Nicholas Butko on 11/3/09.
 *  Copyright 2009. All rights reserved.
 *
7
 * Redistribution and use in source and binary forms, with or without
8 9
 * modification, are permitted provided that the following conditions are met:
 *
10 11 12 13 14 15
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
16
 *    derived from this software without specific prior written permission.
17 18 19 20 21 22 23 24 25 26
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
27 28 29 30 31 32 33 34 35
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "precomp.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#import <QTKit/QTKit.h>

36
using namespace std;
37 38 39 40 41

/********************** Declaration of class headers ************************/

/*****************************************************************************
 *
42
 * CaptureDelegate Declaration.
43 44 45 46
 *
 * CaptureDelegate is notified on a separate thread by the OS whenever there
 *   is a new frame. When "updateImage" is called from the main thread, it
 *   copies this new frame into an IplImage, but only if this frame has not
47 48
 *   been copied before. When "getOutput" is called from the main thread,
 *   it gives the last copied IplImage.
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
 *
 *****************************************************************************/

#ifndef QTKIT_VERSION_7_6_3
#define QTKIT_VERSION_7_6_3         70603
#define QTKIT_VERSION_7_0           70000
#endif

#ifndef QTKIT_VERSION_MAX_ALLOWED
#define QTKIT_VERSION_MAX_ALLOWED QTKIT_VERSION_7_0
#endif

#define DISABLE_AUTO_RESTART 999

@interface CaptureDelegate : NSObject
{
65
    int newFrame;
66
    CVImageBufferRef  mCurrentImageBuffer;
67 68 69 70 71
    char* imagedata;
    IplImage* image;
    char* bgr_imagedata;
    IplImage* bgr_image;
    size_t currSize;
72 73
}

74 75 76 77
- (void)captureOutput:(QTCaptureOutput *)captureOutput
  didOutputVideoFrame:(CVImageBufferRef)videoFrame
     withSampleBuffer:(QTSampleBuffer *)sampleBuffer
       fromConnection:(QTCaptureConnection *)connection;
78

79 80 81
- (void)captureOutput:(QTCaptureOutput *)captureOutput
didDropVideoFrameWithSampleBuffer:(QTSampleBuffer *)sampleBuffer
       fromConnection:(QTCaptureConnection *)connection;
82

83 84
- (int)updateImage;
- (IplImage*)getOutput;
85 86 87 88 89

@end

/*****************************************************************************
 *
90
 * CvCaptureCAM Declaration.
91 92 93 94 95 96 97
 *
 * CvCaptureCAM is the instantiation of a capture source for cameras.
 *
 *****************************************************************************/

class CvCaptureCAM : public CvCapture {
public:
98 99 100 101 102 103 104 105 106
    CvCaptureCAM(int cameraNum = -1) ;
    ~CvCaptureCAM();
    virtual bool grabFrame();
    virtual IplImage* retrieveFrame(int);
    virtual double getProperty(int property_id);
    virtual bool setProperty(int property_id, double value);
    virtual int didStart();


107
private:
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    QTCaptureSession            *mCaptureSession;
    QTCaptureDeviceInput        *mCaptureDeviceInput;
    QTCaptureDecompressedVideoOutput    *mCaptureDecompressedVideoOutput;
    CaptureDelegate* capture;

    int startCaptureDevice(int cameraNum);
    void stopCaptureDevice();

    void setWidthHeight();
    bool grabFrame(double timeOut);

    int camNum;
    int width;
    int height;
    int settingWidth;
    int settingHeight;
    int started;
    int disableAutoRestart;

};
128 129 130 131


/*****************************************************************************
 *
132
 * CvCaptureFile Declaration.
133 134 135 136 137 138 139
 *
 * CvCaptureFile is the instantiation of a capture source for video files.
 *
 *****************************************************************************/

class CvCaptureFile : public CvCapture {
public:
140 141 142 143 144 145 146 147 148
    CvCaptureFile(const char* filename) ;
    ~CvCaptureFile();
    virtual bool grabFrame();
    virtual IplImage* retrieveFrame(int);
    virtual double getProperty(int property_id);
    virtual bool setProperty(int property_id, double value);
    virtual int didStart();


149
private:
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    QTMovie *mCaptureSession;

    char* imagedata;
    IplImage* image;
    char* bgr_imagedata;
    IplImage* bgr_image;
    size_t currSize;

    //IplImage* retrieveFrameBitmap();
    IplImage* retrieveFramePixelBuffer();
    double getFPS();

    int movieWidth;
    int movieHeight;
    double movieFPS;
    double currentFPS;
    double movieDuration;
    int changedPos;

    int started;
};
171 172 173 174


/*****************************************************************************
 *
175
 * CvCaptureFile Declaration.
176 177 178 179 180 181 182
 *
 * CvCaptureFile is the instantiation of a capture source for video files.
 *
 *****************************************************************************/

class CvVideoWriter_QT : public CvVideoWriter{
public:
183 184 185 186 187
    CvVideoWriter_QT(const char* filename, int fourcc,
                   double fps, CvSize frame_size,
                   int is_color=1);
    ~CvVideoWriter_QT();
    bool writeFrame(const IplImage* image);
188
private:
189 190 191 192 193 194 195 196 197
    IplImage* argbimage;
    QTMovie* mMovie;
    unsigned char* imagedata;

    NSString* path;
    NSString* codec;
    double movieFPS;
    CvSize movieSize;
    int movieColor;
198 199 200 201 202 203 204
};


/****************** Implementation of interface functions ********************/


CvCapture* cvCreateFileCapture_QT(const char* filename) {
205 206 207 208 209 210
    CvCaptureFile *retval = new CvCaptureFile(filename);

    if(retval->didStart())
        return retval;
    delete retval;
    return NULL;
211 212 213
}

CvCapture* cvCreateCameraCapture_QT(int index ) {
214 215 216 217
    CvCapture* retval = new CvCaptureCAM(index);
    if (!((CvCaptureCAM *)retval)->didStart())
        cvReleaseCapture(&retval);
    return retval;
218 219
}

220 221 222 223
CvVideoWriter* cvCreateVideoWriter_QT(const char* filename, int fourcc,
                                     double fps, CvSize frame_size,
                                     int is_color) {
    return new CvVideoWriter_QT(filename, fourcc, fps, frame_size,is_color);
224 225
}

226
/********************** Implementation of Classes ****************************/
227 228 229

/*****************************************************************************
 *
230
 * CvCaptureCAM Implementation.
231 232 233 234 235 236
 *
 * CvCaptureCAM is the instantiation of a capture source for cameras.
 *
 *****************************************************************************/

CvCaptureCAM::CvCaptureCAM(int cameraNum) {
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    mCaptureSession = nil;
    mCaptureDeviceInput = nil;
    mCaptureDecompressedVideoOutput = nil;
    capture = nil;

    width = 0;
    height = 0;
    settingWidth = 0;
    settingHeight = 0;
    disableAutoRestart = 0;

    camNum = cameraNum;

    if (!startCaptureDevice(camNum)) {
        cout << "Warning, camera failed to properly initialize!" << endl;
        started = 0;
    } else {
        started = 1;
    }

257 258 259
}

CvCaptureCAM::~CvCaptureCAM() {
260 261 262
    stopCaptureDevice();

    cout << "Cleaned up camera." << endl;
263 264 265
}

int CvCaptureCAM::didStart() {
266
    return started;
267 268 269 270
}


bool CvCaptureCAM::grabFrame() {
271
    return grabFrame(5);
272 273 274 275
}

bool CvCaptureCAM::grabFrame(double timeOut) {

276 277 278 279 280 281 282 283 284
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    double sleepTime = 0.005;
    double total = 0;

    NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:sleepTime];
    while (![capture updateImage] && (total += sleepTime)<=timeOut &&
           [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
                                    beforeDate:loopUntil])
        loopUntil = [NSDate dateWithTimeIntervalSinceNow:sleepTime];
285

286
    [localpool drain];
287

288
    return total <= timeOut;
289 290 291
}

IplImage* CvCaptureCAM::retrieveFrame(int) {
292
    return [capture getOutput];
293 294 295
}

void CvCaptureCAM::stopCaptureDevice() {
296 297 298 299 300
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    [mCaptureSession stopRunning];

    QTCaptureDevice *device = [mCaptureDeviceInput device];
301
    if ([device isOpen])  [device close];
302 303

    [mCaptureSession release];
304
    [mCaptureDeviceInput release];
305 306 307 308 309 310

    [mCaptureDecompressedVideoOutput setDelegate:mCaptureDecompressedVideoOutput];
    [mCaptureDecompressedVideoOutput release];
    [capture release];
    [localpool drain];

311 312 313
}

int CvCaptureCAM::startCaptureDevice(int cameraNum) {
314 315 316 317 318
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    capture = [[CaptureDelegate alloc] init];

    QTCaptureDevice *device;
319
    NSArray* devices = [[[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeVideo]
320 321 322 323 324 325 326 327 328 329
            arrayByAddingObjectsFromArray:[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeMuxed]] retain];

    if ([devices count] == 0) {
        cout << "QTKit didn't find any attached Video Input Devices!" << endl;
        [localpool drain];
        return 0;
    }

    if (cameraNum >= 0) {
        int nCameras = [devices count];
330 331
        if( cameraNum < 0 || cameraNum >= nCameras )
            return 0;
332 333 334 335 336 337 338
        device = [devices objectAtIndex:cameraNum] ;
    } else {
        device = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeVideo]  ;
    }
    int success;
    NSError* error;

339
    if (device) {
340 341 342 343 344 345 346 347 348 349 350 351 352

        success = [device open:&error];
        if (!success) {
            cout << "QTKit failed to open a Video Capture Device" << endl;
            [localpool drain];
            return 0;
        }

        mCaptureDeviceInput = [[QTCaptureDeviceInput alloc] initWithDevice:device] ;
        mCaptureSession = [[QTCaptureSession alloc] init] ;

        success = [mCaptureSession addInput:mCaptureDeviceInput error:&error];

353
        if (!success) {
354 355 356
            cout << "QTKit failed to start capture session with opened Capture Device" << endl;
            [localpool drain];
            return 0;
357
        }
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375


        mCaptureDecompressedVideoOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
        [mCaptureDecompressedVideoOutput setDelegate:capture];
        NSDictionary *pixelBufferOptions ;
        if (width > 0 && height > 0) {
            pixelBufferOptions = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithDouble:1.0*width], (id)kCVPixelBufferWidthKey,
                                  [NSNumber numberWithDouble:1.0*height], (id)kCVPixelBufferHeightKey,
                                  //[NSNumber numberWithUnsignedInt:k32BGRAPixelFormat], (id)kCVPixelBufferPixelFormatTypeKey,
                                  [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA],
                                  (id)kCVPixelBufferPixelFormatTypeKey,
                                  nil];
        } else {
            pixelBufferOptions = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA],
                                  (id)kCVPixelBufferPixelFormatTypeKey,
                                  nil];
376
        }
377 378
        [mCaptureDecompressedVideoOutput setPixelBufferAttributes:pixelBufferOptions];

379
#if QTKIT_VERSION_MAX_ALLOWED >= QTKIT_VERSION_7_6_3
380
        [mCaptureDecompressedVideoOutput setAutomaticallyDropsLateVideoFrames:YES];
381
#endif
382 383


384 385
        success = [mCaptureSession addOutput:mCaptureDecompressedVideoOutput error:&error];
        if (!success) {
386 387
            cout << "QTKit failed to add Output to Capture Session" << endl;
            [localpool drain];
388 389
            return 0;
        }
390 391 392 393 394 395 396 397 398 399

        [mCaptureSession startRunning];

        grabFrame(60);

        return 1;
    }

    [localpool drain];
    return 0;
400 401
}

402 403 404 405 406 407 408 409 410 411 412 413
void CvCaptureCAM::setWidthHeight() {
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    NSDictionary* pixelBufferOptions = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithDouble:1.0*width], (id)kCVPixelBufferWidthKey,
                          [NSNumber numberWithDouble:1.0*height], (id)kCVPixelBufferHeightKey,
                          [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA],
                          (id)kCVPixelBufferPixelFormatTypeKey,
                          nil];

    [mCaptureDecompressedVideoOutput setPixelBufferAttributes:pixelBufferOptions];
    grabFrame(60);
    [localpool drain];
414 415 416 417
}


double CvCaptureCAM::getProperty(int property_id){
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    NSArray* connections = [mCaptureDeviceInput	connections];
    QTFormatDescription* format = [[connections objectAtIndex:0] formatDescription];
    NSSize s1 = [[format attributeForKey:QTFormatDescriptionVideoCleanApertureDisplaySizeAttribute] sizeValue];

    int width=s1.width, height=s1.height;
    switch (property_id) {
        case CV_CAP_PROP_FRAME_WIDTH:
            return width;
        case CV_CAP_PROP_FRAME_HEIGHT:
            return height;
        default:
            return 0;
    }

    [localpool drain];

436 437 438
}

bool CvCaptureCAM::setProperty(int property_id, double value) {
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
    switch (property_id) {
        case CV_CAP_PROP_FRAME_WIDTH:
            width = value;
            settingWidth = 1;
            if (settingWidth && settingHeight) {
                setWidthHeight();
                settingWidth =0;
                settingHeight = 0;
            }
            return true;
        case CV_CAP_PROP_FRAME_HEIGHT:
            height = value;
            settingHeight = 1;
            if (settingWidth && settingHeight) {
                setWidthHeight();
                settingWidth =0;
                settingHeight = 0;
            }
            return true;
        case DISABLE_AUTO_RESTART:
            disableAutoRestart = value;
            return 1;
        default:
            return false;
    }
464 465 466 467 468
}


/*****************************************************************************
 *
469
 * CaptureDelegate Implementation.
470 471 472 473
 *
 * CaptureDelegate is notified on a separate thread by the OS whenever there
 *   is a new frame. When "updateImage" is called from the main thread, it
 *   copies this new frame into an IplImage, but only if this frame has not
474 475
 *   been copied before. When "getOutput" is called from the main thread,
 *   it gives the last copied IplImage.
476 477 478 479
 *
 *****************************************************************************/


480
@implementation CaptureDelegate
481 482

- (id)init {
483 484 485 486 487 488 489 490
    [super init];
    newFrame = 0;
    imagedata = NULL;
    bgr_imagedata = NULL;
    currSize = 0;
    image = NULL;
    bgr_image = NULL;
    return self;
491 492 493 494
}


-(void)dealloc {
495 496 497 498 499
    if (imagedata != NULL) free(imagedata);
    if (bgr_imagedata != NULL) free(bgr_imagedata);
    cvReleaseImage(&image);
    cvReleaseImage(&bgr_image);
    [super dealloc];
500 501
}

502 503 504 505
- (void)captureOutput:(QTCaptureOutput *)captureOutput
  didOutputVideoFrame:(CVImageBufferRef)videoFrame
     withSampleBuffer:(QTSampleBuffer *)sampleBuffer
       fromConnection:(QTCaptureConnection *)connection {
Andrey Kamaev's avatar
Andrey Kamaev committed
506 507 508
    (void)captureOutput;
    (void)sampleBuffer;
    (void)connection;
509

510
    CVBufferRetain(videoFrame);
511 512
    CVImageBufferRef imageBufferToRelease  = mCurrentImageBuffer;

513
    @synchronized (self) {
514

515
        mCurrentImageBuffer = videoFrame;
516
        newFrame = 1;
517
    }
518 519 520

    CVBufferRelease(imageBufferToRelease);

521
}
522 523 524
- (void)captureOutput:(QTCaptureOutput *)captureOutput
didDropVideoFrameWithSampleBuffer:(QTSampleBuffer *)sampleBuffer
       fromConnection:(QTCaptureConnection *)connection {
Andrey Kamaev's avatar
Andrey Kamaev committed
525 526 527
    (void)captureOutput;
    (void)sampleBuffer;
    (void)connection;
528
    cout << "Camera dropped frame!" << endl;
529 530 531
}

-(IplImage*) getOutput {
532
    return bgr_image;
533 534 535
}

-(int) updateImage {
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
    if (newFrame==0) return 0;
    CVPixelBufferRef pixels;

    @synchronized (self){
        pixels = CVBufferRetain(mCurrentImageBuffer);
        newFrame = 0;
    }

    CVPixelBufferLockBaseAddress(pixels, 0);
    uint32_t* baseaddress = (uint32_t*)CVPixelBufferGetBaseAddress(pixels);

    size_t width = CVPixelBufferGetWidth(pixels);
    size_t height = CVPixelBufferGetHeight(pixels);
    size_t rowBytes = CVPixelBufferGetBytesPerRow(pixels);

    if (rowBytes != 0) {

        if (currSize != rowBytes*height*sizeof(char)) {
            currSize = rowBytes*height*sizeof(char);
            if (imagedata != NULL) free(imagedata);
            if (bgr_imagedata != NULL) free(bgr_imagedata);
            imagedata = (char*)malloc(currSize);
            bgr_imagedata = (char*)malloc(currSize);
        }

        memcpy(imagedata, baseaddress, currSize);

        if (image == NULL) {
            image = cvCreateImageHeader(cvSize(width,height), IPL_DEPTH_8U, 4);
        }
        image->width =width;
        image->height = height;
        image->nChannels = 4;
        image->depth = IPL_DEPTH_8U;
        image->widthStep = rowBytes;
        image->imageData = imagedata;
        image->imageSize = currSize;

        if (bgr_image == NULL) {
            bgr_image = cvCreateImageHeader(cvSize(width,height), IPL_DEPTH_8U, 3);
        }
        bgr_image->width =width;
        bgr_image->height = height;
        bgr_image->nChannels = 3;
        bgr_image->depth = IPL_DEPTH_8U;
        bgr_image->widthStep = rowBytes;
        bgr_image->imageData = bgr_imagedata;
        bgr_image->imageSize = currSize;

        cvCvtColor(image, bgr_image, CV_BGRA2BGR);

    }

    CVPixelBufferUnlockBaseAddress(pixels, 0);
    CVBufferRelease(pixels);

    return 1;
593 594 595 596 597 598 599
}

@end


/*****************************************************************************
 *
600
 * CvCaptureFile Implementation.
601 602 603 604 605 606
 *
 * CvCaptureFile is the instantiation of a capture source for video files.
 *
 *****************************************************************************/

CvCaptureFile::CvCaptureFile(const char* filename) {
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

    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];


    mCaptureSession = nil;
    image = NULL;
    bgr_image = NULL;
    imagedata = NULL;
    bgr_imagedata = NULL;
    currSize = 0;

    movieWidth = 0;
    movieHeight = 0;
    movieFPS = 0;
    currentFPS = 0;
    movieDuration = 0;
    changedPos = 0;

    started = 0;

    NSError* error;


    mCaptureSession = [[QTMovie movieWithFile:[NSString stringWithCString:filename
                                                                 encoding:NSASCIIStringEncoding]
                                        error:&error] retain];
    [mCaptureSession setAttribute:[NSNumber numberWithBool:YES]
                           forKey:QTMovieLoopsAttribute];

    if (mCaptureSession == nil) {
        cout << "WARNING: Couldn't read movie file " << filename << endl;
        [localpool drain];
        started = 0;
        return;
    }


    [mCaptureSession gotoBeginning];

    NSSize size = [[mCaptureSession attributeForKey:QTMovieNaturalSizeAttribute] sizeValue];

    movieWidth = size.width;
    movieHeight = size.height;
    movieFPS = getFPS();
    currentFPS = movieFPS;

    QTTime t;

    [[mCaptureSession attributeForKey:QTMovieDurationAttribute] getValue:&t];
    movieDuration = (t.timeValue *1000.0 / t.timeScale);
    started = 1;
    [localpool drain];

660 661 662
}

CvCaptureFile::~CvCaptureFile() {
663 664 665 666 667 668 669
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    if (imagedata != NULL) free(imagedata);
    if (bgr_imagedata != NULL) free(bgr_imagedata);
    cvReleaseImage(&image);
    cvReleaseImage(&bgr_image);
    [mCaptureSession release];
    [localpool drain];
670 671 672
}

int CvCaptureFile::didStart() {
673
    return started;
674 675 676
}

bool CvCaptureFile::grabFrame() {
677 678 679 680 681 682 683 684 685 686 687 688
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    double t1 = getProperty(CV_CAP_PROP_POS_MSEC);
    [mCaptureSession stepForward];
    double t2 = getProperty(CV_CAP_PROP_POS_MSEC);
    if (t2>t1 && !changedPos) {
        currentFPS = 1000.0/(t2-t1);
    } else {
        currentFPS = movieFPS;
    }
    changedPos = 0;
    [localpool drain];
    return 1;
689 690 691 692
}


IplImage* CvCaptureFile::retrieveFramePixelBuffer() {
693 694 695 696 697
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];


    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                QTMovieFrameImageTypeCVPixelBufferRef, QTMovieFrameImageType,
698
#ifdef MAC_OS_X_VERSION_10_6
699
                                [NSNumber numberWithBool:YES], QTMovieFrameImageSessionMode,
700
#endif
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
                                nil];
    CVPixelBufferRef frame = (CVPixelBufferRef)[mCaptureSession frameImageAtTime:[mCaptureSession currentTime]
                                                                  withAttributes:attributes
                                                                           error:nil];

    CVPixelBufferRef pixels = CVBufferRetain(frame);
    CVPixelBufferLockBaseAddress(pixels, 0);

    uint32_t* baseaddress = (uint32_t*)CVPixelBufferGetBaseAddress(pixels);
    size_t width = CVPixelBufferGetWidth(pixels);
    size_t height = CVPixelBufferGetHeight(pixels);
    size_t rowBytes = CVPixelBufferGetBytesPerRow(pixels);

    if (rowBytes != 0) {

        if (currSize != rowBytes*height*sizeof(char)) {
            currSize = rowBytes*height*sizeof(char);
            if (imagedata != NULL) free(imagedata);
            if (bgr_imagedata != NULL) free(bgr_imagedata);
            imagedata = (char*)malloc(currSize);
            bgr_imagedata = (char*)malloc(currSize);
        }

        memcpy(imagedata, baseaddress, currSize);

        //ARGB -> BGRA
        for (unsigned int i = 0; i < currSize; i+=4) {
            char temp = imagedata[i];
            imagedata[i] = imagedata[i+3];
            imagedata[i+3] = temp;
            temp = imagedata[i+1];
            imagedata[i+1] = imagedata[i+2];
            imagedata[i+2] = temp;
        }

        if (image == NULL) {
            image = cvCreateImageHeader(cvSize(width,height), IPL_DEPTH_8U, 4);
        }

        image->width =width;
        image->height = height;
        image->nChannels = 4;
        image->depth = IPL_DEPTH_8U;
        image->widthStep = rowBytes;
        image->imageData = imagedata;
        image->imageSize = currSize;


        if (bgr_image == NULL) {
            bgr_image = cvCreateImageHeader(cvSize(width,height), IPL_DEPTH_8U, 3);
        }

        bgr_image->width =width;
        bgr_image->height = height;
        bgr_image->nChannels = 3;
        bgr_image->depth = IPL_DEPTH_8U;
        bgr_image->widthStep = rowBytes;
        bgr_image->imageData = bgr_imagedata;
        bgr_image->imageSize = currSize;

        cvCvtColor(image, bgr_image,CV_BGRA2BGR);

    }

    CVPixelBufferUnlockBaseAddress(pixels, 0);
    CVBufferRelease(pixels);

    [localpool drain];

    return bgr_image;
771 772 773 774
}


IplImage* CvCaptureFile::retrieveFrame(int) {
775
    return retrieveFramePixelBuffer();
776 777 778
}

double CvCaptureFile::getFPS() {
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
    if (mCaptureSession == nil) return 0;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    double now = getProperty(CV_CAP_PROP_POS_MSEC);
    double retval = 0;
    if (now == 0) {
        [mCaptureSession stepForward];
        double t2 =  getProperty(CV_CAP_PROP_POS_MSEC);
        [mCaptureSession stepBackward];
        retval = 1000.0 / (t2-now);
    } else {
        [mCaptureSession stepBackward];
        double t2 = getProperty(CV_CAP_PROP_POS_MSEC);
        [mCaptureSession stepForward];
        retval = 1000.0 / (now-t2);
    }
    [localpool drain];
    return retval;
796 797 798
}

double CvCaptureFile::getProperty(int property_id){
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
    if (mCaptureSession == nil) return 0;

    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    double retval;
    QTTime t;

    //cerr << "get_prop"<<endl;
    switch (property_id) {
        case CV_CAP_PROP_POS_MSEC:
            [[mCaptureSession attributeForKey:QTMovieCurrentTimeAttribute] getValue:&t];
            retval = t.timeValue * 1000.0 / t.timeScale;
            break;
        case CV_CAP_PROP_POS_FRAMES:
            retval = movieFPS * getProperty(CV_CAP_PROP_POS_MSEC) / 1000;
            break;
        case CV_CAP_PROP_POS_AVI_RATIO:
            retval = (getProperty(CV_CAP_PROP_POS_MSEC)) / (movieDuration );
            break;
        case CV_CAP_PROP_FRAME_WIDTH:
            retval = movieWidth;
            break;
        case CV_CAP_PROP_FRAME_HEIGHT:
            retval = movieHeight;
            break;
        case CV_CAP_PROP_FPS:
            retval = currentFPS;
            break;
        case CV_CAP_PROP_FRAME_COUNT:
            retval = movieDuration*movieFPS/1000;
            break;
        case CV_CAP_PROP_FOURCC:
        default:
            retval = 0;
    }

    [localpool drain];
    return retval;
837 838 839 840
}

bool CvCaptureFile::setProperty(int property_id, double value) {

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
    if (mCaptureSession == nil) return false;

    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    bool retval = false;
    QTTime t;

    double ms;

    switch (property_id) {
        case CV_CAP_PROP_POS_MSEC:
            [[mCaptureSession attributeForKey:QTMovieCurrentTimeAttribute] getValue:&t];
            t.timeValue = value * t.timeScale / 1000;
            [mCaptureSession setCurrentTime:t];
            changedPos = 1;
            retval = true;
            break;
        case CV_CAP_PROP_POS_FRAMES:
            ms = (value*1000.0 -5)/ currentFPS;
            retval = setProperty(CV_CAP_PROP_POS_MSEC, ms);
            break;
        case CV_CAP_PROP_POS_AVI_RATIO:
            ms = value * movieDuration;
            retval = setProperty(CV_CAP_PROP_POS_MSEC, ms);
            break;
        case CV_CAP_PROP_FRAME_WIDTH:
            //retval = movieWidth;
            break;
        case CV_CAP_PROP_FRAME_HEIGHT:
            //retval = movieHeight;
            break;
        case CV_CAP_PROP_FPS:
            //etval = currentFPS;
            break;
        case CV_CAP_PROP_FRAME_COUNT:
            {
            NSArray *videoTracks = [mCaptureSession tracksOfMediaType:QTMediaTypeVideo];
            if ([videoTracks count] > 0) {
                QTMedia *media = [[videoTracks objectAtIndex:0] media];
                retval = [[media attributeForKey:QTMediaSampleCountAttribute] longValue];
            } else {
                retval = 0;
            }
            }
            break;
        case CV_CAP_PROP_FOURCC:
        default:
            retval = false;
    }

    [localpool drain];
    return retval;
893 894 895 896 897
}


/*****************************************************************************
 *
898
 * CvVideoWriter Implementation.
899 900 901 902 903 904
 *
 * CvVideoWriter is the instantiation of a video output class
 *
 *****************************************************************************/


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
CvVideoWriter_QT::CvVideoWriter_QT(const char* filename, int fourcc,
                               double fps, CvSize frame_size,
                               int is_color) {


    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    movieFPS = fps;
    movieSize = frame_size;
    movieColor = is_color;
    mMovie = nil;
    path = [[[NSString stringWithCString:filename encoding:NSASCIIStringEncoding] stringByExpandingTildeInPath] retain];

    argbimage = cvCreateImage(movieSize, IPL_DEPTH_8U, 4);


    char cc[5];
    cc[0] = fourcc & 255;
    cc[1] = (fourcc >> 8) & 255;
    cc[2] = (fourcc >> 16) & 255;
    cc[3] = (fourcc >> 24) & 255;
    cc[4] = 0;
    int cc2 = CV_FOURCC(cc[0], cc[1], cc[2], cc[3]);
    if (cc2!=fourcc) {
        cout << "WARNING: Didn't properly encode FourCC. Expected " << fourcc
        << " but got " << cc2 << "." << endl;
    }

    codec = [[NSString stringWithCString:cc encoding:NSASCIIStringEncoding] retain];

    NSError *error = nil;
936
    if (!mMovie) {
937 938 939 940 941 942 943 944

        NSFileManager* files = [NSFileManager defaultManager];
        if ([files fileExistsAtPath:path]) {
            if (![files removeItemAtPath:path error:nil]) {
                cout << "WARNING: Failed to remove existing file " << [path cStringUsingEncoding:NSASCIIStringEncoding] << endl;
            }
        }

945 946
        mMovie = [[QTMovie alloc] initToWritableFile:path error:&error];
        if (!mMovie) {
947 948
            cout << "WARNING: Could not create empty movie file container." << endl;
            [localpool drain];
949 950 951
            return;
        }
    }
952 953 954 955

    [mMovie setAttribute:[NSNumber numberWithBool:YES] forKey:QTMovieEditableAttribute];

    [localpool drain];
956 957 958 959
}


CvVideoWriter_QT::~CvVideoWriter_QT() {
960 961 962 963 964 965 966
    cvReleaseImage(&argbimage);

    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    [mMovie release];
    [path release];
    [codec release];
    [localpool drain];
967 968 969
}

bool CvVideoWriter_QT::writeFrame(const IplImage* image) {
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
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    cvCvtColor(image, argbimage, CV_BGR2BGRA);


    unsigned char* imagedata = (unsigned char*)argbimage->imageData;
    //BGRA --> ARGB

    for (int j = 0; j < argbimage->height; j++) {
        int rowstart = argbimage->widthStep * j;
        for (int i = rowstart; i < rowstart+argbimage->widthStep; i+=4) {
            unsigned char temp = imagedata[i];
            imagedata[i] = 255;
            imagedata[i+3] = temp;
            temp = imagedata[i+2];
            imagedata[i+2] = imagedata[i+1];
            imagedata[i+1] = temp;
        }
    }

    NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&imagedata
                                                                         pixelsWide:movieSize.width
                                                                         pixelsHigh:movieSize.height
                                                                      bitsPerSample:8
                                                                    samplesPerPixel:4
                                                                           hasAlpha:YES
                                                                           isPlanar:NO
                                                                     colorSpaceName:NSDeviceRGBColorSpace
                                                                       bitmapFormat:NSAlphaFirstBitmapFormat
                                                                        bytesPerRow:argbimage->widthStep
                                                                       bitsPerPixel:32]  ;


    NSImage* nsimage = [[NSImage alloc] init];

    [nsimage addRepresentation:imageRep];

    /*
     codecLosslessQuality          = 0x00000400,
     codecMaxQuality               = 0x000003FF,
     codecMinQuality               = 0x00000000,
     codecLowQuality               = 0x00000100,
     codecNormalQuality            = 0x00000200,
     codecHighQuality              = 0x00000300
     */

    [mMovie addImage:nsimage forDuration:QTMakeTime(100,100*movieFPS) withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                                      codec, QTAddImageCodecType,
                                                                                      //[NSNumber numberWithInt:codecLowQuality], QTAddImageCodecQuality,
                                                                                      [NSNumber numberWithInt:100*movieFPS], QTTrackTimeScaleAttribute,nil]];

    if (![mMovie updateMovieFile]) {
        cout << "Didn't successfully update movie file." << endl;
    }

    [imageRep release];
    [nsimage release];
    [localpool drain];

    return 1;
1030 1031
}