This repository has been archived by the owner on Jul 30, 2022. It is now read-only.
mirrored from https://chromium.googlesource.com/webm/webmquicktime
-
Notifications
You must be signed in to change notification settings - Fork 10
/
WebMVideoStream.c
532 lines (430 loc) · 19.9 KB
/
WebMVideoStream.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include <QuickTime/QuickTime.h>
#include "WebMExportStructs.h"
#include "WebMVideoStream.h"
OSStatus EnableMultiPassWithTemporaryFile(ICMCompressionSessionOptionsRef inCompressionSessionOptions,
ICMMultiPassStorageRef *outMultiPassStorage)
{
FSRef tempDirRef;
ICMMultiPassStorageRef multiPassStorage = NULL;
OSStatus status;
*outMultiPassStorage = NULL;
// users temp directory
status = FSFindFolder(kUserDomain, kTemporaryFolderType,
kCreateFolder, &tempDirRef);
if (noErr != status) goto bail;
// create storage using a temporary file with a unique file name
status = ICMMultiPassStorageCreateWithTemporaryFile(kCFAllocatorDefault,
&tempDirRef,
NULL, 0,
&multiPassStorage);
if (noErr != status) goto bail;
// enable multi-pass by setting the compression session options
// note - the compression session options object retains the multi-pass
// storage object
status = ICMCompressionSessionOptionsSetProperty(inCompressionSessionOptions,
kQTPropertyClass_ICMCompressionSessionOptions,
kICMCompressionSessionOptionsPropertyID_MultiPassStorage,
sizeof(ICMMultiPassStorageRef),
&multiPassStorage);
bail:
if (noErr != status) {
// this api is NULL safe so we can just call it
ICMMultiPassStorageRelease(multiPassStorage);
} else {
*outMultiPassStorage = multiPassStorage;
}
return status;
}
//callback function of the decompression session
static void _frameDecompressedCallback(void *refCon, OSStatus inerr,
ICMDecompressionTrackingFlags decompressionFlags,
CVPixelBufferRef pixelBuffer, TimeValue64 displayTime,
TimeValue64 displayDuration,
ICMValidTimeFlags validTimeFlags, void *reserved,
void *sourceFrameRefCon)
{
OSStatus err;
dbg_printf("[webM] >> _frameDecompressedCallback(err=%d)\n", inerr);
if (!inerr)
{
GenericStreamPtr vs = (GenericStreamPtr) refCon;
if ((decompressionFlags & kICMDecompressionTracking_EmittingFrame) && pixelBuffer)
{
ICMCompressionFrameOptionsRef frameOptions = NULL;
OSType pf = CVPixelBufferGetPixelFormatType(pixelBuffer);
dbg_printf("[webM] _frame_decompressed() = %ld; dFlags %ld,"
" dispTime %lld, dispDur %lld, timeFlags %ld [%ld '%4.4s' (%ld x %ld)]\n",
inerr, decompressionFlags, displayTime, displayDuration, validTimeFlags,
CVPixelBufferGetDataSize(pixelBuffer), (char *) &pf,
CVPixelBufferGetWidth(pixelBuffer),
CVPixelBufferGetHeight(pixelBuffer));
// Feed the frame to the compression session.
dbg_printf("feeding the frame to the compression session\n");
err = ICMCompressionSessionEncodeFrame(vs->vid.compressionSession, pixelBuffer,
displayTime, displayDuration,
validTimeFlags, frameOptions,
NULL, NULL);
if (err !=0)
{
const char* errString = GetMacOSStatusErrorString(err);
dbg_printf("[WebM] ICMCompressionSessionEncodeFrame err = %s\n", errString);
}
}
if (decompressionFlags & kICMDecompressionTracking_ReleaseSourceData)
{
// if we were responsible for managing source data buffers,
// we should release the source buffer here,
// using sourceFramemovieGet.refCon to identify it.
}
}
dbg_printf("[webM] exit _frameDecompressedCallback err= %ld\n", err);
}
static void addint32toDictionary(CFMutableDictionaryRef dictionary, CFStringRef key, SInt32 i)
{
CFNumberRef number = CFNumberCreate(NULL, kCFNumberSInt32Type, &i);
if (!number) return;
CFDictionaryAddValue(dictionary, key, number);
CFRelease(number);
}
static void addShortToDictionary(CFMutableDictionaryRef dictionary, CFStringRef key, short i)
{
CFNumberRef number = CFNumberCreate(NULL, kCFNumberShortType, &i);
if (!number) return;
CFDictionaryAddValue(dictionary, key, number);
CFRelease(number);
}
ComponentResult openDecompressionSession(GenericStreamPtr vs)
{
ImageDescriptionHandle idh = (ImageDescriptionHandle)(vs->source.params.desc);
ComponentResult err = noErr;
CFMutableDictionaryRef pixelBufferAttributes = NULL;
ICMDecompressionTrackingCallbackRecord trackingCallBackRecord;
OSType pixelFormat = k422YpCbCr8PixelFormat;
ImageDescription *id = *idh;
//create a dictionary describingg the pixel buffer we want to get back
pixelBufferAttributes = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
addShortToDictionary(pixelBufferAttributes, kCVPixelBufferWidthKey, id->width);
addShortToDictionary(pixelBufferAttributes, kCVPixelBufferHeightKey, id->height);
addint32toDictionary(pixelBufferAttributes, kCVPixelBufferHeightKey, pixelFormat);
//call back function for the decompression session
trackingCallBackRecord.decompressionTrackingCallback = _frameDecompressedCallback;
trackingCallBackRecord.decompressionTrackingRefCon = (void *) vs; //reference to pass to the callback function
err = ICMDecompressionSessionCreate(NULL, idh, /* sessionOptions */ NULL, pixelBufferAttributes,
&trackingCallBackRecord, &vs->vid.decompressionSession);
return err;
}
static OSStatus
_frame_compressed_callback(void *efRefCon, ICMCompressionSessionRef session,
OSStatus err, ICMEncodedFrameRef ef, void *reserved)
{
dbg_printf("[webM] enter _frame_compressed_callback(err = %d)\n", err);
GenericStreamPtr vs = (GenericStreamPtr) efRefCon;
if (err)
return err;
UInt32 enc_size = ICMEncodedFrameGetDataSize(ef);
ImageDescriptionHandle imgDesc;
err = ICMEncodedFrameGetImageDescription(ef, &imgDesc);
if (!err)
{
ImageDescription *id = *imgDesc;
dbg_printf("[webM --%08lx] :: _frame_compressed() = %ld, '%4.4s'"
" %08lx %08lx [%d x %d] [%f x %f] %ld %d %d %d\n",
(UInt32) - 1, err, (char *) &id->cType,
id->temporalQuality, id->spatialQuality, id->width,
id->height, id->hRes / 65536.0, id->vRes / 65536.0,
id->dataSize, id->frameCount, id->depth, id->clutID);
dbg_printf("[webM -- %08lx] :: _frame_compressed() = %lld %ld %ld\n",
(UInt32) - 1, ICMEncodedFrameGetDecodeDuration(ef),
enc_size, ICMEncodedFrameGetBufferSize(ef));
}
dbg_printf("[webM] allocate data %d bytes\n", enc_size);
//pass appropriate flags for frame type
ICMFrameType frame_type = ICMEncodedFrameGetFrameType(ef);
UInt16 frameFlags = VIDEO_FRAME;
//NOTE: With Altref frames, the decodeTimeStamp Represents the altref time
// this is a workaround that I don't like, ideally some other sort of
// parameter could handle this.
UInt64 displayTime = ICMEncodedFrameGetDisplayTimeStamp(ef);
UInt64 timeScale = ICMEncodedFrameGetTimeScale(ef);
dbg_printf("[WebM] ICMEncodedFrameGetDisplayTimeStamp %llu ICMEncodedFrameGetTimeScale %llu\n",
displayTime, timeScale);
UInt32 decodeNum = ICMEncodedFrameGetDecodeNumber(ef);
UInt32 timeMs = displayTime * 1000/timeScale;
dbg_printf("[WebM] adding frame %d to queue %lu flags %lx\n", decodeNum, timeMs, frameFlags);
if (frame_type != kICMFrameType_Unknown)
{
if (frame_type == kICMFrameType_I)
frameFlags += KEY_FRAME;
//create a buffer with frame data
void * buf = malloc(enc_size);
memcpy(buf, ICMEncodedFrameGetDataPtr(ef), enc_size);
addFrameToQueue(&vs->frameQueue, buf, enc_size, timeMs, frameFlags, decodeNum -1);
}
else
{
//There are two frames embedded in altref frames...
UInt32 decodeTimeMs = vs->vid.lastTimeMs + (timeMs - vs->vid.lastTimeMs)/2;
const unsigned char * cBuf = ICMEncodedFrameGetDataPtr(ef);
UInt32 altrefPortion= *((UInt32*)cBuf);
dbg_printf("[WebM]Size Of altref data in frame %lu at time %lu\n", altrefPortion, decodeTimeMs);
void * altrefBuf = malloc(altrefPortion);
memcpy(altrefBuf, &cBuf[4], altrefPortion);
frameFlags += ALT_REF_FRAME; // currently using the unknown to indicat alt-ref
addFrameToQueue(&vs->frameQueue, altrefBuf, altrefPortion, decodeTimeMs, frameFlags, decodeNum -1);
//also write the following interframe
UInt32 framePortion = enc_size - altrefPortion -4;
dbg_printf("[WebM]Size Of inter frame %lu at time %lu\n", framePortion, timeMs);
frameFlags = VIDEO_FRAME;
void * frameBuf = malloc(altrefPortion);
memcpy(frameBuf, &cBuf[altrefPortion+4], altrefPortion);
addFrameToQueue(&vs->frameQueue, frameBuf, framePortion, timeMs, frameFlags, decodeNum -1);
}
vs->vid.lastTimeMs = timeMs;
dbg_printf("[webM] exit _frame_compressed_callback(err = %d)\n", err);
return err;
}
//Using the componentInstance, load settings and then pass them to the compression session
//this in turn sends all these parameters to the VP8 Component
static ComponentResult setCompressionSettings(WebMExportGlobalsPtr glob, ICMCompressionSessionOptionsRef options)
{
ComponentInstance videoCI = NULL;
ComponentResult err = getVideoComponentInstace(glob, &videoCI);
if(err) goto bail;
// --- Hardcoded settings ---
//Allow P Frames
err = ICMCompressionSessionOptionsSetAllowTemporalCompression(options, true);
if (err) goto bail;
// Disable B frames.
err = ICMCompressionSessionOptionsSetAllowFrameReordering(options, false);
if (err) goto bail;
// --- Transfer spatial settings ----
SCSpatialSettings ss;
err = SCGetInfo(videoCI, scSpatialSettingsType, &ss);
if (err) goto bail;
dbg_printf("[WebM]Spatial settings - depth %d Quality %lx\n", ss.depth, ss.spatialQuality);
// ------ Transfer Temporal Settings --------
SCTemporalSettings ts;
err = SCGetInfo(videoCI, scTemporalSettingsType, &ts);
if (err) goto bail;
dbg_printf("[WebM] Temporal Settings max keyframerate %ld quality %ld frameRate %f\n",
ts.keyFrameRate, ts.temporalQuality,FixedToFloat(ts.frameRate));
SInt32 keyFrameRate = ts.keyFrameRate;
if (keyFrameRate != 0)
{
err = ICMCompressionSessionOptionsSetMaxKeyFrameInterval(options,
keyFrameRate);
if (err) goto bail;
}
err = ICMCompressionSessionOptionsSetProperty(options,
kQTPropertyClass_ICMCompressionSessionOptions,
kICMCompressionSessionOptionsPropertyID_Quality,
sizeof(CodecQ), &ts.temporalQuality);
if (err) goto bail;
err = ICMCompressionSessionOptionsSetProperty(options,
kQTPropertyClass_ICMCompressionSessionOptions,
kICMCompressionSessionOptionsPropertyID_ExpectedFrameRate,
sizeof(Fixed), &ts.frameRate);
if (err) goto bail;
// ------ Transfer Datarate Settings ----
SCDataRateSettings ds;
err = SCGetInfo(videoCI, scDataRateSettingsType, &ds);
dbg_printf("[webm] DataRateSettings %ld frameDuration %ld, spatial Quality %d, temporal Quality %d\n",
ds.dataRate, ds.frameDuration, ds.minSpatialQuality, ds.minTemporalQuality);
if (err) goto bail;
if (ds.dataRate != 0)
{
err = ICMCompressionSessionOptionsSetProperty(options,
kQTPropertyClass_ICMCompressionSessionOptions,
kICMCompressionSessionOptionsPropertyID_AverageDataRate,
sizeof(SInt32), &ds.dataRate);
if (err) goto bail;
}
// ------ Transfer Custom Settings ----
if (glob->videoSettingsCustom == NULL)
{
glob->videoSettingsCustom = NewHandleClear(0);
SetHandleSize(glob->videoSettingsCustom, 0);
}
err = SCGetInfo(videoCI, scCodecSettingsType, &glob->videoSettingsCustom);
if (glob->videoSettingsCustom != NULL)
{
err = ICMCompressionSessionOptionsSetProperty(options,
kQTPropertyClass_ICMCompressionSessionOptions,
kICMCompressionSessionOptionsPropertyID_CompressorSettings,
sizeof(glob->videoSettingsCustom),
&glob->videoSettingsCustom);
}
QTUnlockContainer(glob->videoSettingsAtom);
bail:
if (videoCI != NULL)
CloseComponent(videoCI);
if (err)
dbg_printf("[webm] Error in setCompressionSettingFromAC %d\n", err);
return err;
}
ComponentResult openCompressionSession(WebMExportGlobalsPtr globals, GenericStreamPtr vs)
{
ComponentResult err = noErr;
ICMCompressionSessionOptionsRef options;
ICMEncodedFrameOutputRecord efor;
ImageDescription *id = *(ImageDescriptionHandle) vs->source.params.desc;
int width = id->width;
int height = id->height;
StreamSource *source = &vs->source;
err = ICMCompressionSessionOptionsCreate(NULL, &options);
if (err) goto bail;
ICMCompressionSessionOptionsSetDurationsNeeded(options, true);
setCompressionSettings(globals, options);
efor.encodedFrameOutputCallback = _frame_compressed_callback;
efor.encodedFrameOutputRefCon = (void *) vs;
efor.frameDataAllocator = NULL;
//Even though VP8 doesn't use this, I am enabling a temporary storage file
// This is so quick time allows the two pass
if (vs->vid.bTwoPass)
{
ICMMultiPassStorageRef multiPassStorage = NULL;
OSStatus status = EnableMultiPassWithTemporaryFile(options, &multiPassStorage);
if (noErr != status) goto bail;
ICMMultiPassStorageRelease(multiPassStorage);
}
dbg_printf("[webM] openCompressionSession timeScale = %ld (%d x %d)\n",
vs->source.timeScale, width, height);
err = ICMCompressionSessionCreate(NULL, width,
height,
'VP80', /* fixed for now... */
vs->source.timeScale, options,
NULL, &efor, &vs->vid.compressionSession);
dbg_printf("[webM] created compression Session %d\n", err);
if(err) goto bail;
//After initializing the compression session, set passes if there are two passes
if (vs->vid.bTwoPass)
err = startPass(vs,1);
bail:
if (err)
dbg_printf("[WebM] Open Comprlession Session error = \n", err);
return err;
}
static void initFrameTimeRecord(GenericStreamPtr vs, ICMFrameTimeRecord *frameTimeRecord)
{
memset(frameTimeRecord, 0, sizeof(ICMFrameTimeRecord));
frameTimeRecord->recordSize = sizeof(ICMFrameTimeRecord);
//si->source.time is in milliseconds whereas this value needs to be in timeScale Units
//*(TimeValue64 *) &frameTimeRecord->value = vs->currentFrame * vs->source.params.durationPerSample / si->source.timeScale;
frameTimeRecord->value = SInt64ToWide(vs->source.time);
frameTimeRecord->scale = vs->source.timeScale;
frameTimeRecord->rate = fixed1;
frameTimeRecord->duration = vs->source.params.durationPerSample;
frameTimeRecord->flags = icmFrameTimeDecodeImmediately;
frameTimeRecord->frameNumber = vs->framesIn;
dbg_printf("[webM] init Frame Time %lld scale = %ld\n", frameTimeRecord->value, frameTimeRecord->scale);
}
//buffer is null when there are no more frames
ComponentResult compressNextFrame(WebMExportGlobalsPtr globals, GenericStreamPtr vs)
{
ComponentResult err = noErr;
ICMFrameTimeRecord frameTimeRecord;
initMovieGetParams(&vs->source);
err = InvokeMovieExportGetDataUPP(vs->source.refCon, &vs->source.params,
vs->source.dataProc);
if (err == eofErr)
{
vs->source.eos = true;
err= noErr;
}
else
{
vs->framesIn += 1;
}
if (err != noErr)
return err;
dbg_printDataParams(&vs->source);
initFrameTimeRecord(vs, &frameTimeRecord);
if (vs->vid.decompressionSession == NULL)
{
err = openDecompressionSession(vs);
dbg_printf("[webM] open new decompression session %d\n", err);
if (err != noErr) return err;
}
if (vs->vid.compressionSession == NULL)
{
err = openCompressionSession(globals, vs);
dbg_printf("[webM] open new compression session %d\n", err);
if (err != noErr) return err;
}
//the callback function also compresses, the compressed data is then kept in vs->outBuf.data
dbg_printf("[webm] Call ICMDecompressionSessionDecodeFrame\n");
if (!vs->source.eos)
{
dbg_printf("[WebM] Setting frame time to %lld\n",frameTimeRecord.value, frameTimeRecord.scale);
err = ICMDecompressionSessionDecodeFrame(vs->vid.decompressionSession,
(UInt8 *) vs->source.params.dataPtr,
vs->source.params.dataSize,
NULL, //session options
&frameTimeRecord, vs);
}
else
{
dbg_printf("Completing Frames\n");
ICMCompressionSessionCompleteFrames(vs->vid.compressionSession,
true, //complete all frames
0, //ignored when complete all frames true
0); //also ignored
vs->complete = true;
}
//increment next source time
double framerate = globals->framerate;
if (framerate == 0)
{
globals->framerate = (1.0 * vs->source.params.sourceTimeScale) / (1.0 * vs->source.params.durationPerSample );
dbg_printf("[webm] Recomputing framerate %ld / %ld\n",
vs->source.params.durationPerSample, vs->source.params.sourceTimeScale);
framerate = globals->framerate;
}
vs->source.time = (SInt32)(vs->framesIn / globals->framerate * vs->source.timeScale) ;
dbg_printf("exit compressFrame err = %d\n", err);
return err;
}
ComponentResult initVideoStream(GenericStreamPtr vs)
{
memset(vs, 0, sizeof(GenericStreamPtr));
}
ComponentResult startPass(GenericStreamPtr vs,int pass)
{
ComponentResult err = noErr;
ICMCompressionPassModeFlags cpFlag =0;
dbg_printf("[WEBM] Start pass %d session %ld\n", pass, (UInt32) vs->vid.compressionSession);
if (pass == 1)
{
ICMCompressionPassModeFlags readFlags;
Boolean bSupports = ICMCompressionSessionSupportsMultiPassEncoding(vs->vid.compressionSession,
0, &readFlags);
dbg_printf("[WebM] Supports multipass %d, flags %u\n", bSupports, readFlags);
cpFlag = kICMCompressionPassMode_WriteToMultiPassStorage;
}
else if (pass == 2)
cpFlag = kICMCompressionPassMode_OutputEncodedFrames | kICMCompressionPassMode_ReadFromMultiPassStorage;
else
return paramErr;
OSStatus os= ICMCompressionSessionBeginPass(vs->vid.compressionSession, cpFlag, 0);
if (os)
{
dbg_printf("[WebM] Error on ICMCompressionSessionBeginPass %d\n", os);
err = os; //TODO choose an apropriate error message
}
return err;
}
OSStatus endPass(GenericStreamPtr vs)
{
dbg_printf("[WEBM] End pass session %ld\n", (UInt32) vs->vid.compressionSession);
OSStatus os = ICMCompressionSessionEndPass(vs->vid.compressionSession);
if (os != 0)
dbg_printf("[WEBM] Error: endPass got error %d\n", os);
return os;
}