1

I have a local video url that I am trying to put an overlay on. It all works properly, but the quality of the video is being drastically reduced upon export.

I have narrowed it down to find that it happens when I set the AVAssetExportSession.videoComposition (which I need to do for the overlay). If I set the export preset quality to Passthrough, then the video doesn't lose quality but the overlays don't appear.

func merge3(url: URL) {
    activityMonitor.startAnimating()

    let firstAsset = AVAsset(url: url)

    // 1 - Create AVMutableComposition object. This object will hold your AVMutableCompositionTrack instances.
    let mixComposition = AVMutableComposition()

    // 2 - Create two video tracks
    guard
      let firstTrack = mixComposition.addMutableTrack(withMediaType: AVMediaType.video,
                                                      preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
      else {
        return
    }
    do {
      try firstTrack.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: firstAsset.duration),
                                     of: firstAsset.tracks(withMediaType: AVMediaType.video)[0],
                                     at: CMTime.zero)
    } catch {
      print("Failed to load first track")
      return
    }

    let s = UIScreen.main.bounds

    let imglogo = UIImage(named: "logo")
    let imglayer = CALayer()
    imglayer.contents = imglogo?.cgImage
    imglayer.frame = CGRect(x: s.width / 2 - 125, y: s.height / 2 - 125
      , width: 25, height: 25)
    imglayer.opacity = 1.0

    let videolayer = CALayer()
    videolayer.frame = CGRect(x: 0, y: 0, width: s.width, height: s.height)

    let parentlayer = CALayer()
    parentlayer.frame = CGRect(x: 0, y: 0, width: s.width, height: s.height)
    parentlayer.addSublayer(videolayer)
    parentlayer.addSublayer(imglayer)

    // 2.1
    let mainInstruction = AVMutableVideoCompositionInstruction()
    mainInstruction.timeRange = CMTimeRangeMake(start: CMTime.zero,
                                                duration: firstAsset.duration)

    let layercomposition = AVMutableVideoComposition()
    layercomposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
    layercomposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videolayer, in: parentlayer)
    layercomposition.renderSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)

    // instruction for watermark
    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: firstAsset.duration)
    _ = mixComposition.tracks(withMediaType: AVMediaType.video)[0] as AVAssetTrack
    let layerinstruction = VideoHelper.videoCompositionInstruction1(firstTrack, asset: firstAsset)
    instruction.layerInstructions = [layerinstruction]
    layercomposition.instructions = [instruction]

    // 4 - Get path
    guard let documentDirectory = FileManager.default.urls(for: .documentDirectory,
                                                           in: .userDomainMask).first else {
                                                            return
    }
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long
    dateFormatter.timeStyle = .short
    let date = dateFormatter.string(from: Date())
    let url = documentDirectory.appendingPathComponent("mergeVideo-\(date).mov")

    // 5 - Create Exporter
    guard let exporter = AVAssetExportSession(asset: mixComposition,
                                              presetName: AVAssetExportPresetHighestQuality) else {
                                                return
    }
    exporter.outputURL = url
    exporter.outputFileType = AVFileType.mov
    exporter.shouldOptimizeForNetworkUse = true
    exporter.videoComposition = layercomposition

    // 6 - Perform the Export
    exporter.exportAsynchronously() {
      DispatchQueue.main.async {
        self.exportDidFinish(exporter)
      }
    }
  }
static func videoCompositionInstruction1(_ track: AVCompositionTrack, asset: AVAsset)
    -> AVMutableVideoCompositionLayerInstruction {
      let instruction = AVMutableVideoCompositionLayerInstruction(assetTrack: track)
      let assetTrack = asset.tracks(withMediaType: .video)[0]

      let transform = assetTrack.preferredTransform
      let assetInfo = orientationFromTransform(transform)

      var scaleToFitRatio = UIScreen.main.bounds.width / assetTrack.naturalSize.width
      if assetInfo.isPortrait { // not hit
        scaleToFitRatio = UIScreen.main.bounds.width / assetTrack.naturalSize.height
        let scaleFactor = CGAffineTransform(scaleX: scaleToFitRatio, y: scaleToFitRatio)
        instruction.setTransform(assetTrack.preferredTransform.concatenating(scaleFactor), at: CMTime.zero)
      } else { // hit
        let scaleFactor = CGAffineTransform(scaleX: scaleToFitRatio, y: scaleToFitRatio)
        var concat = assetTrack.preferredTransform.concatenating(scaleFactor)
          .concatenating(CGAffineTransform(translationX: 0, y: UIScreen.main.bounds.width / 4))
        if assetInfo.orientation == .down { // not hit
          let fixUpsideDown = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
          let windowBounds = UIScreen.main.bounds
          let yFix = assetTrack.naturalSize.height + windowBounds.height
          let centerFix = CGAffineTransform(translationX: assetTrack.naturalSize.width, y: yFix)
          concat = fixUpsideDown.concatenating(centerFix).concatenating(scaleFactor)
        }
        instruction.setTransform(concat, at: CMTime.zero)
      }

      return instruction
  }

func exportDidFinish(_ session: AVAssetExportSession) {
    guard
      session.status == AVAssetExportSession.Status.completed,
      let outputURL = session.outputURL
      else {
        return
    }

    let saveVideoToPhotos = {
      PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputURL)
      }) { saved, error in
        let success = saved && (error == nil)
        let title = success ? "Success" : "Error"
        let message = success ? "Video saved" : "Failed to save video"

        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil))
        self.present(alert, animated: true, completion: nil)
      }
    }

    // Ensure permission to access Photo Library
    if PHPhotoLibrary.authorizationStatus() != .authorized {
      PHPhotoLibrary.requestAuthorization { status in
        if status == .authorized {
          saveVideoToPhotos()
        }
      }
    } else {
      saveVideoToPhotos()
    }
  }
connorvo
  • 761
  • 2
  • 7
  • 21
  • The video quality depends on the current device – Leo Dabus Jul 26 '19 at 01:01
  • @LeoDabus That can't be the problem because the exact same video on the exact same device without adding the overlays remains at its high quality. Adding the overlay reduces the video quality – connorvo Jul 26 '19 at 15:24
  • Are you saying that if you export the same video without adding overlays the quality doesn't change? – Leo Dabus Jul 26 '19 at 15:27
  • @LeoDabus Yup. But it's because if I don't want overlays I don't need to set the export sessions video composition or can set the quality to AVAssetExportPresetPassthrough. If I don't need to set the video composition or can use passthrough preset, the video exports with perfect quality – connorvo Jul 26 '19 at 17:41
  • @connorvo experiencing same isse here, did you find any solution – jpulikkottil Sep 05 '19 at 07:18
  • @jpulikkottil https://stackoverflow.com/questions/57225191/overlaying-image-on-video-reduces-video-resolution/57226730#57226730 – connorvo Sep 05 '19 at 20:34
  • @connorvo I am already doing this (.naturalSize). But still the 24mb video reduced to 13mb. Thanks for your comment. – jpulikkottil Sep 06 '19 at 05:47
  • Have u maybe managed to sort out this problem? – Baki Apr 17 '20 at 10:40

0 Answers0