VLCMediaThumbnailerCache.swift 5.03 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*****************************************************************************
 * VLCMediaThumbnailerCache.swift
 * VLC for iOS
 *****************************************************************************
 * Copyright (c) 2019 VideoLAN. All rights reserved.
 * $Id$
 *
 * Authors: Pierre Sagaspe <pierre.sagaspe # me.com>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/

import UIKit

@objc class VLCMediaThumbnailerCache: NSObject, VLCMediaThumbnailerDelegate {

    @objc func getVideoThumbnail(_ videoURL: NSString) {
        if getThumbnailURL(videoURL) != nil {
            return
        }

        let media = VLCMedia(url: URL(fileURLWithPath: videoURL.removingPercentEncoding!))

        let thumbnailer = VLCMediaThumbnailer(media: media, andDelegate: self)

        let thumbSize = CGSize(width: 800, height: 600)
        thumbnailer?.thumbnailWidth = thumbSize.width
        thumbnailer?.thumbnailHeight = thumbSize.height

        thumbnailer?.fetchThumbnail()
    }

    // MARK: - VLCMediaThumbnailer data source
    func mediaThumbnailer(_ mediaThumbnailer: VLCMediaThumbnailer!, didFinishThumbnail thumbnail: CGImage!) {
35
        if thumbnail != nil {
36
            let thumbnailImage: UIImage? = UIImage.init(cgImage: thumbnail)
37
            if thumbnailImage != nil {
38 39 40 41 42 43 44
                saveThumbnail(thumbnailImage!, mediaURL: mediaThumbnailer.media.url)
                NotificationCenter.default.post(name: Notification.Name("thumbnailIComplete"), object: nil)
            }
        }
    }

    func mediaThumbnailerDidTimeOut(_ mediaThumbnailer: VLCMediaThumbnailer!) {
45
        print("Time out : \(mediaThumbnailer.media.url)")
46 47 48 49 50 51 52 53 54 55 56
    }

    // MARK: - 
    private func getThumbnailDirectory() -> NSString {
        let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] as NSString
        let thumbnailDirectory = paths.appendingPathComponent("thumbnail")
        return thumbnailDirectory.removingPercentEncoding! as NSString
    }

    @objc func getThumbnailURL(_ mediaPath: NSString) -> URL? {
        let thumbnailDir = getThumbnailDirectory()
57
        let thumbnailPath = String(format: "%@/%@.%@", thumbnailDir, (mediaPath.lastPathComponent as NSString).deletingPathExtension.removingPercentEncoding!, "png")
58 59 60 61 62

        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: thumbnailPath) {
            return URL.init(fileURLWithPath: thumbnailPath)
        }
63
        return nil
64 65 66 67 68 69
    }

    @objc func removeThumbnail(_ mediaPath: NSString? = nil) {
        var thumbnailPath = getThumbnailDirectory()

        if mediaPath != nil {
70
            thumbnailPath = NSString(format: "%@/%@.%@", thumbnailPath, (mediaPath!.lastPathComponent as NSString ).deletingPathExtension.removingPercentEncoding!, "png")
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
        }

        let fileManager = FileManager.default
        var isDir = ObjCBool(false)
        if fileManager.fileExists(atPath: thumbnailPath as String, isDirectory: &isDir) {
            do {
                try fileManager.removeItem(atPath: thumbnailPath as String)
                //print("removed : \(String(describing: thumbnailPath))")
            }
            catch let error as NSError {
                print("error remove : \(error)")
            }
        }
    }

    func saveThumbnail(_ thumbnail: UIImage, mediaURL: URL) {
        let imageData = thumbnail.pngData()
        
        let pngSize: Int = imageData?.count ?? 0
        if pngSize > getFreeDiskSpace() ?? 0 {
            return
        }

        let thumbnailDir = getThumbnailDirectory()
95
        let thumbnailPath = NSString(format: "%@/%@.%@", thumbnailDir, ((mediaURL.relativePath.removingPercentEncoding! as NSString).lastPathComponent as NSString).deletingPathExtension, "png")
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

        let fileManager = FileManager.default
        if !fileManager.fileExists(atPath: thumbnailDir as String) {
            do {
                try fileManager.createDirectory(atPath: thumbnailDir as String, withIntermediateDirectories: true, attributes: nil)
            }
            catch let error as NSError {
                print("error creating directory: \(error)")
            }
        }
        if !fileManager.fileExists(atPath: thumbnailPath as String) {
            do {
                try imageData?.write(to: URL(fileURLWithPath: thumbnailPath.standardizingPath, relativeTo: nil))
            } catch let error as NSError {
                print("error writing thumbnail : \(error)")
            }
        }
    }

    func getFreeDiskSpace() -> Int? {
        let fileURL = URL(fileURLWithPath:"/")
        do {
            let values = try fileURL.resourceValues(forKeys: [.volumeAvailableCapacityKey])
            if let capacity = values.volumeAvailableCapacity {
                //print("Available capacity for important usage: \(capacity)")
                return capacity
            } else {
                print("Capacity is unavailable")
            }
        } catch {
            print("Error retrieving capacity")
        }
        return nil
    }

}