-
Notifications
You must be signed in to change notification settings - Fork 49
/
AVUtilities.swift
77 lines (59 loc) · 2.9 KB
/
AVUtilities.swift
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
import UIKit
import AVFoundation
class AVUtilities {
static func reverse(_ original: AVAsset, outputURL: URL, completion: @escaping (AVAsset) -> Void) {
// Initialize the reader
var reader: AVAssetReader! = nil
do {
reader = try AVAssetReader(asset: original)
} catch {
print("could not initialize reader.")
return
}
guard let videoTrack = original.tracks(withMediaType: AVMediaTypeVideo).last else {
print("could not retrieve the video track.")
return
}
let readerOutputSettings: [String: Any] = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)]
let readerOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: readerOutputSettings)
reader.add(readerOutput)
reader.startReading()
// read in samples
var samples: [CMSampleBuffer] = []
while let sample = readerOutput.copyNextSampleBuffer() {
samples.append(sample)
}
// Initialize the writer
let writer: AVAssetWriter
do {
writer = try AVAssetWriter(outputURL: outputURL, fileType: AVFileTypeQuickTimeMovie)
} catch let error {
fatalError(error.localizedDescription)
}
let videoCompositionProps = [AVVideoAverageBitRateKey: videoTrack.estimatedDataRate]
let writerOutputSettings = [
AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: videoTrack.naturalSize.width,
AVVideoHeightKey: videoTrack.naturalSize.height,
AVVideoCompressionPropertiesKey: videoCompositionProps
] as [String : Any]
let writerInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: writerOutputSettings)
writerInput.expectsMediaDataInRealTime = false
writerInput.transform = videoTrack.preferredTransform
let pixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: writerInput, sourcePixelBufferAttributes: nil)
writer.add(writerInput)
writer.startWriting()
writer.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(samples.first!))
for (index, sample) in samples.enumerated() {
let presentationTime = CMSampleBufferGetPresentationTimeStamp(sample)
let imageBufferRef = CMSampleBufferGetImageBuffer(samples[samples.count - 1 - index])
while !writerInput.isReadyForMoreMediaData {
Thread.sleep(forTimeInterval: 0.1)
}
pixelBufferAdaptor.append(imageBufferRef!, withPresentationTime: presentationTime)
}
writer.finishWriting {
completion(AVAsset(url: outputURL))
}
}
}