UBQuickTimeFile.mm 14.8 KB
Newer Older
1
/*
2
 * Copyright (C) 2015-2018 Département de l'Instruction Publique (DIP-SEM)
Craig Watson's avatar
Craig Watson committed
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
 * Copyright (C) 2013 Open Education Foundation
 *
 * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour
 * l'Education Numérique en Afrique (GIP ENA)
 *
 * This file is part of OpenBoard.
 *
 * OpenBoard is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License,
 * with a specific linking exception for the OpenSSL project's
 * "OpenSSL" library (or with modified versions of it that use the
 * same license as the "OpenSSL" library).
 *
 * OpenBoard 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. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with OpenBoard. If not, see <http://www.gnu.org/licenses/>.
 */




#include "UBQuickTimeFile.h"

#include <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import <Foundation/Foundation.h>
#import <CoreMedia/CoreMedia.h>

#include "UBAudioQueueRecorder.h"
#include <QtGui>

#include "core/memcheck.h"

QWaitCondition UBQuickTimeFile::frameBufferNotEmpty;

UBQuickTimeFile::UBQuickTimeFile(QObject * pParent)
    : QThread(pParent)
    , mVideoWriter(0)
    , mVideoWriterInput(0)
    , mAdaptor(0)
49 50
    , mAudioWriterInput(0)
    , mWaveRecorder(0)
51
    , mTimeScale(1000)
52 53 54 55
    , mRecordAudio(true)
    , mShouldStopCompression(false)
    , mCompressionSessionRunning(false)
{
56 57
    mVideoDispatchQueue = dispatch_queue_create("org.oef.VideoDispatchQueue", NULL);
    mAudioDispatchQueue = dispatch_queue_create("org.oef.AudioDispatchQueue", NULL);
58 59 60 61 62 63 64 65 66 67
}


UBQuickTimeFile::~UBQuickTimeFile()
{
}

bool UBQuickTimeFile::init(const QString& pVideoFileName, const QString& pProfileData, int pFramesPerSecond
                , const QSize& pFrameSize, bool pRecordAudio, const QString& audioRecordingDevice)
{
68 69 70
    Q_UNUSED(pProfileData);
    Q_UNUSED(pFramesPerSecond);

71 72 73
    mFrameSize = pFrameSize;
    mVideoFileName = pVideoFileName;
    mRecordAudio = pRecordAudio;
74
    //mRecordAudio = false;
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

    if (mRecordAudio)
        mAudioRecordingDeviceName = audioRecordingDevice;
    else
        mAudioRecordingDeviceName = "";


    qDebug() << "UBQuickTimeFile created; video size: " << pFrameSize.width() << " x " << pFrameSize.height();

    return true;

}


void UBQuickTimeFile::run()
{
    mShouldStopCompression = false;

    if (!beginSession())
        return;

    mCompressionSessionRunning = true;
    emit compressionSessionStarted();

99 100 101 102
    [mVideoWriterInput requestMediaDataWhenReadyOnQueue:mVideoDispatchQueue
        usingBlock:^{
            frameQueueMutex.lock();
            //frameBufferNotEmpty.wait(&UBQuickTimeFile::frameQueueMutex); // TODO: monitor performance with and without this
103

104 105 106 107
            if (!mShouldStopCompression && 
                !frameQueue.isEmpty() &&
                [mVideoWriterInput isReadyForMoreMediaData]) 
            {
108
                // in this case the last few frames may be dropped if the queue isn't empty...
109
                    VideoFrame frame = frameQueue.dequeue();
110
                    appendFrameToVideo(frame.buffer, frame.timestamp);
111
            }
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126
            frameQueueMutex.unlock();
            
    }];
    
    if (mRecordAudio) {
        [mAudioWriterInput requestMediaDataWhenReadyOnQueue:mAudioDispatchQueue
            usingBlock:^{
                audioQueueMutex.lock();
                if (!audioQueue.isEmpty() && 
                    [mAudioWriterInput isReadyForMoreMediaData]) 
                {
                        appendSampleBuffer(audioQueue.dequeue());
                }
                audioQueueMutex.unlock();
127

128 129
            }];
    }
130 131 132 133

}

/**
134 135
  * \brief Begin the recording session; initialize the audio/video writer
  * \return true if the session was initialized successfully
136
  *
137 138
  * This function initializes the AVAssetWriter and associated video and audio inputs.
  * Video is encoded as H264; audio is encoded as AAC.
139 140 141 142 143 144 145 146 147 148 149
  */
bool UBQuickTimeFile::beginSession()
{
    NSError *outError;
    NSString * outputPath = [[NSString alloc] initWithUTF8String: mVideoFileName.toUtf8().data()];
    NSURL * outputUrl = [[NSURL alloc] initFileURLWithPath: outputPath];

    if (!outputUrl) {
        qDebug() << "Podcast video URL invalid; not recording";
        return false;
    }
150

151 152
    // Create and check the assetWriter
    mVideoWriter = [[AVAssetWriter assetWriterWithURL:outputUrl
153 154
                                   fileType:AVFileTypeQuickTimeMovie
                                   error:&outError] retain];
155 156 157
    NSCParameterAssert(mVideoWriter);

    mVideoWriter.movieTimeScale = mTimeScale;
158

159 160 161 162 163


    // Video
    //

164 165 166
    int frameWidth = mFrameSize.width();
    int frameHeight = mFrameSize.height();

167
    // Create the input and check it
168 169 170 171 172 173 174
    NSDictionary * videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                                AVVideoCodecH264, AVVideoCodecKey,
                                                [NSNumber numberWithInt:frameWidth], AVVideoWidthKey,
                                                [NSNumber numberWithInt:frameHeight], AVVideoHeightKey,
                                                nil];

    mVideoWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
175
                                            outputSettings:videoSettings] retain];
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    NSCParameterAssert(mVideoWriterInput);



    // Pixel Buffer Adaptor. This makes it possible to pass CVPixelBuffers to the WriterInput
    NSDictionary* pixelBufSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                         [NSNumber numberWithInt:kCVPixelFormatType_32BGRA], kCVPixelBufferPixelFormatTypeKey,
                                         [NSNumber numberWithInt: frameWidth], kCVPixelBufferWidthKey,
                                         [NSNumber numberWithInt: frameHeight], kCVPixelBufferHeightKey,
                                         nil];

    mAdaptor = [[AVAssetWriterInputPixelBufferAdaptor
                        assetWriterInputPixelBufferAdaptorWithAssetWriterInput:mVideoWriterInput
                        sourcePixelBufferAttributes:pixelBufSettings] retain];

    NSCParameterAssert([mVideoWriter canAddInput:mVideoWriterInput]);
    [mVideoWriter addInput:mVideoWriterInput];


195 196 197 198 199 200

    // Audio
    //

    if(mRecordAudio) {
        mWaveRecorder = new UBAudioQueueRecorder();
201

202 203 204 205 206 207 208
        // Get the audio format description from mWaveRecorder
        CMAudioFormatDescriptionCreate(kCFAllocatorDefault, mWaveRecorder->audioFormat(),
                                       0, NULL, 0, NULL, NULL,
                                       &mAudioFormatDescription);

        if(mWaveRecorder->init(mAudioRecordingDeviceName)) {
            connect(mWaveRecorder, &UBAudioQueueRecorder::newWaveBuffer,
209
                    this, &UBQuickTimeFile::enqueueAudioBuffer);
210 211 212 213 214 215 216 217 218 219 220

            connect(mWaveRecorder, SIGNAL(audioLevelChanged(quint8)),
                    this, SIGNAL(audioLevelChanged(quint8)));
        }
        else {
            setLastErrorMessage(mWaveRecorder->lastErrorMessage());
            mWaveRecorder->deleteLater();
            mRecordAudio = false;
        }

        // Audio is mono, and compressed to AAC at 128kbps
221

222 223 224 225 226 227
        AudioChannelLayout audioChannelLayout = {
            .mChannelLayoutTag = kAudioChannelLayoutTag_Mono,
            .mChannelBitmap = 0,
            .mNumberChannelDescriptions = 0
        };

228
        NSData *channelLayoutAsData = [NSData dataWithBytes:&audioChannelLayout
229
                                              length:offsetof(AudioChannelLayout, mChannelDescriptions)];
230

231 232 233 234
        NSDictionary * compressionAudioSettings = @{
            AVFormatIDKey         : [NSNumber numberWithUnsignedInt:kAudioFormatMPEG4AAC],
            AVEncoderBitRateKey   : [NSNumber numberWithInteger:128000],
            AVSampleRateKey       : [NSNumber numberWithInteger:44100],
235
            //AVChannelLayoutKey    : channelLayoutAsData,
236 237 238
            AVNumberOfChannelsKey : [NSNumber numberWithUnsignedInteger:1]
        };

239
        mAudioWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio
240
                                               outputSettings:compressionAudioSettings] retain];
241

242 243 244 245 246 247
        NSCParameterAssert([mVideoWriter canAddInput:mAudioWriterInput]);
        [mVideoWriter addInput:mAudioWriterInput];
    }


    // Begin the writing session
248 249 250
    bool canStartWriting = [mVideoWriter startWriting];
    [mVideoWriter startSessionAtSourceTime:CMTimeMake(0, mTimeScale)];

251
    mStartTime = CFAbsoluteTimeGetCurrent(); // used for audio timestamp calculation
252
    mLastFrameTimestamp = CMTimeMake(0, mTimeScale);
253

254 255 256 257 258 259 260 261
    return (mVideoWriter != nil) && (mVideoWriterInput != nil) && canStartWriting;
}

/**
 * \brief Close the recording sesion and finish writing the video file
 */
void UBQuickTimeFile::endSession()
{
262 263 264
    //qDebug() << "Ending session";


265
    [mVideoWriterInput markAsFinished];
266 267
    if (mAudioWriterInput != 0)
        [mAudioWriterInput markAsFinished];
268

269 270 271
    [mVideoWriter finishWritingWithCompletionHandler:^{
        [mAdaptor release];
        [mVideoWriterInput release];
272

273 274 275 276
        if (mAudioWriterInput != 0)
            [mAudioWriterInput release];
        
        [mVideoWriter release];
277

278 279 280 281 282 283 284 285 286 287 288 289 290
        mAdaptor = nil;
        mVideoWriterInput = nil;
        mVideoWriter = nil;
        mAudioWriterInput = nil;

        if (mWaveRecorder) {
            mWaveRecorder->close();
            mWaveRecorder->deleteLater();
        }


        emit compressionFinished();
    }];
291

292 293 294 295 296 297 298
}

/**
 * \brief Request the recording to stop
 */
void UBQuickTimeFile::stop()
{
299
    //qDebug() << "requested end of recording";
300
    mShouldStopCompression = true;
301 302 303 304 305 306 307


    frameQueueMutex.lock();
    audioQueueMutex.lock();
    endSession();
    frameQueueMutex.unlock();
    audioQueueMutex.unlock();
308 309 310 311
}


/**
312 313 314
 * \brief Create and return a CVPixelBufferRef 
 *
 * The CVPixelBuffer is created from the input adaptor's CVPixelBufferPool
315 316 317 318 319
 */
CVPixelBufferRef UBQuickTimeFile::newPixelBuffer()
{
    CVPixelBufferRef pixelBuffer = 0;

320 321 322 323
    CVReturn result = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, mAdaptor.pixelBufferPool, &pixelBuffer);

    if (result != kCVReturnSuccess) {
        setLastErrorMessage("Could not retrieve CV buffer from pool (error " + QString::number(result) + ")");
324 325 326 327 328 329
        return 0;
    }

    return pixelBuffer;
}

330 331 332 333 334 335
void UBQuickTimeFile::enqueueVideoFrame(VideoFrame frame)
{
    frameQueueMutex.lock();
    frameQueue.enqueue(frame);
    frameQueueMutex.unlock();
}
336 337 338

/**
 * \brief Add a frame to the pixel buffer adaptor
339 340
 * \param pixelBuffer The CVPixelBufferRef (video frame) to add to the movie
 * \param msTimeStamp Timestamp, in milliseconds, of the frame
341
 */
342
void UBQuickTimeFile::appendFrameToVideo(CVPixelBufferRef pixelBuffer, long msTimeStamp)
343
{
344
    //qDebug() << "appending video frame";
345
    CMTime t = CMTimeMake((msTimeStamp * mTimeScale / 1000.0), mTimeScale);
346

347 348
    // The timestamp must be both valid and larger than the previous frame's timestamp
    if (CMTIME_IS_VALID(t) && CMTimeCompare(t, mLastFrameTimestamp) == 1) {
349

350 351 352 353
        bool added = [mAdaptor appendPixelBuffer: pixelBuffer
                            withPresentationTime: t];
        if (!added)
            setLastErrorMessage(QString("Could not encode frame at time %1").arg(msTimeStamp));
354

355 356 357 358 359 360 361
        mLastFrameTimestamp = t;
    }

    else {
        qDebug() << "Frame dropped; timestamp was smaller or equal to previous frame's timestamp of: "
                 << mLastFrameTimestamp.value << "/" << mLastFrameTimestamp.timescale;
    }
362 363 364 365

    CVPixelBufferRelease(pixelBuffer);
}

366 367 368 369 370 371 372 373 374 375 376 377



/**
 * \brief Append an AudioQueue Buffer to the audio AVAssetWriterInput
 * \param pBuffer The AudioQueueBufferRef to add. Must be uncompressed (LPCM).
 * \param pLength The length of the buffer, in Bytes
 *
 * This function serves as an interface between the low-level audio stream
 * (implemented in the UBAudioQueueRecorder class) and the recording, handled
 * by the AVAssetWriterInput instance mAudioWriterInput.
 */
378
void UBQuickTimeFile::enqueueAudioBuffer(void* pBuffer,
379 380
                                        long pLength)
{
381 382
    
    if(!mRecordAudio || mShouldStopCompression)
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
        return;


    // CMSampleBuffers require a CMBlockBuffer to hold the media data; we
    // create a blockBuffer here from the AudioQueueBuffer's data.
    CMBlockBufferRef blockBuffer;
    CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault,
                                       pBuffer,
                                       pLength,
                                       kCFAllocatorNull,
                                       NULL,
                                       0,
                                       pLength,
                                       kCMBlockBufferAssureMemoryNowFlag,
                                       &blockBuffer);


    // Timestamp of current sample
    CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent();
    CFTimeInterval elapsedTime = currentTime - mStartTime;
    CMTime timeStamp = CMTimeMake(elapsedTime * mTimeScale, mTimeScale);

    // Number of samples in the buffer
    long nSamples = pLength / mWaveRecorder->audioFormat()->mBytesPerFrame;

    CMSampleBufferRef sampleBuffer;
    CMAudioSampleBufferCreateWithPacketDescriptions(kCFAllocatorDefault,
                                                    blockBuffer,
                                                    true,
                                                    NULL,
                                                    NULL,
414
                                                    mAudioFormatDescription,
415
                                                    nSamples,
416
                                                    timeStamp,
417 418 419
                                                    NULL,
                                                    &sampleBuffer);

420
    //qDebug() << "enqueueAudioBuffer, timeStamp = " << timeStamp.value << " / " << timeStamp.timescale;
421

422 423 424 425 426 427 428 429 430 431
    
    audioQueueMutex.lock();
    audioQueue.enqueue(sampleBuffer);
    audioQueueMutex.unlock();
    
    //qDebug() << "buffer enqueued";
    


}
432 433


434 435 436 437 438 439 440
bool UBQuickTimeFile::appendSampleBuffer(CMSampleBufferRef sampleBuffer)
{
    bool success = [mAudioWriterInput appendSampleBuffer:sampleBuffer];
    
    if (!success)
        setLastErrorMessage(QString("Failed to append sample buffer to audio input"));
    
441

442
    CMBlockBufferRef blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer);
443 444 445

    CFRelease(sampleBuffer);
    CFRelease(blockBuffer);
446

447
    return success;
448 449
}

450

451 452 453
/**
 * \brief Print an error message to the terminal, and store it
 */
454 455 456 457 458
void UBQuickTimeFile::setLastErrorMessage(const QString& error)
{
    mLastErrorMessage = error;
    qWarning() << "UBQuickTimeFile error" << error;
}