                             self.texture = texture.texture
                         }
                         self.context.flush()
-                        
-                        if writer.status == .writing {
-                            writer.finishWriting {
-                                self.processNext()
-                            }
-                        } else {
-                            self.processNext()
-                        }
-                    }
+                        self.writeNextFrame()
+                     }
                 })
                 commandBuffer?.commit()
             } catch {

            }
        }
    }
}

extension SampleViewController4 : MTKViewDelegate {

                    self.writer = writer

                    // https://stackoverflow.com/questions/44797728/recording-a-video-filtered-with-cifilter-is-too-slow
                    /*
                    let compressionSettings: [String: Any] = [
                        AVVideoAverageBitRateKey: NSNumber(value: 20000000),
                        AVVideoMaxKeyFrameIntervalKey: NSNumber(value: 1),
                        AVVideoProfileLevelKey: AVVideoProfileLevelH264Baseline41
                    ]
                    */

                    let videoSettings: [String : Any] = [
                        AVVideoCodecKey  : AVVideoCodecH264,
                        //AVVideoCompressionPropertiesKey: compressionSettings,
                        AVVideoWidthKey  : track.naturalSize.width,
                        AVVideoHeightKey : track.naturalSize.height,
                        //AVVideoScalingModeKey:AVVideoScalingModeResizeAspectFill
                    ]
                    let input = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: videoSettings)
                    input.transform = track.preferredTransform
                    
                    let attrs : [String: Any] = [
                        String(kCVPixelBufferPixelFormatTypeKey) : kCVPixelFormatType_32BGRA,
                        String(kCVPixelBufferWidthKey) : track.naturalSize.width,
                        String(kCVPixelBufferHeightKey) : track.naturalSize.height
                    ]
                    let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: attrs)
                    self.adaptor = adaptor
                    
                    writer.add(input)
                    writer.startWriting()
                    writer.startSession(atSourceTime: kCMTimeZero)
                    
