-
Notifications
You must be signed in to change notification settings - Fork 14
/
MP4Writer.m
264 lines (205 loc) · 8.97 KB
/
MP4Writer.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
//
// MP4Writer.m
// SDKSampleApp
//
// This code and all components © 2015 – 2019 Wowza Media Systems, LLC. All rights reserved.
// This code is licensed pursuant to the BSD 3-Clause License.
//
#import "MP4Writer.h"
#import <AVFoundation/AVFoundation.h>
NSString *const MP4Filename = @"GoCoderMovie.mov";
static BOOL isKeyFrame(CMSampleBufferRef sample) {
BOOL isKey = NO;
CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sample, 0);
if (CFArrayGetCount(attachments) > 0) {
CFBooleanRef value;
Boolean notSyncValue = CFDictionaryGetValueIfPresent
((CFDictionaryRef) CFArrayGetValueAtIndex(attachments, 0),
kCMSampleAttachmentKey_NotSync,
(const void **)(&value));
isKey = !notSyncValue || !CFBooleanGetValue(value);
}
return isKey;
}
@interface MP4Writer () {
}
@property (nonatomic, assign, readwrite) BOOL writing;
@property (nonatomic, strong) AVAssetWriter* writer;
@property (nonatomic, strong) AVAssetWriterInput *videoWriterInput;
@property (nonatomic, strong) AVAssetWriterInput *audioWriterInput;
@property (nonatomic, assign) BOOL startedSession;
@property (nonatomic, assign) BOOL firstVideoBuffer;
@property (nonatomic, assign) BOOL firstAudioBuffer;
@property (nonatomic, assign) CMTime firstVideoFrameTime;
@end
@implementation MP4Writer
- (BOOL) prepareWithConfig:(WowzaConfig *)config {
BOOL result = FALSE;
NSError *error = nil;
NSURL *videoURL = [self videoFilePath];
if (videoURL) {
self.writer = [[AVAssetWriter alloc] initWithURL:videoURL fileType:AVFileTypeMPEG4 error:&error];
if (error) {
return result;
}
// video input
CMVideoFormatDescriptionRef formatDescription = nil;
CMVideoFormatDescriptionCreate(NULL, kCMVideoCodecType_H264, (int32_t)config.videoWidth, (int32_t)config.videoHeight, nil, &formatDescription);
self.videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:nil sourceFormatHint:formatDescription];
self.videoWriterInput.expectsMediaDataInRealTime = YES;
[self.writer addInput:self.videoWriterInput];
// audio input will be initialized when first audio frame arrives
if (config.audioEnabled) {
[self prepareAudioWriter];
}
result = TRUE;
}
return result;
}
- (CMAudioFormatDescriptionRef) makeAudioFormatDescription {
CMAudioFormatDescriptionRef audioFormat = nil;
AudioStreamBasicDescription absd = {0};
absd.mSampleRate = [[AVAudioSession sharedInstance] sampleRate];
absd.mFormatID = kAudioFormatMPEG4AAC;
absd.mFormatFlags = kMPEG4Object_AAC_Main;
CMAudioFormatDescriptionCreate(NULL, &absd, 0, NULL, 0, NULL, NULL, &audioFormat);
return audioFormat;
}
- (void) prepareAudioWriter {
if (self.audioWriterInput == nil) {
self.audioWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:nil sourceFormatHint:self.makeAudioFormatDescription];
self.audioWriterInput.expectsMediaDataInRealTime = YES;
[self.writer addInput:self.audioWriterInput];
}
}
- (void) startWriting {
if (self.writer.status != AVAssetWriterStatusWriting) {
self.startedSession = NO;
self.firstAudioBuffer = YES;
self.firstVideoBuffer = YES;
self.firstVideoFrameTime = kCMTimeInvalid;
self.writing = YES;
if (![self.writer startWriting]) {
NSLog (@"Error in startWriting");
[self logWriterStatus];
}
else {
NSLog (@"Started writing video file");
}
}
}
- (void) stopWriting {
self.writing = NO;
[self.writer finishWritingWithCompletionHandler:^{
NSLog(@"Stopped writing video file");
}];
}
- (void) logPresentationTime:(CMSampleBufferRef)sample logPrefix:(NSString *)logPrefix {
// Note: uncomment the below if you want to log the time stamp of each audio and video sample that is written
// CMTime time = CMSampleBufferGetPresentationTimeStamp(sample);
// float seconds = CMTimeGetSeconds(time);
// NSLog(@"%@ time: %0.3f", logPrefix, seconds);
}
- (void) appendVideoSample:(CMSampleBufferRef)videoSample {
if (self.firstVideoBuffer && !isKeyFrame(videoSample)) {
NSLog(@"MP4Writer:appendVideoSample: first frame not key, discarding");
return;
}
self.firstVideoBuffer = NO;
if (self.videoWriterInput.readyForMoreMediaData && self.writer.status == AVAssetWriterStatusWriting) {
if (videoSample != nil) {
if (!self.startedSession) {
CMTime pts = CMSampleBufferGetPresentationTimeStamp(videoSample);
[self.writer startSessionAtSourceTime:pts];
self.startedSession = YES;
NSLog(@"MP4Writer: started session in appendVideoSample");
}
BOOL appended = [self.videoWriterInput appendSampleBuffer:videoSample];
if (CMTimeCompare(kCMTimeInvalid, self.firstVideoFrameTime) == 0) {
self.firstVideoFrameTime = CMSampleBufferGetPresentationTimeStamp(videoSample);
}
[self logPresentationTime:videoSample logPrefix:@"Video Sample"];
if (!appended) {
[self logWriterStatus];
}
}
}
else {
NSLog(@"MP4Writer:appendVideoSample - sample not appended; readyForMoreMediaData = %d, status = %ld", self.audioWriterInput.readyForMoreMediaData, (long)self.writer.status);
}
}
- (void) primeAudio:(CMSampleBufferRef)audioSample {
CMAttachmentMode attachmentMode;
CFTypeRef trimDuration = CMGetAttachment(audioSample, kCMSampleBufferAttachmentKey_TrimDurationAtStart, &attachmentMode);
if (!trimDuration) {
NSLog(@"MP4Writer - Priming audio");
CMTime trimTime = CMTimeMakeWithSeconds(0.1, 1000000000);
CFDictionaryRef timeDict = CMTimeCopyAsDictionary(trimTime, kCFAllocatorDefault);
CMSetAttachment(audioSample, kCMSampleBufferAttachmentKey_TrimDurationAtStart, timeDict, kCMAttachmentMode_ShouldPropagate);
CFRelease(timeDict);
}
}
- (void) appendAudioSample:(CMSampleBufferRef)audioSample {
if (CMTimeCompare(kCMTimeInvalid, self.firstVideoFrameTime) == 0 ||
CMTimeCompare(self.firstVideoFrameTime, CMSampleBufferGetPresentationTimeStamp(audioSample)) == 1) {
return;
}
if (self.audioWriterInput.readyForMoreMediaData && self.writer.status == AVAssetWriterStatusWriting) {
if (audioSample != nil) {
if (!self.startedSession) {
CMTime pts = CMSampleBufferGetPresentationTimeStamp(audioSample);
[self.writer startSessionAtSourceTime:pts];
self.startedSession = YES;
NSLog(@"MP4Writer: started session in appendAudioSample");
}
if (_firstAudioBuffer) {
_firstAudioBuffer = NO;
[self primeAudio:audioSample];
}
BOOL appended = [self.audioWriterInput appendSampleBuffer:audioSample];
[self logPresentationTime:audioSample logPrefix:@"Audio Sample"];
if (!appended) {
[self logWriterStatus];
}
}
}
else {
NSLog(@"MP4Writer:appendAudioSample - sample not appended; readyForMoreMediaData = %d, status = %ld", self.audioWriterInput.readyForMoreMediaData, (long)self.writer.status);
}
}
- (void) logWriterStatus {
switch (self.writer.status) {
case AVAssetWriterStatusFailed:
NSLog (@"AVAssetWriter status: AVAssetWriterStatusFailed");
NSLog (@"%@", self.writer.error.description);
break;
case AVAssetWriterStatusCancelled:
NSLog (@"AVAssetWriter status: AVAssetWriterStatusCancelled");
break;
case AVAssetWriterStatusUnknown:
NSLog (@"AVAssetWriter status: AVAssetWriterStatusUnknown");
break;
case AVAssetWriterStatusWriting:
NSLog (@"AVAssetWriter status: AVAssetWriterStatusWriting");
break;
case AVAssetWriterStatusCompleted:
NSLog (@"AVAssetWriter status: AVAssetWriterStatusCompleted");
break;
default:
break;
}
}
- (NSURL *) videoFilePath {
NSArray * paths = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
if (paths.count) {
NSURL *url = paths.lastObject;
url = [url URLByAppendingPathComponent:MP4Filename];
if ([[NSFileManager defaultManager] fileExistsAtPath:url.path]) {
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtURL:url error:&error];
}
return url;
}
return nil;
}
@end