Search code examples
iosgpuimage

Can't make GPUImageAlphaBlendFilter overlay static image over movie file


I can't get it working. As a result I alvays have an empty movie. If I replace GPUImageAlphaBlendFilter with something like GPUImagePixellateFilter, video is rendered just fine.

    func convertVideo(source: URL, destination: URL, encodingPreferenses: VideoEncodingParams = .profileMedium,
                   overlayImage: UIImage?, completion: @escaping ExportAsyncBlock = { _, _ in }) {

    let movieFile = GPUImageMovie(url: source)
    movieFile?.runBenchmark = true

    let alphaFilter = GPUImageAlphaBlendFilter()
    alphaFilter.mix = 1.0

    let markerInput = GPUImagePicture(image: ImageUtils.sharedUtils.resizeImage(overlayImage!, newSize: encodingPreferenses.videoSize, scaleFactor: 1.0))

    movieFile?.addTarget(alphaFilter)
    markerInput?.addTarget(alphaFilter)

    let movieWriter = GPUImageMovieWriter(movieURL: destination, size: encodingPreferenses.videoSize)
    alphaFilter.addTarget(movieWriter)

    movieWriter?.shouldPassthroughAudio = true
    movieFile?.audioEncodingTarget = movieWriter

    movieFile?.enableSynchronizedEncoding(using: movieWriter)

    movieWriter?.startRecording()
    movieFile?.startProcessing()

    movieWriter?.completionBlock = {
        print("Ahoy")
        movieFile?.removeAllTargets()
        movieWriter?.finishRecording {
            print("Ahoy")
        }
    }

}

Solution

  • The movie playback / recording process occurs asynchonously. Therefore, it won't be finished by the time your method above completes.

    Your markerInput GPUImagePicture instance is allocated within that method, and no strong references are provided to it outside of that method. therefore, ARC will deallocate this picture upon exiting this method and will tear down its input into the processing chain. Your movie recording going on after this method has finished will be garbled.

    An easy solution is to create an instance variable for markerInput in the class that owns this method, so that it will live beyond the method itself.