I'm trying to stream frames from ARSession
to Firebase Storage in real-time. There is some preprocessing that is done on frames before they are sent to firebase. The flow of app is as follows.
The frameCount
variable is used used to name the image files in database. I want the images to be named in sequence as they were captured. The files are being uploaded successfully, the problems are:
It is not real-time because
upload()
runs asynchronously and takes some time.The images are not uploaded in a sequence. I want them to be uploaded in same sequence as they are captured. The async part is doing something that is not intended with the
count
variable. From several hours of debugging I found that the same value ofcount
is used multiple times for different frames. Uploading is all over the place. TheframeCount
reaches to 100 but uploading lags at 5-10. Then, when I stop the session, the uploading part continues but in random order. For example, it would upload the file98.jpg
and the next one would be5.jpg
.
var frameCount = 0
func session(_ session: ARSession, didUpdate frame: ARFrame) {
frameCount += 1
queue.async {
process(frame: frame, count: frameCount)
}
}
func process(frame: ARFrame, count: Int) {
// all the processing happens here to get jpg data of the image
var imgData = ...
var fileURL = writeToFile(imageData: imgData, count: count)
upload(fileURL: fileURL, count: count)
}
func writeToFile(imageData: Data, count: Int) -> URL {
jpgFileURL = try getDirectory().appendingPathComponent("\(count).jpg")
try jpgData.write(to: jpgFileURL!)
return jpgFileURL
}
func upload(fileURL: URL, count: Int) {
let imageFileRef = storageRef.child("\(count).jpg")
imageFileRef.putFile(from: fileURL) // this part runs asynchronously
}
I have tried multiple variations of DispatchQueue
, async
-await
keywords, TaskGroup
, etc. but nothing seems to work. At the core, I just want to increment the frameCount
, write data to file, and upload in sequential manner. This pipeline for next frame should stack over execution of previous frame and should wait for it to upload successfully.