forked from wadetregaskis/cocoa-tlassemble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tlassemble.m
1526 lines (1276 loc) · 79.5 KB
/
tlassemble.m
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
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
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
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
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
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
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
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
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
/*
* Copyright (c) 2012-2013, Daniel Bridges & Wade Tregaskis
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the Daniel Bridges nor Wade Tregaskis nor the
* names of its contributors may 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 <COPYRIGHT HOLDER> 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.*
*/
#include <errno.h>
#include <getopt.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#import <AppKit/AppKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreFoundation/CoreFoundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import <CoreMedia/CoreMedia.h>
#import <CoreVideo/CoreVideo.h>
#import <Foundation/Foundation.h>
#import <ImageIO/ImageIO.h>
#import <VideoToolbox/VideoToolbox.h>
#import <VideoToolbox/VTVideoEncoderList.h>
static unsigned long logLevel = 0;
static const unsigned long V_CONFIGURATION = 1;
static const unsigned long V_CONFIGURATION_OPTIONS = 2;
static const unsigned long V_FRAME_EVENTS = 3;
static const unsigned long V_FRAME_METADATA = 4;
static const unsigned long V_FRAME_SORTING = 5;
#define DLOG(level, fmt, ...) ({ if (level <= logLevel) { NSLog(@"%s:%d " fmt, __FILE__, __LINE__, ## __VA_ARGS__); } })
#define LOG_WARNING(format, ...) ({ fflush(stdout); fprintf(stderr, "%s", [NSString stringWithFormat:@"WARNING: " format "\n", ## __VA_ARGS__].UTF8String); fflush(stderr); })
#define LOG_ERROR(format, ...) ({ fflush(stdout); fprintf(stderr, "%s", [NSString stringWithFormat:@"ERROR: " format "\n", ## __VA_ARGS__].UTF8String); fflush(stderr); })
static const double kDefaultFPS = 30;
static const char* DescriptionOfCVReturn(CVReturn status) {
switch (status) {
case kCVReturnError:
return "An otherwise undefined error occurred.";
case kCVReturnInvalidArgument:
return "Invalid function parameter. For example, out of range or the wrong type.";
case kCVReturnAllocationFailed:
return "Memory allocation for a buffer or buffer pool failed.";
case kCVReturnInvalidDisplay:
return "The display specified when creating a display link is invalid.";
case kCVReturnDisplayLinkAlreadyRunning:
return "The specified display link is already running.";
case kCVReturnDisplayLinkNotRunning:
return "The specified display link is not running.";
case kCVReturnDisplayLinkCallbacksNotSet:
return "No callback registered for the specified display link. You must set either the output callback or both the render and display callbacks.";
case kCVReturnInvalidPixelFormat:
return "The buffer does not support the specified pixel format.";
case kCVReturnInvalidSize:
return "The buffer cannot support the requested buffer size (usually too big).";
case kCVReturnInvalidPixelBufferAttributes:
return "A buffer cannot be created with the specified attributes.";
case kCVReturnPixelBufferNotOpenGLCompatible:
return "The pixel buffer is not compatible with OpenGL due to an unsupported buffer size, pixel format, or attribute.";
case kCVReturnWouldExceedAllocationThreshold:
return "Allocation for a pixel buffer failed because the threshold value set for the kCVPixelBufferPoolAllocationThresholdKey key in the CVPixelBufferPoolCreatePixelBufferWithAuxAttributes function would be surpassed.";
case kCVReturnPoolAllocationFailed:
return "Allocation for a buffer pool failed, most likely due to a lack of resources. Check to make sure your parameters are in range.";
case kCVReturnInvalidPoolAttributes:
return "A buffer pool cannot be created with the specified attributes.";
default:
return "Unknown.";
}
}
static void CreatePixelBufferFromCGImage(CGImageRef image,
NSSize frameSize,
int orientation,
dispatch_semaphore_t concurrencyLimiter,
dispatch_group_t group,
dispatch_queue_t outputQueue,
void (^outputBlock)(CVPixelBufferRef pixelBuffer)) {
if (0 != dispatch_semaphore_wait(concurrencyLimiter, DISPATCH_TIME_FOREVER)) {
LOG_ERROR("Somehow timed out waiting for the image rendering concurrency limiter semaphore, even though there was no timeout specified. Going ahead blindly...");
}
dispatch_group_async(group, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
// I've seen the following two settings recommended, but I'm not sure why we'd bother overriding them?
//NSDictionary *pixelBufferOptions = @{kCVPixelBufferCGImageCompatibilityKey: @NO,
// kCVPixelBufferCGBitmapContextCompatibilityKey, @NO};
CVPixelBufferRef pixelBuffer = NULL;
CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault,
frameSize.width,
frameSize.height,
kCVPixelFormatType_32ARGB,
NULL,
&pixelBuffer);
if (kCVReturnSuccess == status) {
status = CVPixelBufferLockBaseAddress(pixelBuffer, 0);
if (kCVReturnSuccess == status) {
void *data = CVPixelBufferGetBaseAddress(pixelBuffer);
if (data) {
CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
if (colourSpace) {
CGContextRef context = CGBitmapContextCreate(data,
frameSize.width,
frameSize.height,
8, // Bits per component
CVPixelBufferGetBytesPerRow(pixelBuffer),
colourSpace,
(CGBitmapInfo)kCGImageAlphaNoneSkipFirst); // + kCGBitmapByteOrder32Big? Or 16Big?
if (context) {
CGSize rotatedSize = frameSize;
// TODO: Get some samples of these other orientations and make them work too.
switch (orientation) {
case 0: // Unspecified; means assume 1
case 1: // "Top, left" - i.e. "normal", no-adjustments-needed rotation.
break;
case 2: // "Top, right"
LOG_ERROR("Unsupported image orientation, \"Top, right\". This frame may be drawn with incorrect rotation, mirroring, and/or proportions.");
break;
case 3: // "Bottom, right"
LOG_ERROR("Unsupported image orientation, \"Bottom, right\". This frame may be drawn with incorrect rotation, mirroring, and/or proportions.");
break;
case 4: // "Bottom, left"
LOG_ERROR("Unsupported image orientation, \"Bottom, left\". This frame may be drawn with incorrect rotation, mirroring, and/or proportions.");
break;
case 5: // "Left, top"
LOG_ERROR("Unsupported image orientation, \"Left, top\". This frame may be drawn with incorrect rotation, mirroring, and/or proportions.");
break;
case 6: // "Right, top"
LOG_ERROR("Unsupported image orientation, \"Right, top\". This frame may be drawn with incorrect rotation, mirroring, and/or proportions.");
break;
case 7: // "Right, bottom"
LOG_ERROR("Unsupported image orientation, \"Right, bottom\". This frame may be drawn with incorrect rotation, mirroring, and/or proportions.");
break;
case 8: // "Left, bottom"
rotatedSize = CGSizeMake(frameSize.height, frameSize.width);
CGContextTranslateCTM(context, rotatedSize.height / 2.0, rotatedSize.width / 2.0);
CGContextRotateCTM(context, M_PI_2);
CGContextTranslateCTM(context, -(rotatedSize.width / 2.0), -(rotatedSize.height / 2.0));
break;
default:
LOG_WARNING("Unknown image rotation (%d) - leaving as is, which may mean the frame is not correctly oriented in the output video.", orientation);
break;
}
if (kCVReturnSuccess == status) {
CGContextDrawImage(context,
CGRectMake(0, 0, rotatedSize.width, rotatedSize.height),
image);
}
CGContextRelease(context);
} else {
LOG_ERROR("Unable to create a new bitmap context around the pixel buffer.");
status = kCVReturnError;
}
CGColorSpaceRelease(colourSpace);
} else {
LOG_ERROR("Unable to create a device RGB colour space.");
}
} else {
LOG_ERROR("Unable to get a raw pointer to the pixel buffer.");
status = kCVReturnError;
}
const CVReturn nonFatalStatus = CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
if (kCVReturnSuccess != nonFatalStatus) {
LOG_WARNING("Unable to unlock pixel buffer, error #%d: %s", nonFatalStatus, DescriptionOfCVReturn(nonFatalStatus));
}
} else {
LOG_ERROR("Unable to lock pixel buffer, error #%d: %s", status, DescriptionOfCVReturn(status));
}
} else {
LOG_ERROR("Unable to create a pixel buffer, error #%d: %s", status, DescriptionOfCVReturn(status));
}
if (kCVReturnSuccess != status) {
CVPixelBufferRelease(pixelBuffer), pixelBuffer = NULL;
}
dispatch_group_async(group, outputQueue, ^{
outputBlock(pixelBuffer);
});
dispatch_semaphore_signal(concurrencyLimiter);
});
}
const char* NameOfAVAssetWriterStatus(AVAssetWriterStatus status) {
switch (status) {
case AVAssetWriterStatusUnknown:
return "Unknown";
case AVAssetWriterStatusWriting:
return "Writing";
case AVAssetWriterStatusCompleted:
return "Completed";
case AVAssetWriterStatusFailed:
return "Failed";
case AVAssetWriterStatusCancelled:
return "Cancelled";
default:
return "Especially unknown";
}
}
@interface FrameOutputContext : NSObject
@property(readwrite) AVAssetWriter *assetWriter;
@property(readwrite) AVAssetWriterInput *assetWriterInput;
@property(readwrite) BOOL quiet;
@end
@implementation FrameOutputContext
@end
static void compressedFrameOutput(void *rawContext,
void *frameNumber,
OSStatus status,
VTEncodeInfoFlags infoFlags,
CMSampleBufferRef sampleBuffer) {
if (0 != status) {
LOG_ERROR("Unable to compress frame #%"PRIuPTR", error #%d.", (uintptr_t)frameNumber, status);
exit(1);
}
FrameOutputContext *context = (__bridge FrameOutputContext*)rawContext;
if (context) {
if (context.assetWriterInput) {
if ([context.assetWriterInput appendSampleBuffer:sampleBuffer]) {
if (!context.quiet) {
printf("Completed frame #%"PRIuPTR".\n", (uintptr_t)frameNumber);
}
} else {
LOG_ERROR("Unable to append compressed frame #%"PRIuPTR" to file, status = %s (%@).",
(uintptr_t)frameNumber,
NameOfAVAssetWriterStatus(context.assetWriter.status),
context.assetWriter.error.description);
exit(1);
}
}
}
}
#ifndef countof
#define countof(_x_) (sizeof(_x_) / sizeof(*_x_))
#endif
static BOOL applyTimeSuffix(double *value, const char *suffix, BOOL invert) {
const struct {
char suffix[3];
double multiplier;
} suffixes[] = {
{"w", 604800.0},
{"d", 86400.0},
{"h", 3600.0},
{"m", 60.0},
{"s", 1.0},
{"ms", 0.001},
{"us", 0.000001},
{"µs", 0.000001},
{"ns", 0.000000001},
{"ps", 0.000000000001},
};
for (int i = 0; i < countof(suffixes); ++i) {
if (0 == strcmp(suffix, suffixes[i].suffix)) {
if (invert) {
*value /= suffixes[i].multiplier;
} else {
*value *= suffixes[i].multiplier;
}
return YES;
}
}
return NO;
}
static BOOL applyBitSuffix(double *value, const char *suffix) {
const char kModifiers[] = "KMGTPEZY";
const char *modifier = (('k' == suffix[0]) ? kModifiers : strchr(kModifiers, suffix[0]));
if (modifier) {
const uintptr_t factor = (uintptr_t)modifier - (uintptr_t)kModifiers + 1;
const BOOL baseTwo = ('i' == suffix[1]);
*value *= (baseTwo ? exp2(factor * 10) : __exp10(factor * 3));
++suffix;
if (baseTwo) {
++suffix;
}
}
switch (suffix[0]) {
case 'b':
// Do nothing.
break;
case 'B':
*value *= 8;
break;
case 0:
// Do nothing.
break;
default:
return NO;
}
return YES;
}
static BOOL applyBitRateSuffix(double *value, const char *suffix) {
char *divider = strchr(suffix, '/');
if (divider) {
char *bytePortion = strndup(suffix, divider - suffix);
assert(bytePortion);
BOOL allGood = applyBitSuffix(value, bytePortion);
free(bytePortion);
if (allGood) {
return applyTimeSuffix(value, divider + 1, YES);
} else {
return NO;
}
} else {
return applyBitSuffix(value, suffix);
}
}
static BOOL determineBitsPerTimeInterval(double *bits, double *timeInterval, const char *suffix) {
char *divider = strchr(suffix, '/');
if (divider) {
char *bytePortion = strndup(suffix, divider - suffix);
assert(bytePortion);
BOOL allGood = applyBitSuffix(bits, bytePortion);
free(bytePortion);
if (allGood) {
char *end = NULL;
double timeScalar = strtod(divider + 1, &end);
if (end) {
if (end == divider + 1) {
timeScalar = 1;
}
*timeInterval *= timeScalar;
if (*end) {
return applyTimeSuffix(timeInterval, end, YES);
} else {
return YES;
}
} else {
return NO;
}
} else {
return NO;
}
} else {
return applyBitSuffix(bits, suffix);
}
}
void prescanFile(NSURL *file,
const double speed,
NSDate **earliestFrame,
NSDate **latestFrame,
NSMutableDictionary *fileCreationDates,
NSMutableArray *imageFiles,
dispatch_semaphore_t concurrencyLimiter,
dispatch_group_t group,
dispatch_queue_t serialisationQueue) {
if (0 != dispatch_semaphore_wait(concurrencyLimiter, DISPATCH_TIME_FOREVER)) {
LOG_ERROR("Somehow timed out waiting for the prescan concurrency limiter semaphore, even though there was no timeout specified. Going ahead blindly...");
}
dispatch_group_async(group, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
BOOL fileLooksGood = YES;
if (0 < speed) {
// Unfortunately the file system's idea of creation date is often not very precise, nor accurate - some cameras (e.g. D7100) can end up creating files roughly simultaneously, despite the images of course being sequential (presumably as some kind of batching optimisation when emptying the in-camera image buffer). So we try to get the actual recording time of the image out of the EXIF metadata, and only fall back to the file's creation date as a last resort.
id creationDate;
NSError *err;
NSDictionary *imageSourceOptions = @{ (__bridge NSString*)kCGImageSourceShouldAllowFloat: @YES,
(__bridge NSString*)kCGImageSourceShouldCache: @NO,
(__bridge NSString*)kCGImageSourceCreateThumbnailFromImageIfAbsent: @NO,
(__bridge NSString*)kCGImageSourceCreateThumbnailFromImageAlways: @NO };
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((__bridge CFURLRef)file, (__bridge CFDictionaryRef)imageSourceOptions);
if (imageSource) {
NSDictionary *imageProperties = CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(imageSource, 0, (__bridge CFDictionaryRef)imageSourceOptions));
if (imageProperties) {
NSDictionary *exifProperties = imageProperties[(__bridge NSString*)kCGImagePropertyExifDictionary];
if (exifProperties) {
NSString *dateAsString = exifProperties[(__bridge NSString*)kCGImagePropertyExifDateTimeOriginal];
DLOG(V_FRAME_METADATA, @"Raw creation date for \"%@\": %@", file.path, dateAsString);
creationDate = [NSDate dateWithNaturalLanguageString:dateAsString];
}
} else {
LOG_ERROR("Unable to get image metadata for \"%@\".", file.path);
fileLooksGood = NO;
}
CFRelease(imageSource);
} else {
LOG_ERROR("Unable to create an image source for \"%@\".", file.path);
fileLooksGood = NO;
}
if (!creationDate) {
if (![file getResourceValue:&creationDate forKey:NSURLCreationDateKey error:&err]) {
LOG_ERROR("Unable to determine the creation date of \"%@\".", file.path);
fileLooksGood = NO;
}
}
if (creationDate) {
dispatch_group_async(group, serialisationQueue, ^{
DLOG(V_FRAME_METADATA, @"Creation date of \"%@\": %@", file.path, creationDate);
fileCreationDates[file] = creationDate;
*earliestFrame = (*earliestFrame ? [*earliestFrame earlierDate:creationDate] : creationDate);
*latestFrame = (*latestFrame ? [*latestFrame laterDate:creationDate] : creationDate);
});
}
}
if (fileLooksGood) {
dispatch_async(serialisationQueue, ^{
[imageFiles addObject:file];
});
}
dispatch_semaphore_signal(concurrencyLimiter);
});
}
@interface RenderedFrame : NSObject
@property(readwrite) CVPixelBufferRef pixelBuffer;
@property(readwrite) NSURL *file;
@property(readwrite) unsigned long fileIndex;
@property(readwrite) unsigned long frameIndex;
@property(readwrite) CMTime frameTime;
@property(readwrite) NSDate *creationDate;
@end
@implementation RenderedFrame
@end
int main(int argc, char* const argv[]) {
@autoreleasepool {
static const struct option longOptions[] = {
{"assume-preceding-frames", no_argument, NULL, 16},
{"assume-succeeding-frames", no_argument, NULL, 17},
{"average-bit-rate", required_argument, NULL, 14},
{"codec", required_argument, NULL, 1},
{"dryrun", no_argument, NULL, 10},
{"entropy-mode", required_argument, NULL, 18},
{"file-type", required_argument, NULL, 20},
{"filter", required_argument, NULL, 9},
{"fps", required_argument, NULL, 2},
{"frame-limit", required_argument, NULL, 22},
{"height", required_argument, NULL, 3},
{"help", no_argument, NULL, 4},
{"key-frames-only", no_argument, NULL, 12},
{"max-frame-delay", required_argument, NULL, 19},
{"max-key-frame-period", required_argument, NULL, 11},
{"non-recursive", no_argument, NULL, 24},
{"quality", required_argument, NULL, 5},
{"quiet", no_argument, NULL, 6},
{"rate-limit", required_argument, NULL, 15},
{"reverse", no_argument, NULL, 7},
{"speed", required_argument, NULL, 21},
{"sort", required_argument, NULL, 8},
{"strict-frame-ordering", no_argument, NULL, 13},
{"verbosity", required_argument, NULL, 23},
{NULL, 0, NULL, 0}
};
NSMutableDictionary *compressionSettings = [NSMutableDictionary dictionary];
double fps = 0.0;
double speed = 0.0;
long height = 0;
CMVideoCodecType codec = 'avc1';
NSString *encoderID;
NSString *fileType;
BOOL quiet = NO;
BOOL reverseOrder = NO;
NSString *sortAttribute = @"creation";
NSMutableDictionary *filter = [NSMutableDictionary dictionary];
BOOL dryrun = NO;
unsigned long long frameLimit = -1;
BOOL scanInputFilesRecursively = YES;
long concurrencyLimit;
size_t concurrencyLimitSize = sizeof(concurrencyLimit);
if (0 != sysctlbyname("hw.logicalcpu", &concurrencyLimit, &concurrencyLimitSize, NULL, 0)) {
LOG_WARNING(@"Unable to determine how many logical cores this Mac contains, in order to optimise the level of concurrency. Making a conservative assumption instead.");
concurrencyLimit = 4;
}
// Has to be here so it can be referenced in the creation-time sort comparator, below. Also, needs to be __block so that it's refered to by reference, and will thus see modifications (i.e. when it's created later on, if necessary). As opposed to the default behaviour, for non-__block variables, which is to copy their current value at the time the block is created.
__block NSMutableDictionary *fileCreationDates;
NSDictionary *sortComparators = @{
@"name": ^(NSURL *a, NSURL *b) {
return [(reverseOrder ? b : a).lastPathComponent compare:(reverseOrder ? a : b).lastPathComponent
options:( NSCaseInsensitiveSearch
| NSNumericSearch
| NSDiacriticInsensitiveSearch
| NSWidthInsensitiveSearch
| NSForcedOrderingSearch)];
},
@"creation": ^(NSURL *a, NSURL *b) {
id aCreationDate = fileCreationDates[a], bCreationDate = fileCreationDates[b];
NSError *err;
if (!aCreationDate && ![a getResourceValue:&aCreationDate forKey:NSURLCreationDateKey error:&err]) {
LOG_ERROR("Unable to determine the creation date of \"%@\".", a.path);
return (reverseOrder ? NSOrderedAscending : NSOrderedDescending);
} else if (!bCreationDate && ![b getResourceValue:&bCreationDate forKey:NSURLCreationDateKey error:&err]) {
LOG_ERROR("Unable to determine the creation date of \"%@\".", b.path);
return (reverseOrder ? NSOrderedDescending : NSOrderedAscending);
} else {
const NSComparisonResult result = (reverseOrder ? [bCreationDate compare:aCreationDate] : [aCreationDate compare:bCreationDate]);
DLOG(V_FRAME_SORTING,
"\"%@\" (%@) %c \"%@\" (%@).",
a,
aCreationDate,
((NSOrderedSame == result) ? '=' : ((NSOrderedAscending == result) ? '<' : '>')),
b,
bCreationDate);
if (NSOrderedSame == result) {
LOG_WARNING(@"\"%@\" and \"%@\" have the same creation date - %@ - and so their true order cannot be discerned. They'll be ordered arbitrarily with respect to each other.", a, b, aCreationDate);
}
return result;
}
}
};
NSDictionary *sortFileAttributeKeys = @{ @"name" : @[],
@"creation": @[NSURLCreationDateKey] };
int optionIndex = 0;
while (-1 != (optionIndex = getopt_long(argc, argv, "", longOptions, NULL))) {
switch (optionIndex) {
case 1: {
CFArrayRef supportedVideoEncoders = NULL;
const OSStatus status = VTCopyVideoEncoderList(NULL, &supportedVideoEncoders);
if (0 != status) {
LOG_ERROR("Unable to determine the supported video codecs, error #%d.", status);
return 1;
}
NSMutableDictionary *codecMap = [NSMutableDictionary dictionary];
NSMutableDictionary *encoderMap = [NSMutableDictionary dictionary];
for (NSDictionary *codecSpec in CFBridgingRelease(supportedVideoEncoders)) {
NSString *codecName = codecSpec[(__bridge NSString*)kVTVideoEncoderList_DisplayName];
if (codecMap[codecName]) {
LOG_WARNING("Found two encoders with the same name - \"%@\".", codecName);
}
codecMap[codecName] = codecSpec[(__bridge NSString*)kVTVideoEncoderList_CodecType];
encoderMap[codecName] = codecSpec[(__bridge NSString*)kVTVideoEncoderList_EncoderID];
}
codec = ((NSNumber*)codecMap[@(optarg)]).intValue;
encoderID = encoderMap[@(optarg)];
if (!codec || !encoderID) {
LOG_ERROR("Unrecognised codec \"%s\". Supported codecs are:", optarg);
for (NSString *code in [codecMap.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]) {
LOG_ERROR(" %@", code);
}
return EINVAL;
}
break;
}
case '2': {
char *end = NULL;
fps = strtod(optarg, &end);
if (!end || (end == optarg) || *end || (0 >= fps)) {
LOG_ERROR("Invalid argument \"%s\" to --fps. Should be a non-zero, positive real value (e.g. 24.0, 29.97, etc).", optarg);
return EINVAL;
}
break;
}
case 3: {
char *end = NULL;
height = strtol(optarg, &end, 0);
if (!end || (end == optarg) || *end || (0 >= height)) {
LOG_ERROR("Invalid argument \"%s\" to --height. Should be a non-zero, positive integer.", optarg);
return EINVAL;
}
break;
}
case 4:
printf("Usage: %s [FLAGS...] SOURCE [SOURCE...] DESTINATION.MOV\n"
"\n"
"SOURCE must be specified at least once. Each instance is the name or path to an image file or a folder containing images. Folders are searched exhaustively and recursively (but symlinks are not followed). Images which cannot be opened will be skipped. If no valid images are found, the program will fail and return a non-zero exit status.\n"
"\n"
"DESTINATION specifies the output file for the movie. It must end with a '.mov' suffix and must not already exist.\n"
"\n",
argv[0]);
printf("FLAGS:\n"
"\t--assume-preceding-frames: Assume additional frames will be prefixed to the output movie file later, so adjust encoding settings to accomodate.\n"
"\t--assume-succeeding-frames: Assume additional frames will be appended to the output movie file later, so adjust encoding settings to accomodate.\n"
"\t--average-bit-rate: The target average bitrate, e.g. \"3mb\" or \"450kB\". Actual bitrate may fluctuate above and below this goal.\n"
"\t--codec: Codec with which to compress the resulting movie. Defaults to 'h264'.\n"
"\t--dryrun: Don't actually create the output movie. Simulates most of the process, however, to give you a good idea of how it'd go. Off by default.\n"
"\t--entropy-mode: Either \"CAVLC\" or \"CABAC\". CABAC generally yields better compression, at the expense of higher CPU usage in encoding and playback.\n"
"\t--file-type: The format for the output file - one of \"mov\", \"mp4\" or \"m4v\". The default is \"mov\", or derived from the output file name (if specified and with a file extension).\n"
"\t--filter: Specify a filter on the image metadata for each frame. e.g. 'Model=Nikon D5200'. May be specified multiple times to add successive filters. Filters are case insensitive.\n"
"\t--fps: Frame rate of the movie. Defaults to 30.\n"
"\t--frame-limit: The maximum number of frames to encode. This is mainly useful for encoding testing and 'dry-running', by letting you limit the encode to just an initial subset of the full movie.\n"
"\t--height: The desired height of the movie; source frames will be proportionately resized. If unspecified the height is taken from the source frames.\n"
"\t--help: Prints out this usage information.\n"
"\t--key-frames-only: Use only 'key' frames (I-frames). This yields larger video files, but ones which may exhibit less quality loss as a result of subsequent editing (e.g. in Final Cut Pro or iMovie).\n"
"\t--max-frame-delay: The maximum number of frames that the encoder may hold in its internal buffer, during compression. This basically limits how far, forward or back, the encoder can go to reference other frames during temporal compression. Smaller values typically make the output video slightly larger, but compatible with a wider range of playback devices.\n"
"\t--max-key-frame-period: The maximum amount of time (if a time unit is specified, e.g. \"5s\" or \"10ms\") or number of frames (if just a number is specified, e.g. \"25\" or \"10\") between key frames (I-frames). Higher values permit better compression, but make the output video more difficult for subsequent editing software to use [without losing quality], and may prevent correct playback on some devices.\n"
"\t--quality: Quality level to encode with can. Defaults to 'high'.\n"
"\t--quiet: Supresses non-error output. Off by default.\n"
"\t--rate-limit: The absolute date rate limit (as opposed to --average-bit-rate, for example). Useful for compatibility with lesser playback devices, which may not be able to handle bitrates above a certain threshold.\n"
"\t--reverse: Reverse the sort order.\n"
"\t--sort: Sort method for the input images. Defaults to 'creation'.\n"
"\t--speed: How much to speed up the frames versus real time (when they were captured). By default each frame is simply blindly played back a fixed interval of time after the previous (i.e. 1 / --fps). When this parameter is specified, the real time relation between each frame is preserved (albeit shrunk by this multiplier). This is particularly useful if your interval between frames changed during shooting (e.g. due to changing light changing shutter speed). It can also yield more natural results if there are missing frames or otherwise gaps in recording.\n"
"\t--strict-frame-ordering: If specified, disables frame reordering. Resulting output files will be compatible with more playback devices but the video quality may suffer.\n"
"\t--verbosity: A numeric verbosity level, either 0 (i.e. verbose logging off, the default), 1, 2, or 3 (corresponding to increasing levels of detail). Typically useful only for debugging and development.\n"
"\n");
printf("EXAMPLES\n"
"\t%s ./images time_lapse.mov\n"
"\t%s --fps 30 --height 720 --codec h264 --quality high imagesA imagesB time_lapse.mov\n"
"\t%s --quiet image01.jpg image02.jpg image03.jpg time_lapse.mov\n"
"\n"
"WARRANTY\n"
"There isn't one. This software is provided in the hope that it will be useful, but without any warranty, without even the implied warranty for merchantability or fitness for a particular purpose. The software is provided as-is and its authors are not to be held responsible for any harm that may result from its use, including (but not limited to) data loss or corruption.\n",
argv[0], argv[0], argv[0]);
return 0;
case 5: {
char *end = NULL;
const double quality = strtod(optarg, &end);
if (end && (end != optarg) && !*end && (0.0 <= quality) && (1.0 >= quality)) {
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_Quality] = @(quality);
} else {
LOG_ERROR("Invalid --quality argument \"%s\" - expect a floating-point value between 0.0 and 1.0 (inclusive).", optarg);
return EINVAL;
}
break;
}
case 6:
quiet = YES;
break;
case 7:
reverseOrder = YES;
break;
case 8:
sortAttribute = @(optarg);
if (!sortComparators[sortAttribute]) {
LOG_ERROR("Unsupported sort method \"%s\". Supported methods are:", optarg);
for (NSString *method in sortComparators) {
LOG_ERROR(" %@", method);
}
return EINVAL;
}
break;
case 9: {
NSArray *pair = [@(optarg) componentsSeparatedByString:@"="];
if (2 == pair.count) {
NSCharacterSet *whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet;
filter[[pair[0] stringByTrimmingCharactersInSet:whitespace].lowercaseString] = [pair[1] stringByTrimmingCharactersInSet:whitespace];
} else {
LOG_ERROR("Unable to parse filter argument \"%s\" - expected something like 'property = value'.", optarg);
return EINVAL;
}
break;
}
case 10:
dryrun = YES;
break;
case 11: {
BOOL allGood = NO;
char *end = NULL;
double max = strtod(optarg, &end);
if (end && (end != optarg)) {
if (*end) {
if (applyTimeSuffix(&max, end, NO)) {
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration] = @(max);
allGood = YES;
}
} else {
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_MaxKeyFrameInterval] = @(lround(max));
allGood = YES;
}
}
if (!allGood) {
LOG_ERROR("Invalid parameter \"%s\" to --max_key_frame_period. Expected an integer number of frames or a floating-point unit of time with appropriate suffix (e.g. 's', 'ms', etc).", optarg);
return EINVAL;
}
break;
}
case 12:
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_AllowTemporalCompression] = @(NO);
break;
case 13:
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_AllowFrameReordering] = @(NO);
break;
case 14: {
char *end = NULL;
double averageBitRate = strtod(optarg, &end);
BOOL allGood = NO;
if (end && (end != optarg)) {
if (*end) {
if (applyBitRateSuffix(&averageBitRate, end)) {
allGood = YES;
}
} else {
allGood = YES;
}
}
if (allGood) {
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_AverageBitRate] = @(averageBitRate);
} else {
LOG_ERROR("Invalid --average-bit-rate argument \"%s\" - expected a floating-point number optionally followed by units (e.g. 'Mb' [implied per second] or 'kB/ms' etc).", optarg);
return EINVAL;
}
break;
}
case 15: {
char *end = NULL;
double rateLimit = strtod(optarg, &end);
double interval = 1;
BOOL allGood = NO;
if (end && (end != optarg)) {
if (*end) {
if (determineBitsPerTimeInterval(&rateLimit, &interval, end)) {
allGood = YES;
}
} else {
allGood = YES;
}
}
if (allGood) {
if (!compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_DataRateLimits]) {
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_DataRateLimits] = [NSMutableArray array];
}
[compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_DataRateLimits] addObject:@(rateLimit)];
[compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_DataRateLimits] addObject:@(interval)];
} else {
LOG_ERROR("Invalid --rate-limit argument \"%s\" - expected a floating-point number optionally followed by units (e.g. 'Mb' [implied per second] or 'kB/ms' or 'b/10s' etc).", optarg);
return EINVAL;
}
break;
}
case 16:
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_MoreFramesBeforeStart] = @(YES);
break;
case 17:
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_MoreFramesAfterEnd] = @(YES);
break;
case 18: {
NSDictionary *entropyModes = @{@"cavlc": (__bridge NSString*)kVTH264EntropyMode_CAVLC,
@"cabac": (__bridge NSString*)kVTH264EntropyMode_CABAC};
NSString *mode = entropyModes[[@(optarg) lowercaseString]];
if (mode) {
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_H264EntropyMode] = mode;
} else {
LOG_ERROR("Unrecognised entropy mode \"%s\".", optarg);
return EINVAL;
}
break;
}
case 19: {
char *end = NULL;
const unsigned long long maxFrameDelay = strtoull(optarg, &end, 0);
if (end && (end != optarg) && !*end) {
compressionSettings[(__bridge NSString*)kVTCompressionPropertyKey_MaxFrameDelayCount] = @(maxFrameDelay);
} else {
LOG_ERROR("Invalid --max-frame-delay argument \"%s\" - expect a positive integer (or zero).", optarg);
return EINVAL;
}
break;
}
case 20:
fileType = @(optarg);
break;
case 21: { // --speed
char *end = NULL;
speed = strtod(optarg, &end);
if (!end || (end == optarg) || *end || (0 >= speed)) {
LOG_ERROR("Invalid --speed argument \"%s\" - expect a positive floating-point number.", optarg);
return EINVAL;
}
break;
}
case 22: { // --frame-limit
char *end = NULL;
frameLimit = strtoll(optarg, &end, 0);
if (!end || (end == optarg) || *end || (0 >= frameLimit)) {
LOG_ERROR("Invalid --frame-limit argument \"%s\" - expect a positive integer.", optarg);
return EINVAL;
}
break;
}
case 23: { // --verbosity
char *end = NULL;
logLevel = strtoul(optarg, &end, 0);
if (!end || (end == optarg) || *end) {
LOG_ERROR("Invalid --verbosity argument \"%s\" - expect a positive integer (or zero).", optarg);
return EINVAL;
}
break;
}
case 24: // --non-recursive
scanInputFilesRecursively = NO;
break;
default:
LOG_ERROR("Invalid arguments (%d).", optionIndex);
return EINVAL;
}
}
const char *invocationString = argv[0];
argc -= optind;
argv += optind;
if (2 > argc) {
LOG_ERROR("Expect additional parameters specifying the source & destination.");
fprintf(stderr, "Usage: %s [FLAGS...] SOURCE [SOURCE...] DESTINATION.MOV\n", invocationString);
return EINVAL;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *destPath = [NSURL fileURLWithPath:[@(argv[argc - 1]) stringByExpandingTildeInPath]];
DLOG(V_CONFIGURATION, @"Destination Path: %@", destPath);
if (!fileType) {
NSString *fileExtension = destPath.pathExtension.lowercaseString;
if (fileExtension) {
NSDictionary *fileTypeFromExtension = @{@"mov": AVFileTypeQuickTimeMovie,
@"mp4": AVFileTypeMPEG4,
@"m4v": AVFileTypeAppleM4V};
fileType = fileTypeFromExtension[fileExtension];
}
if (!fileType) {
fileType = AVFileTypeQuickTimeMovie;
}
}
if ([fileManager fileExistsAtPath:destPath.path]) {
LOG_ERROR("Output file (\"%@\") already exists.", destPath.path);
return 1;
}
BOOL isDir;
if (!([fileManager fileExistsAtPath:[destPath.path stringByDeletingLastPathComponent]
isDirectory:&isDir]
&& isDir)) {
LOG_ERROR("Output file (\"%@\") is not writable. Does the destination directory exist?", destPath.path);
return 1;
}
NSMutableArray *filePropertyKeys = [sortFileAttributeKeys[sortAttribute] mutableCopy];
[filePropertyKeys addObject:NSURLIsDirectoryKey];
if (0 < speed) {
if (![filePropertyKeys containsObject:NSURLCreationDateKey]) {
[filePropertyKeys addObject:NSURLCreationDateKey];
}
fileCreationDates = [NSMutableDictionary dictionary];
}
NSMutableArray *imageFiles = [NSMutableArray array];
NSDate *earliestFrame, *latestFrame;
if (!quiet) {
printf("Scanning inputs (%srecursively) to find input images...\n", (scanInputFilesRecursively ? "" : "non-"));
}
dispatch_semaphore_t concurrencyLimiter = dispatch_semaphore_create(concurrencyLimit);
if (!concurrencyLimiter) {
LOG_ERROR("Unable to create image rendering concurrency limiter semaphore.");
exit(-1);
}
{
dispatch_group_t prescanGroup = dispatch_group_create();
if (!prescanGroup) {
LOG_ERROR("Unable to create prescan group.");
exit(-1);
}
dispatch_queue_t serialisationQueue = dispatch_queue_create("Prescan Serialisation", DISPATCH_QUEUE_SERIAL);
if (!serialisationQueue) {
LOG_ERROR("Unable to create prescan serialisation queue.");
exit(-1);
}
for (int i = 0; i < argc - 1; ++i) {
NSURL *inputPath = [NSURL fileURLWithPath:[@(argv[i]) stringByExpandingTildeInPath]];
DLOG(V_CONFIGURATION, @"Input Path: %@", inputPath);
if (![fileManager fileExistsAtPath:inputPath.path isDirectory:&isDir]) {
LOG_ERROR("Input file/folder \"%@\" does not exist.", inputPath.path);
return EINVAL;
}