'Incorrect Video Time using mpeg4AppleHLS swift
I am creating MPEG-2 video files using mpeg4applehls profile type in avassetwriter, the videos duration or start time are wrong. I create 5-second video segment and write it to a file to upload on the server later. The data return from didoutputsegment delegate returns two types, one is the initialization segment and one is separable segment. I concatenate the initialization with seprable segment and write it to a file, the video works fine but the timestamps are wrong.
Code to create avassetwriter:
videoWriter = AVAssetWriter(contentType: UTType(AVFileType.mp4.rawValue)!)
videoWriter?.outputFileTypeProfile = .mpeg4AppleHLS
videoWriter?.preferredOutputSegmentInterval = CMTime(seconds: 5.0, preferredTimescale: CMTimeScale(1.0))
videoWriter?.delegate = self
code before start recording:
let sessionAtSourceTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
if #available(iOS 14.0, *) {
videoWriter?.initialSegmentStartTime = .zero
} else {
createRecordingFile()
}
videoWriter?.startWriting()
videoWriter?.startSession(atSourceTime: sessionAtSourceTime)
Code to write files:
@available(iOS 14.0, *)
func assetWriter(_ writer: AVAssetWriter, didOutputSegmentData segmentData: Data, segmentType: AVAssetSegmentType) {
print("Did output segment Data")
if segmentType == .separable {
guard let initData = initializationSegment else { return }
createRecordingFile()
var data = Data()
data.append(initData)
data.append(segmentData)
try? data.write(to: currentFileLocation!)
} else if segmentType == .initialization {
self.initializationSegment = segmentData
}
}
I have tried setting initialSegmentStartTime to sessionAtSourceTime or setting both initialSegmentStartTime, startSession to .zero but it seems to affect nothing.
The normal file writing with other profiles works fine like producing an mp4 file.
Sample produced file: File This file starts from 28 mins, before it was starting from 20 hours or more.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|