iosswiftcodecphpickerviewcontroller

iOS PHAsset to check if a video is HEVC or H.264


Any way to retrieve if a video from gallery is H.264 or HEVC by using PHPickerViewController from PHAsset?

Below are the images in H.264 and HEVC from details information.

This image is H2.264.

enter image description here

This image is HEVC.

enter image description here

Anyway to get it or check if it's one of them?


Solution

  • You can use PHImageManager to fetch the video as an AVAsset and inspect its codec information using AVAssetTrack and CMFormatDescription.

    import Photos
    import AVFoundation
    
    func checkVideoCodec(for asset: PHAsset, completion: @escaping (String?) -> Void) {
        guard asset.mediaType == .video else {
            completion(nil)
            return
        }
        
        let options = PHVideoRequestOptions()
        options.version = .original
        options.isNetworkAccessAllowed = true
        
        PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { avAsset, _, _ in
            guard let urlAsset = avAsset as? AVURLAsset else {
                completion(nil)
                return
            }
            
            if let track = urlAsset.tracks(withMediaType: .video).first,
               let formatDescriptions = track.formatDescriptions as? [CMFormatDescription] {
                for formatDescription in formatDescriptions {
                    let codecType = CMFormatDescriptionGetMediaSubType(formatDescription)
                    switch codecType {
                    case kCMVideoCodecType_HEVC:
                        completion("HEVC (H.265)")
                        return
                    case kCMVideoCodecType_H264:
                        completion("H.264")
                        return
                    default:
                        completion("Unknown Codec")
                        return
                    }
                }
            }
            completion(nil)
        }
    }
    

    Of course, you could also create an async/await version of the same function if needed.