Coder Social home page Coder Social logo

gmod-medialib's Introduction

gmod-medialib

Media library for Garry's Mod.

Setup

  1. Copy dist/medialib.lua into your addon/gamemode
  2. Make sure it is available to clients via AddCSLuaFile
  3. Include it where-ever you need it. See best-practises below:
    • local medialib = include("the/path/to/medialib.lua") if you only use it in one file
    • MyGlobalTable.medialib = include("the/path/to/medialib.lua") if you use it multiple times (you need to refer to medialib as MyGlobalTable.medialib or localize it if you do this)
Note: SoundCloud API

SoundCloud support requires an API key (or 'client id'), which must be assigned to the medialib table manually. Here's an example:

local medialib = include("medialib.lua")
medialib.SOUNDCLOUD_API_KEY = "my-key-here"

Example

-- If existing global reference exists, remove them
if IsValid(CLIP) then CLIP:stop() end

local link = "https://www.youtube.com/watch?v=6IqKEeRS90A"

-- Get the service that this link uses (eg. youtube, twitch, vimeo, webaudio)
local service = medialib.load("media").guessService(link)

-- Create a mediaclip from the link
local mediaclip = service:load(link)

-- Store global reference for debugging purposes
CLIP = mediaclip

-- Play media
mediaclip:play()

-- Draw video
hook.Add("HUDPaint", "DrawVideo", function()
	local w = 500
	local h = w * (9/16)

	mediaclip:draw(0, 0, w, h)

	surface.SetDrawColor(255, 255, 255)
	surface.DrawRect(0, h, w, 25)

	-- Request metadata. 'meta' will be nil if metadata is still being fetched.
	-- Note: this is a clientside shortcut to Service#query. You should use Service#query on serverside.
	local meta = mediaclip:lookupMetadata()

	local title, duration = tostring(meta and meta.title),
							(meta and meta.duration) or 0

	draw.SimpleText(title, "DermaDefaultBold", 5, h+3, Color(0, 0, 0))

	local timeStr = string.format("%.1f / %.1f", mediaclip:getTime(), duration)
	draw.SimpleText(timeStr, "DermaDefaultBold", w - 5, h+3, Color(0, 0, 0), TEXT_ALIGN_RIGHT)
end)

See examples/ for more elaborate examples.

Resource usage

  • Server โ‡‹ Client

Medialib provides no means of communication between server and client. This means that to for example synchronize video between clients, you must handle networking the media URL and the media start time yourself.

For this purpose you might find my NetTable library useful, but medialib itself contains no networking code.

  • Client

On clientside medialib uses either HTML Awesomium panels or BASS sound objects for playback.

HTML panels are relatively expensive way to playback videos, but having one or two of them should work fine. BASS sound objects (which are used for webaudio and webradio) are pretty cheap. There should be no problem having many of them playing at the same time if needed.

In a nutshell you should use mp3 or ogg files when possible, as they are way cheaper for media playback, but for things like media players that must accept Youtube links HTML media works fine. If there can be arbitrary amount of player controlled jukeboxes on the map, you might want to add some limitations so eg. more than two cannot play simultaneously.

  • Shared (server and client)

Both server and client have the ability to query for video metadata.

This is not instant, as HTTP queries used for majority of services take their time, but querying for metadata is pretty cheap as long as you don't do it in a Think hook or similar.

API

Method Description Notes
medialib.load("media").guessService(url, [opts]) Returns a Service object based on the URL. Returns nil if there is no service for the URL. Note
Service:load(url, options) Creates a Media object using the URL
Service:query(url, callback) Queries for metadata about video (eg. title and duration)
Media:on(name, listener) Adds an event listener. See below for a list of events
Media:isValid() Returns a boolean indicating whether media is valid Note
Media:getServiceBase() Returns the media service type, which is one of the following: "html", "bass"
Media:getService() Returns the service from which this media was loaded
Media:getUrl() Returns the original url passed to Service:load, from which this media was loaded
Media:lookupMetadata() Returns metadata if it's cached. Otherwise queries service for metadata and returns nil. Note
Media:play() Plays media. A playing event is emitted when media starts playing.
Media:pause() Pause media. A paused event is emitted when media pauses.
Media:stop() Pause media. A stopped event is emitted when media stops.
Media:getState() Returns state of media, which is one of the following: "error", "loading", "buffering", "playing", "paused", "stopped" Note
Media:isPlaying() Returns a boolean indicating whether media is playing. Uses getState().
Media:setVolume(vol) Sets volume. vol must be a float in the range of 0 and 1.
Media:getVolume() Returns the volume (a float in the range of 0 and 1).
Media:setQuality(qual) Sets quality. qual must be one of the following: "low", "medium", "high", "veryhigh" Note
Media:getTime() Returns the elapsed time
Media:seek(time) Seeks to specified time. Note
Media:sync(time, errorMargin) Seeks to given time, if the elapsed time differs from it too much (more than errorMargin) Note
Media:runCommand(fn) Runs a command after media has loaded or immediately if it is already loaded

Events

Media

Event name Parameters Description
playing Called when media starts playing
paused Called when media is paused
buffering Called when media is buffering. A playing event is emitted when buffering stops.
ended { stopped = bool } Called when media ends. stopped is true if ended by call to clip:stop()
destroyed Called when media is destroyed/invalidated. isValid() will return false after this
error errorId errorDesc Called when media fails to play. errorId is short error identifier. errorDesc is a longer string type description.

Hooks

Medialib calls some hooks. You can use Garry's Mod's hook.Add to hook them and modify extend medialib's functionality.

Medialib_ProcessOpts(Media mediaObj, table opts) Called before media is loaded but after it is created with the options passed to Service:load(url, options). You can use this hook to add new methods to the media object or set variables. Maybe even queue some things with Media:runCommand(fn).

Medialib_ExtendQuery(string url, CallbackChainObj cbchain) Can be used to add additional data to queried data. Because data querying requires callbacks and medialib doesn't have promises, it uses really hardcore callback chainer, which can be found from servicebase.lua.

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.