Exporting a mirrored video with AVMutableComposition causes resizing issues

心已入冬 提交于 2020-01-04 06:14:56

问题


Everything works as expected if I turn off the mirroring on the front camera. However, if I turn it on, my final exported video has crucial resizing problems:

This is how I currently manage the mirroring for my videos:

       if currentDevice == frontCamera {

            if let connection = output.connections.first {
                if connection.isVideoMirroringSupported {
                    connection.automaticallyAdjustsVideoMirroring = false
                    connection.isVideoMirrored = true //if true, this bug occurs.
                }
            }


        }else {
             //disabling photo mirroring on backCamera
            if let connection = output.connections.first {
                if connection.isVideoMirroringSupported {
                    connection.automaticallyAdjustsVideoMirroring = false
                    connection.isVideoMirrored = false
                }
            }
        }

And this is how I export the video:

  /// Create AVMutableComposition object. This object will hold the AVMutableCompositionTrack instances.

let mainMutableComposition = AVMutableComposition()
        /// Creating an empty video track
        let videoTrack = mainMutableComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)
        let videoAssetTrack = videoAsset.tracks(withMediaType: AVMediaType.video)[0]

        do {
            //Adding the video track
            try videoTrack?.insertTimeRange(CMTimeRange(start: kCMTimeZero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: AVMediaType.video).first!, at: kCMTimeZero)

        } catch {
            completion(false,  nil)
        }

        /// Adding audio if user wants to.
        if withAudio {
            do {
                //Adding the video track
                let audio = videoAsset.tracks(withMediaType: AVMediaType.audio).first
                if audio != nil {
                    let audioTrack = mainMutableComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)
                    try audioTrack?.insertTimeRange(CMTimeRange(start: kCMTimeZero, duration: videoAsset.duration), of: audio!, at: kCMTimeZero)

                }

            } catch {
                completion(false,  nil)
            }

        }

        // * MARK - Composition is ready ----------

        // Create AVMutableVideoCompositionInstruction
        let compositionInstructions = AVMutableVideoCompositionInstruction()
        compositionInstructions.timeRange = CMTimeRange(start: kCMTimeZero, duration: videoAsset.duration)

        // Create an AvmutableVideoCompositionLayerInstruction
        let videoLayerInstruction = AVMutableVideoCompositionLayerInstruction.init(assetTrack: videoTrack!)
        videoLayerInstruction.setTransform(videoAssetTrack.preferredTransform, at: kCMTimeZero)
        compositionInstructions.layerInstructions = [videoLayerInstruction]

        //Add instructions
        let videoComposition = AVMutableVideoComposition()

        let naturalSize : CGSize = videoAssetTrack.naturalSize

        ///Rendering image into video
        let renderWidth = naturalSize.width
        let renderHeight = naturalSize.height

        //Assigning instructions and rendering size
        videoComposition.renderSize = CGSize(width: renderWidth, height: renderHeight)
        videoComposition.instructions = [compositionInstructions]
        videoComposition.frameDuration = CMTime(value: 1, timescale: Int32((videoTrack?.nominalFrameRate)!))

        //Applying image to instruction
        self.applyVideoImage(to: videoComposition, withSize: naturalSize, image: image)

        // Getting the output path
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
        let outputPath = documentsURL?.appendingPathComponent("lastEditedVideo.mp4")
        if FileManager.default.fileExists(atPath: (outputPath?.path)!) {
            do {
                try FileManager.default.removeItem(atPath: (outputPath?.path)!)
            }
            catch {
                completion(false, nil)
            }
        }



        // Create exporter
        let exporter = NextLevelSessionExporter(withAsset: mainMutableComposition)
        exporter.outputURL = outputPath
        exporter.outputFileType = AVFileType.mp4
        exporter.videoComposition = videoComposition

        let compressionDict: [String: Any] = [
            AVVideoAverageBitRateKey: NSNumber(integerLiteral: 2300000),
            AVVideoProfileLevelKey: AVVideoProfileLevelH264BaselineAutoLevel as String
            ]

        exporter.videoOutputConfiguration = [
            AVVideoCodecKey: AVVideoCodecType.h264,
            AVVideoWidthKey: NSNumber(integerLiteral: Int(naturalSize.width)),
            AVVideoHeightKey: NSNumber(integerLiteral: Int(naturalSize.height)),
            AVVideoCompressionPropertiesKey: compressionDict
        ]

        exporter.audioOutputConfiguration = [
            AVFormatIDKey: kAudioFormatMPEG4AAC,
            AVEncoderBitRateKey: NSNumber(integerLiteral: 128000),
            AVNumberOfChannelsKey: NSNumber(integerLiteral: 2),
            AVSampleRateKey: NSNumber(value: Float(44100))
        ]

        completion(true, exporter)
    }

I'm using the NextLevelSessionExporter to export the video. It doesn't matter if I use the default exporter or not, the resizing problems still occur.


回答1:


There is an active bug that prevents you from exporting mirrored videos correctly. You need a few workarounds:

  1. Turn off the mirroring on the movieOutputFile
  2. Manually flip the video horizontally when needed:

    if needsMirroring == true {
    
        var transform:CGAffineTransform = CGAffineTransform(scaleX: -1.0, y: 1.0)
        transform = transform.translatedBy(x: -naturalSize.width, y: 0.0)
        transform = transform.rotated(by: CGFloat(Double.pi/2))
        transform = transform.translatedBy(x: 0.0, y: -naturalSize.width)
        videoTransform = transform
    }
    

It took me days to figure this out, hope it helps.



来源:https://stackoverflow.com/questions/50783192/exporting-a-mirrored-video-with-avmutablecomposition-causes-resizing-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!