                             self.texture = texture.texture
                         }
                         self.context.flush()
-                        let time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
                         self.writeNextFrame(time:time)
                      }
                 })

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        self.dismiss(animated: true, completion: nil)
        if let url = info[UIImagePickerControllerMediaURL] as? URL {
            //print("didFinish", url)
            // https://stackoverflow.com/questions/12500408/can-i-use-avfoundation-to-stream-downloaded-video-frames-into-an-opengl-es-textu/12500409#12500409
            let asset = AVURLAsset(url: url)
            asset.loadValuesAsynchronously(forKeys: ["tracks"]) {
                let status = asset.statusOfValue(forKey: "tracks", error: nil)

    private func processNext() {
        guard let reader = self.reader,
            let output = self.output,
            let writer = self.writer else {
                return
        }
        guard reader.status == .reading,
            let sampleBuffer = output.copyNextSampleBuffer(),
            let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
            print("Process Complete")
            if let url = self.url, let input = self.input {
                input.markAsFinished()
                writer.finishWriting {
                    print("Finish Writing")
                        let sheet = UIActivityViewController(activityItems: [url], applicationActivities: nil)
                        if let popover = sheet.popoverPresentationController {
                            popover.barButtonItem = self.btnCamera
                        }
                        self.present(sheet, animated: true, completion: nil)
                }
            }
            return
        }
        
        let time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
        let width = CVPixelBufferGetWidth(pixelBuffer), height = CVPixelBufferGetHeight(pixelBuffer)
        var metalTextureFromPixelBuffer:CVMetalTexture? = nil
        let status = CVMetalTextureCacheCreateTextureFromImage(nil, self.textureCache, pixelBuffer, nil,
