Giter Club home page Giter Club logo

ksplayer's Introduction

Build Status Platform License

KSPlayer

KSPlayer is a powerful media play framework for iOS, tvOS, macOS, xrOS, visionOS, Mac Catalyst, SwiftUI, Apple Silicon M1 .

English | 简体中文

Based On

  • FFmpeg
  • Metal
  • AVAudioEngine

Features

  • iOS, tvOS, macOS, visionOS, Mac Catalyst, Apple Silicon M1, SwiftUI.
  • Multiple audio/video tracks.
  • hardware accelerator.
  • 4k/HDR/HDR10/HDR10+/Dolby Vision
  • show local and online subtitles(shooter/assrt/opensubtitles).
  • text subtitle(srt/vtt/ass)/Closed Captions/image subtitle(dvbsub/dvdsub/pgssub)
  • Picture in Picture
  • Record video
  • De-interlace auto detect
  • Dolby Atmos/Spatial Audio
  • 360° panorama video.
  • libsmbclient protocol

Requirements

  • iOS 13 +, macOS 10.15 +, tvOS 13 +, xrOS 1 +

Demo

cd Demo
pod install
  • Open Demo/Demo.xcworkspace with Xcode.

TestFlight

APPStore

TestFlight

License

KSPlayer defaults to the GPL license (requires open-sourcing your own project code), and we hope everyone will consciously respect the licensing agreement of the KSPlayer project. Additionally, there is a paid version that adopts the LGPL license (contact us).

If due to commercial reasons, you prefer not to adhere to the GPL license or the LGPL license, you can contact us. Through our authorization, you can obtain a more flexible licensing agreement.

Quick Start

CocoaPods

Make sure to use the latest version cocoapods 1.10.1+, which can be installed using the command brew install cocoapods

target 'ProjectName' do
    use_frameworks!
    pod 'KSPlayer',:git => 'https://github.com/kingslay/KSPlayer.git', :branch => 'main'
    pod 'DisplayCriteria',:git => 'https://github.com/kingslay/KSPlayer.git', :branch => 'main'
    pod 'FFmpegKit',:git => 'https://github.com/kingslay/FFmpegKit.git', :branch => 'main'
    pod 'Libass',:git => 'https://github.com/kingslay/FFmpegKit.git', :branch => 'main'
end

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/kingslay/KSPlayer.git", .branch("main"))
]

Usage

initialize

KSOptions.secondPlayerType = KSMEPlayer.self
playerView = IOSVideoPlayerView()
view.addSubview(playerView)
playerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    playerView.topAnchor.constraint(equalTo: view.readableContentGuide.topAnchor),
    playerView.leftAnchor.constraint(equalTo: view.leftAnchor),
    playerView.rightAnchor.constraint(equalTo: view.rightAnchor),
    playerView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
playerView.backBlock = { [unowned self] in
    if UIApplication.shared.statusBarOrientation.isLandscape {
        self.playerView.updateUI(isLandscape: false)
    } else {
        self.navigationController?.popViewController(animated: true)
    }
}

Setting up a regular video

playerView.set(url:URL(string: "http://baobab.wdjcdn.com/14525705791193.mp4")!)
playerView.set(resource: KSPlayerResource(url: url, name: name!, cover: URL(string: "http://img.wdjimg.com/image/video/447f973848167ee5e44b67c8d4df9839_0_0.jpeg"), subtitleURL: URL(string: "http://example.ksplay.subtitle")))

Multi-definition, with cover video

let res0 = KSPlayerResourceDefinition(url: URL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!,
                                      definition: "高清")
let res1 = KSPlayerResourceDefinition(url: URL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!,
                                      definition: "标清")
   
let asset = KSPlayerResource(name: "Big Buck Bunny",
                             definitions: [res0, res1],
                             cover: URL(string: "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Big_buck_bunny_poster_big.jpg/848px-Big_buck_bunny_poster_big.jpg"))
playerView.set(resource: asset)

Setting up an HTTP header

let options = KSOptions()
options.appendHeader(["Referer":"https:www.xxx.com"])
let definition = KSPlayerResourceDefinition(url: URL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!,
                                            definition: "高清",
                                            options: options)
let asset = KSPlayerResource(name: "Video Name",
                             definitions: [definition])
playerView.set(resource: asset)

Listening status change

// Listen to play time change
playerView.playTimeDidChange = { (currentTime: TimeInterval, totalTime: TimeInterval) in
    print("playTimeDidChange currentTime: \(currentTime) totalTime: \(totalTime)")
}

// Delegates
public protocol PlayerControllerDelegate: class {
    func playerController(state: KSPlayerState)
    func playerController(currentTime: TimeInterval, totalTime: TimeInterval)
    func playerController(finish error: Error?)
    func playerController(maskShow: Bool)
    func playerController(action: PlayerButtonType)
    // `bufferedCount: 0` indicates first time loading
    func playerController(bufferedCount: Int, consumeTime: TimeInterval)
}

Advanced Usage

  • Inherits PlayerView's custom play logic and UI.

    class CustomVideoPlayerView: IOSVideoPlayerView {
        override func updateUI(isLandscape: Bool) {
            super.updateUI(isLandscape: isLandscape)
            toolBar.playbackRateButton.isHidden = true
        }
    
        override func onButtonPressed(type: PlayerButtonType, button: UIButton) {
            if type == .landscape {
                // Your own button press behaviour here
            } else {
                super.onButtonPressed(type: type, button: button)
            }
        }
    }
  • Selecting Tracks

       override open func player(layer: KSPlayerLayer, state: KSPlayerState) {
            super.player(layer: layer, state: state)
            if state == .readyToPlay, let player = layer.player {
                let tracks = player.tracks(mediaType: .audio)
                let track = tracks[1]
                /// the name of the track
                let name = track.name
                /// the language of the track
                let language = track.language
                /// selecting the one
                player.select(track: track)
            }
       }
  • Set the properties in KSOptions

    open class KSOptions {
      /// 最低缓存视频时间
      @Published
      public var preferredForwardBufferDuration = KSOptions.preferredForwardBufferDuration
      /// 最大缓存视频时间
      public var maxBufferDuration = KSOptions.maxBufferDuration
      /// 是否开启秒开
      public var isSecondOpen = KSOptions.isSecondOpen
      /// 开启精确seek
      public var isAccurateSeek = KSOptions.isAccurateSeek
      /// Applies to short videos only
      public var isLoopPlay = KSOptions.isLoopPlay
      /// 是否自动播放,默认false
      public var isAutoPlay = KSOptions.isAutoPlay
      /// seek完是否自动播放
      public var isSeekedAutoPlay = KSOptions.isSeekedAutoPlay
      /*
       AVSEEK_FLAG_BACKWARD: 1
       AVSEEK_FLAG_BYTE: 2
       AVSEEK_FLAG_ANY: 4
       AVSEEK_FLAG_FRAME: 8
       */
      public var seekFlags = Int32(0)
      // ffmpeg only cache http
      public var cache = false
      public var outputURL: URL?
      public var display = DisplayEnum.plane
      public var avOptions = [String: Any]()
      public var formatContextOptions = [String: Any]()
      public var decoderOptions = [String: Any]()
      public var probesize: Int64?
      public var maxAnalyzeDuration: Int64?
      public var lowres = UInt8(0)
      public var startPlayTime: TimeInterval = 0
      public var startPlayRate: Float = 1.0
      public var registerRemoteControll: Bool = true // 默认支持来自系统控制中心的控制
      public var referer: String?
      public var userAgent: String?
        // audio
      public var audioFilters = [String]()
      public var syncDecodeAudio = false
      // sutile
      public var autoSelectEmbedSubtitle = true
      public var subtitleDisable = false
      public var isSeekImageSubtitle = false
      // video
      public var videoDelay = 0.0 // s
      public var autoDeInterlace = false
      public var autoRotate = true
      public var destinationDynamicRange: DynamicRange?
      public var videoAdaptable = true
      public var videoFilters = [String]()
      public var syncDecodeVideo = false
      public var hardwareDecode = KSOptions.hardwareDecode
      public var asynchronousDecompression = true
      public var videoDisable = false
      public var canStartPictureInPictureAutomaticallyFromInline = true
    }

Effect

gif

Developments and Tests

Any contributing and pull requests are warmly welcome. However, before you plan to implement some features or try to fix an uncertain issue, it is recommended to open a discussion first. It would be appreciated if your pull requests could build and with all tests green. :)

Backers & Sponsors

Open-source projects cannot live long without your help. If you find KSPlayer to be useful, please consider supporting this project by becoming a sponsor.

Become a sponsor through GitHub Sponsors. ❤️

Your user icon or company logo shows up this with a link to your home page.

UnknownCoder807 skrew
Kimentanm nakiostudio andrefmsilva CodingByJerez byMohamedali romaingyh FantasyKingdom

Thanks to nightfall708 for sponsoring a mac mini

Thanks to cdguy UnknownCoder807 skrew and LillyPlayer community for sponsoring a LG S95QR Sound Bar

Thanks to skrew and LillyPlayer community for sponsoring a 2022 Apple TV 4K

Communication

If you have a business cooperation project or want to initiate a paid consultation, you can contact me via email

1

ksplayer's People

Contributors

birdmichael avatar faichou avatar fandongtongxue avatar fantasykingdom avatar ianmagallan avatar kimentanm avatar kingslay avatar littleturnip avatar loveq369 avatar matteogobbi avatar nakiostudio avatar nazar-41 avatar nicknull avatar strangeliu avatar tmm1 avatar weitieda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ksplayer's Issues

MKV media playing with subtitles automatically

When I select an MKV file which has internal subtitles, the subtitles are automatically displayed

I have selected the media using both :

        let res0 = KSPlayerResourceDefinition(url: mediaURL, definition: "HD")
        let asset = KSPlayerResource(name: "Test Video", definitions: [res0], cover: coverImageURL)
        playerView.set(resource: asset)

and

playerView.set(resource: KSPlayerResource(url: mediaURL, name: "Test Video", cover: coverImageURL, subtitleURL: nil))

and in both instances, the internal subtitles are displayed by default. I would like there to be no subtitles displayed by default.

thanks.

KSPlayer_vide (2): EXC_BAD_ACCESS (code=1, address=0x8)

av_buffer_unref(&deviceCtx)
var framesCtx = av_hwframe_ctx_alloc(deviceCtx)
if let framesCtx = framesCtx {

KSPlayer_vide (2): EXC_BAD_ACCESS (code=1, address=0x8)

ffmpeg:4.2.2

你好,这个需要做什么调整,才能兼容FFmpeg4.2.2

Internal Subtitles

Some media, like movies and live tv have internal subtitles. How do I access these please?

How to change aspect ratio ?

Is there an option to change the aspect ratio of a playing video?

If so, can you please give an example of how to do it?

Feature Request-Drop down menu in player

Hi I have a feature request if you can add traditional drop down menu we see in every player in tvOS. I am attaching picture. Thats the easyway to handle meta data of video. plus any extra feature you wanna add like selecting audio, subtitle or video tracks.
IMG_2443
IMG_2444
IMG_2445

video error: "Error splitting the input into NAL units."

Hi Kingslay,

After upgrading to latest develop, I'm getting below error very often when playing bilibili videos:

KSPlayer: MEPlayerItem.swift:88 init(url:options:) | Invalid NAL unit size (2389 > 1387).
KSPlayer: MEPlayerItem.swift:88 init(url:options:) | Error splitting the input into NAL units.
KSPlayerTime 211.91648526077097 of 4079.0
KSPlayerTime 4079.0 of 4079.0

when this error happens, video will stop playing.
this issue was not there back in Apr, when I first tried the code. do you have any idea what could be the root cause and how to solve it? any info would be helpful, thanks !

sample video: https://www.bilibili.com/video/BV1Wb411S7eE?p=6

Not getting resolution of video

print("Size = (String(describing: playerView.playerLayer.player?.naturalSize))")

this gives me

Size = Optional((0.0, 0.0))

I am not getting resolution can you help please @kingslay ?

player issue

Connection 23: unable to determine interface type without an established connection
AudioObjectRemovePropertyListener: no object with given ID 0

AudioObjectRemovePropertyListener: no object with given ID 0
Connection 23: unable to determine fallback status without a connection

AudioObjectRemovePropertyListener: no object with given ID 0
Task .<162> HTTP load failed, 0/0 bytes (error code: -999 [1:89])

Task <7F681D06-7F59-48E9-ADD7-C338698E9A1B>.<869> HTTP load failed, 0/0 bytes (error code: -999
AudioObjectRemovePropertyListener: no object with given ID 0

constantly receiving it doesnt matter video is playing or not.

What is the issue?

initial overlay display when video starts playing

I have managed to implement ksplayer into a project of mine, but find whenever a video starts to play there is an overlay displayed at the bottom of the screen. It is a progress bar and there is some chinese(?) language text at the bottom right. It does disappear after a few seconds.

Is it possible to disable this overlay from appearing?

4:3 16:9 Aspect Ratio

Is it possible to change the actual video aspect ratio?

If a video is in 4:3 format, I would like the option to stretch it to 16:9 (for example) - removing/reducing the black bars down the left and right sides.

I know about contentMode = .scaleAspectRatio etc but that doesn't do what I expected.

is this possible on KSPlayer ? and if so, how please?

KSAVPlayer always shutdown

image

Avplayer seems to not work anymore only KSMEPlayer is working, I want to use AVplayer because I want use the airplay functionality

I will send you the iptv link like this you can test.

Thank you

Orientation Issue

How to make it work in full screen on iphone it just changes the orientation of whole app.
i dont want to change orientation of app i want to run it in full screen.

Headers

Not able to set player headers
Still get KSplayer even after changing

如何同时加载视频和音轨

{
    "dash": {
        "video":["http://upos-hz-mirrorks3u.acgvideo.com/upgcxcode/18/58/77995818/77995818-1-30015.m4s?e=ig8euxZM2rNcNbdlhoNvNC8BqJIzNbfqXBvEuENvNC8aNEVEtEvE9IMvXBvE2ENvNCImNEVEIj0Y2J_aug859r1qXg8xNEVE5XREto8GuFGv2U7SuxI72X6fTr859IB_&deadline=1551113319&gen=playurl&nbs=1&oi=3670888782&os=ks3u&platform=android&trid=925269b941bf4883ac9ec92c6ab5af4e&uipk=5&upsig=82bc845bce9f22b731b062bf83fa000f"],
        "audio":["http://upos-hz-mirrorks3u.acgvideo.com/upgcxcode/18/58/77995818/77995818-1-30280.m4s?e=ig8euxZM2rNcNbdlhoNvNC8BqJIzNbfqXBvEuENvNC8aNEVEtEvE9IMvXBvE2ENvNCImNEVEIj0Y2J_aug859r1qXg8xNEVE5XREto8GuFGv2U7SuxI72X6fTr859IB_&deadline=1551113319&gen=playurl&nbs=1&oi=3670888782&os=ks3u&platform=android&trid=925269b941bf4883ac9ec92c6ab5af4e&uipk=5&upsig=33273eaf403739d9f51304509f55589e"]
    }
}

如上,在线视频的画面和音频分了两个链接,请问大佬这样改如何处理?

Player

I am inheriting iosvideoplayer class when player leave view audio dont stop.

Cannot get the name of subtitle

Hi,

I am trying to get the name of the subtitle but by default you put a default name "内置字幕", how can I get the real name of the subtitle ?

Thank you

Video Stuttering on tvOS

I am trying to play a remote MKV file and find it stutters when playing, like every frame has a twitch.
I am using an Apple TV (tvOS)

I can provide an example url for you via email if you want as I can't post it publicly.

Constant 'player' used before being initialized

I'm trying to get the internal audio tracks using the code in the readme.

        let player: MediaPlayerProtocol
        let tracks = player.tracks(mediaType: .audio)

but I am getting the following error :

Constant 'player' used before being initialized for line 2

This is probably a newbie error (I'm tired), but any help would be appreciated.

如何使用内部字幕呢?

我成功打印出了字幕信息
let tracks = player.tracks(mediaType: .audio)
let track = tracks[1]
let subtitle = player.tracks(mediaType: .subtitle)
print(subtitle)

        player.select(track: track)

如何像使用音轨一样使用他呢?

Please tell me about how to change streams smoothly like you

Hi kingslay.
Thank for awsome player.
I am maintancing and develop hls play function for ijkplayer, but I have stuck in bellow issues.
If you don't mind, please tell me some solution because KSPLayer is awsome player and I want ijkplayer is good for hls too.

  1. With m3u8 contains many variants like: 240p, 360p, 480p. We have 6 streams (audio & video). With default, 240p (stream 0&1) will played. When I switch to 360P, I using method "ffp_set_stream_selected" to change stream, it changed but has stuck when off old stream and open new stream. There are discontinuous phenomenon in playing HLS stream when changing another bitrate stream.
    In KSPlayer, I don't see this stuck, it is very smooth.
    → Can you told me solution for this?

Thank you.

Apple Tv controls or Button Options

Hi There is no default control options for apple tv.
Can you please guide how i can bring buttons in apple tv player.
Subtitle or Speed, there is no way to select those on apple tv.
(Like selecting quality as a example)

Avplayer

when playing vod using avplayer as a firstplayer it takes time to buffer but i want to play right away.
how i can eliminate that time?

Seek

I want to seek only when player state is paused. how i can implement that?

Changing Subtitle URL when playing

I know how to set a subtitle url when the media is first set to play()

Is it possible to change the subtitle URL once media is playing() ?

I'm implementing my own open subtitles code rather than the builtin code.

Video Is playing but...

Video is playing but player state is paused. Happens while live video and VOD too. Happening in some videos only.

overriding pressedEnded

I am trying to allow keyboard control using the pressesEnded func. It works on vlckit but on KSPlayer the keyboard presses are ignored. I am also using tvOS. Keyboard control is vital for allowing universal remotes to work as they send keypresses.

Here is my code

override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
        for press in presses {
            if (press.type == .select) {
                // Select is pressed
                print("select pressed")
            }  else if (press.type == .downArrow) {
                print("down arrow pressed")
            }
        }
}

How can I make this work please?

你好。请问能否像VLC一样提供tvOS下的基础界面

经过几天的测试,KSPlayer的解码能力非常好,但是在tvOS下,我几乎找不到定制界面的相关文档。

请问能否像VLC一样,做一下tvOS下的基础界面呢?

其中2个操作:
1、遥控器触控板往下滑动 ,显示视频元数据,切换音轨、字幕轨道
2、按触控板可暂停,并显示进度条,可左右滑动更改播放时间,再按触控板确定,从选择的时间开始播放。

这2个在tvOS上属于最基础的功能,请问能否实现呢?

Inheritance Issue

Set first player as a avplayer
inherit iosvideoplayer class

Avplayer audio will never stops even player player is removed from view.

when first player is ksmeplayer there is no issue.

Deinterlacing filters

Is it possible to access deinterlace filters?

VLCKit for example has linear, discard, x, mean, yadif, yadif2x etc

is there an equivalent for KSPlayer please?

Playback Error

When seeking through an MKV multiple times, sometimes the video freezes. the sound is still playing and there is a spinning activity spinner at the centre of the screen. This is the output in the xcode debugger

KSPlayer: KSMEPlayer.swift:259 play() | play KSPlayer.KSMEPlayer
KSPlayer: KSPlayerLayer.swift:100 state | playerStateDidChange - bufferFinished
2020-07-22 17:20:14.405145+0800 [4270:4990322] [CAMetalLayerDrawable texture] should not be called after already presenting this drawable. Get a nextDrawable instead.

then after a short while the app will crash and outputs :

2020-07-22 17:22:43.357929+0800 Snappy IPTV[4270:4990457] Execution of the command buffer was aborted due to an error during execution. Discarded (victim of GPU error/recovery) (IOAF code 5)
2020-07-22 17:22:43.358099+0800 [4270:4990457] Execution of the command buffer was aborted due to an error during execution. Discarded (victim of GPU error/recovery) (IOAF code 5)
KSPlayer: KSMEPlayer.swift:264 pause() | pause KSPlayer.KSMEPlayer
KSPlayer: KSPlayerLayer.swift:100 state | playerStateDidChange - paused

This happens regardless of the MKV being viewed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.