cap_qtkit.mm 33.2 KB
Newer Older
wester committed
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
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "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 contributor 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 advised of the possibility of such damage.
//
//M*////////////////////////////////////////////////////////////////////////////////////////


#include "precomp.hpp"
wester committed
44
#include "opencv2/imgproc/imgproc.hpp"
wester committed
45 46 47
#include <iostream>
#import <QTKit/QTKit.h>

wester committed
48 49
using namespace std;

wester committed
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
/********************** Declaration of class headers ************************/

/*****************************************************************************
 *
 * CaptureDelegate Declaration.
 *
 * 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
 *   been copied before. When "getOutput" is called from the main thread,
 *   it gives the last copied IplImage.
 *
 *****************************************************************************/

#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
{
    int newFrame;
    CVImageBufferRef  mCurrentImageBuffer;
    char* imagedata;
    IplImage* image;
    char* bgr_imagedata;
    IplImage* bgr_image;
    size_t currSize;
}

- (void)captureOutput:(QTCaptureOutput *)captureOutput
  didOutputVideoFrame:(CVImageBufferRef)videoFrame
     withSampleBuffer:(QTSampleBuffer *)sampleBuffer
       fromConnection:(QTCaptureConnection *)connection;

- (void)captureOutput:(QTCaptureOutput *)captureOutput
didDropVideoFrameWithSampleBuffer:(QTSampleBuffer *)sampleBuffer
       fromConnection:(QTCaptureConnection *)connection;

- (int)updateImage;
- (IplImage*)getOutput;

wester committed
98 99
- (void)doFireTimer:(NSTimer *)timer;

wester committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
@end

/*****************************************************************************
 *
 * CvCaptureCAM Declaration.
 *
 * CvCaptureCAM is the instantiation of a capture source for cameras.
 *
 *****************************************************************************/

class CvCaptureCAM : public CvCapture {
public:
    CvCaptureCAM(int cameraNum = -1) ;
    ~CvCaptureCAM();
    virtual bool grabFrame();
    virtual IplImage* retrieveFrame(int);
wester committed
116
    virtual double getProperty(int property_id);
wester committed
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
    virtual bool setProperty(int property_id, double value);
    virtual int didStart();


private:
    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;

};


/*****************************************************************************
 *
 * CvCaptureFile Declaration.
 *
 * CvCaptureFile is the instantiation of a capture source for video files.
 *
 *****************************************************************************/

class CvCaptureFile : public CvCapture {
public:
    CvCaptureFile(const char* filename) ;
    ~CvCaptureFile();
    virtual bool grabFrame();
    virtual IplImage* retrieveFrame(int);
wester committed
158
    virtual double getProperty(int property_id);
wester committed
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
    virtual bool setProperty(int property_id, double value);
    virtual int didStart();


private:
    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;
    QTTime endOfMovie;
};


/*****************************************************************************
 *
 * CvCaptureFile Declaration.
 *
 * CvCaptureFile is the instantiation of a capture source for video files.
 *
 *****************************************************************************/

class CvVideoWriter_QT : public CvVideoWriter{
public:
    CvVideoWriter_QT(const char* filename, int fourcc,
                   double fps, CvSize frame_size,
                   int is_color=1);
    ~CvVideoWriter_QT();
    bool writeFrame(const IplImage* image);
private:
    IplImage* argbimage;
    QTMovie* mMovie;
wester committed
206
    unsigned char* imagedata;
wester committed
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

    NSString* path;
    NSString* codec;
    double movieFPS;
    CvSize movieSize;
    int movieColor;
};


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


CvCapture* cvCreateFileCapture_QT(const char* filename) {
    CvCaptureFile *retval = new CvCaptureFile(filename);

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

CvCapture* cvCreateCameraCapture_QT(int index ) {
    CvCapture* retval = new CvCaptureCAM(index);
    if (!((CvCaptureCAM *)retval)->didStart())
        cvReleaseCapture(&retval);
    return retval;
}

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);
}

/********************** Implementation of Classes ****************************/

/*****************************************************************************
 *
 * CvCaptureCAM Implementation.
 *
 * CvCaptureCAM is the instantiation of a capture source for cameras.
 *
 *****************************************************************************/

CvCaptureCAM::CvCaptureCAM(int cameraNum) {
    mCaptureSession = nil;
    mCaptureDeviceInput = nil;
    mCaptureDecompressedVideoOutput = nil;
    capture = nil;

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

    camNum = cameraNum;

    if (!startCaptureDevice(camNum)) {
wester committed
266
        cout << "Warning, camera failed to properly initialize!" << endl;
wester committed
267 268 269 270 271 272 273 274 275
        started = 0;
    } else {
        started = 1;
    }

}

CvCaptureCAM::~CvCaptureCAM() {
    stopCaptureDevice();
a  
Kai Westerkamp committed
276

wester committed
277
    cout << "Cleaned up camera." << endl;
wester committed
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
}

int CvCaptureCAM::didStart() {
    return started;
}


bool CvCaptureCAM::grabFrame() {
    return grabFrame(5);
}

bool CvCaptureCAM::grabFrame(double timeOut) {

    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    double sleepTime = 0.005;
    double total = 0;

    // If the capture is launched in a separate thread, then
    // [NSRunLoop currentRunLoop] is not the same as in the main thread, and has no timer.
    //see https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsrunloop_Class/Reference/Reference.html
    // "If no input sources or timers are attached to the run loop, this
    // method exits immediately"
    // using usleep() is not a good alternative, because it may block the GUI.
    // Create a dummy timer so that runUntilDate does not exit immediately:
    [NSTimer scheduledTimerWithTimeInterval:100 target:capture selector:@selector(doFireTimer:) userInfo:nil repeats:YES];
    while (![capture updateImage] && (total += sleepTime)<=timeOut) {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:sleepTime]];
    }

    [localpool drain];

    return total <= timeOut;
}

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

void CvCaptureCAM::stopCaptureDevice() {
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    [mCaptureSession stopRunning];

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

    [mCaptureSession release];
    [mCaptureDeviceInput release];

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

}

int CvCaptureCAM::startCaptureDevice(int cameraNum) {
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    capture = [[CaptureDelegate alloc] init];

    QTCaptureDevice *device;
    NSArray* devices = [[[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeVideo]
            arrayByAddingObjectsFromArray:[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeMuxed]] retain];

    if ([devices count] == 0) {
wester committed
344
        cout << "QTKit didn't find any attached Video Input Devices!" << endl;
wester committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
        [localpool drain];
        return 0;
    }

    if (cameraNum >= 0) {
        NSUInteger nCameras = [devices count];
        if( (NSUInteger)cameraNum >= nCameras ) {
            [localpool drain];
            return 0;
        }
        device = [devices objectAtIndex:cameraNum] ;
    } else {
        device = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeVideo]  ;
    }
    int success;
    NSError* error;

    if (device) {

        success = [device open:&error];
        if (!success) {
wester committed
366
            cout << "QTKit failed to open a Video Capture Device" << endl;
wester committed
367 368 369 370 371 372 373 374 375 376
            [localpool drain];
            return 0;
        }

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

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

        if (!success) {
wester committed
377
            cout << "QTKit failed to start capture session with opened Capture Device" << endl;
wester committed
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
            [localpool drain];
            return 0;
        }


        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];
        }
        [mCaptureDecompressedVideoOutput setPixelBufferAttributes:pixelBufferOptions];

#if QTKIT_VERSION_MAX_ALLOWED >= QTKIT_VERSION_7_6_3
        [mCaptureDecompressedVideoOutput setAutomaticallyDropsLateVideoFrames:YES];
#endif


        success = [mCaptureSession addOutput:mCaptureDecompressedVideoOutput error:&error];
        if (!success) {
wester committed
409
            cout << "QTKit failed to add Output to Capture Session" << endl;
wester committed
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
            [localpool drain];
            return 0;
        }

        [mCaptureSession startRunning];

        grabFrame(60);

        [localpool drain];
        return 1;
    }

    [localpool drain];
    return 0;
}

void CvCaptureCAM::setWidthHeight() {
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

    [mCaptureSession stopRunning];

    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];

    [mCaptureSession startRunning];

    grabFrame(60);
    [localpool drain];
}


wester committed
447
double CvCaptureCAM::getProperty(int property_id){
wester committed
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
    int retval;
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];

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

    switch (property_id) {
        case CV_CAP_PROP_FRAME_WIDTH:
            retval = s1.width;
            break;
        case CV_CAP_PROP_FRAME_HEIGHT:
            retval = s1.height;
            break;
        default:
            retval = 0;
            break;
    }

    [localpool drain];
    return retval;
}

bool CvCaptureCAM::setProperty(int property_id, double value) {
    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;
    }
}


/*****************************************************************************
 *
 * CaptureDelegate Implementation.
 *
 * 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
 *   been copied before. When "getOutput" is called from the main thread,
 *   it gives the last copied IplImage.
 *
 *****************************************************************************/


@implementation CaptureDelegate

- (id)init {
    self = [super init];
    if (self) {
        newFrame = 0;
        imagedata = NULL;
        bgr_imagedata = NULL;
        currSize = 0;
        image = NULL;
        bgr_image = NULL;
    }
    return self;
}


-(void)dealloc {
    if (imagedata != NULL) free(imagedata);
    if (bgr_imagedata != NULL) free(bgr_imagedata);
    cvReleaseImage(&image);
    cvReleaseImage(&bgr_image);
    [super dealloc];
}

- (void)captureOutput:(QTCaptureOutput *)captureOutput
  didOutputVideoFrame:(CVImageBufferRef)videoFrame
     withSampleBuffer:(QTSampleBuffer *)sampleBuffer
       fromConnection:(QTCaptureConnection *)connection {
    (void)captureOutput;
    (void)sampleBuffer;
    (void)connection;

    CVBufferRetain(videoFrame);
    CVImageBufferRef imageBufferToRelease  = mCurrentImageBuffer;

    @synchronized (self) {

        mCurrentImageBuffer = videoFrame;
        newFrame = 1;
    }

    CVBufferRelease(imageBufferToRelease);

}
- (void)captureOutput:(QTCaptureOutput *)captureOutput
didDropVideoFrameWithSampleBuffer:(QTSampleBuffer *)sampleBuffer
       fromConnection:(QTCaptureConnection *)connection {
    (void)captureOutput;
    (void)sampleBuffer;
    (void)connection;
wester committed
563
    cout << "Camera dropped frame!" << endl;
wester committed
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
}

-(IplImage*) getOutput {
    return bgr_image;
}

-(int) updateImage {
    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((int)width,(int)height), IPL_DEPTH_8U, 4);
        }
        image->width = (int)width;
        image->height = (int)height;
        image->nChannels = 4;
        image->depth = IPL_DEPTH_8U;
        image->widthStep = (int)rowBytes;
        image->imageData = imagedata;
        image->imageSize = (int)currSize;

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

        cvCvtColor(image, bgr_image, CV_BGRA2BGR);

    }

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

    return 1;
}

wester committed
630 631 632 633 634
- (void)doFireTimer:(NSTimer *)timer {
    (void)timer;
    // dummy
}

wester committed
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
@end


/*****************************************************************************
 *
 * CvCaptureFile Implementation.
 *
 * CvCaptureFile is the instantiation of a capture source for video files.
 *
 *****************************************************************************/

CvCaptureFile::CvCaptureFile(const char* filename) {

    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) {
wester committed
677
        cout << "WARNING: Couldn't read movie file " << filename << endl;
wester committed
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
        [localpool drain];
        started = 0;
        return;
    }

    [mCaptureSession gotoEnd];
    endOfMovie = [mCaptureSession currentTime];

    [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];

}

CvCaptureFile::~CvCaptureFile() {
    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];
}

int CvCaptureFile::didStart() {
    return started;
}

bool CvCaptureFile::grabFrame() {
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];
    double t1 = getProperty(CV_CAP_PROP_POS_MSEC);

    QTTime curTime;
    curTime = [mCaptureSession currentTime];
    bool isEnd=(QTTimeCompare(curTime,endOfMovie) == NSOrderedSame);

    [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 !isEnd;
}


IplImage* CvCaptureFile::retrieveFramePixelBuffer() {
    NSAutoreleasePool* localpool = [[NSAutoreleasePool alloc] init];


    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                QTMovieFrameImageTypeCVPixelBufferRef, QTMovieFrameImageType,
#ifdef MAC_OS_X_VERSION_10_6
                                [NSNumber numberWithBool:YES], QTMovieFrameImageSessionMode,
#endif
                                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((int)width,(int)height), IPL_DEPTH_8U, 4);
        }

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


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

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

        cvCvtColor(image, bgr_image,CV_BGRA2BGR);

    }

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

    [localpool drain];

    return bgr_image;
}


IplImage* CvCaptureFile::retrieveFrame(int) {
    return retrieveFramePixelBuffer();
}

double CvCaptureFile::getFPS() {
    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;
}

wester committed
845
double CvCaptureFile::getProperty(int property_id){
wester committed
846 847 848 849 850 851 852
    if (mCaptureSession == nil) return 0;

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

    double retval;
    QTTime t;

wester committed
853
    //cerr << "get_prop"<<endl;
wester committed
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
    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;
}

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

    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;
}


/*****************************************************************************
 *
 * CvVideoWriter Implementation.
 *
 * CvVideoWriter is the instantiation of a video output class
 *
 *****************************************************************************/


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) {
wester committed
976 977
        cout << "WARNING: Didn't properly encode FourCC. Expected " << fourcc
        << " but got " << cc2 << "." << endl;
wester committed
978 979 980 981 982 983 984 985 986 987
    }

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

    NSError *error = nil;
    if (!mMovie) {

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

        mMovie = [[QTMovie alloc] initToWritableFile:path error:&error];
        if (!mMovie) {
wester committed
994
            cout << "WARNING: Could not create empty movie file container." << endl;
wester committed
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
            [localpool drain];
            return;
        }
    }

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

    [localpool drain];
}


CvVideoWriter_QT::~CvVideoWriter_QT() {
    cvReleaseImage(&argbimage);

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

bool CvVideoWriter_QT::writeFrame(const IplImage* image) {
    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]) {
wester committed
1069
        cout << "Didn't successfully update movie file." << endl;
wester committed
1070 1071 1072 1073 1074 1075 1076 1077
    }

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

    return 1;
}