youtube

package module
v3.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 14, 2023 License: MIT Imports: 23 Imported by: 0

README

Download Youtube Video in Golang

GitHub license Go Reference Build Status Coverage

This package is a Youtube video download package, for more detail refer https://github.com/ytdl-org/youtube-dl for more download options.

This tool is meant to be used to download CC0 licenced content, we do not support nor recommend using it for illegal activities.

Overview

Installation

Install via go get

Please ensure you have installed Go 1.21 or later.

go get github.com/kkdai/youtube/v2
From source code
git clone https://github.com/kkdai/youtube.git
cd youtube
go run ./cmd/youtubedr
Mac
brew install youtubedr
in Termux
pkg install youtubedr
You can also find this package in

Usage

Use the binary directly

It's really simple to use, just get the video id from youtube url - ex: https://www.youtube.com/watch?v=rFejpH_tAHM, the video id is rFejpH_tAHM

$ youtubedr download QAGDGja7kbs
$ youtubedr download https://www.youtube.com/watch?v=rFejpH_tAHM
Use this package in your golang program

Please check out the example_test.go for example code.

Example:

  • Get information of dotGo-2015-rob-pike video for downloading

    go get github.com/kkdai/youtube/v2/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated

    youtubedr info https://www.youtube.com/watch?v=rFejpH_tAHM
    
    Title: dotGo 2015 - Rob Pike - Simplicity is Complicated
    Author: dotconferences
    -----available streams-----
    itag:  18 , quality: medium , type: video/mp4; codecs="avc1.42001E, mp4a.40.2"
    itag:  22 , quality:  hd720 , type: video/mp4; codecs="avc1.64001F, mp4a.40.2"
    itag: 137 , quality: hd1080 , type: video/mp4; codecs="avc1.640028"
    itag: 248 , quality: hd1080 , type: video/webm; codecs="vp9"
    ........
    
  • Download dotGo-2015-rob-pike-video

    go get github.com/kkdai/youtube/v2/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated

    youtubedr download https://www.youtube.com/watch?v=rFejpH_tAHM
    
  • Download video to specific folder and name

    go get github.com/kkdai/youtube/v2/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated to current directory and name the file to simplicity-is-complicated.mp4

    youtubedr download -d ./ -o simplicity-is-complicated.mp4 https://www.youtube.com/watch?v=rFejpH_tAHM
    
  • Download video with specific quality

    go get github.com/kkdai/youtube/v2/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated with specific quality

    youtubedr download -q medium https://www.youtube.com/watch?v=rFejpH_tAHM
    
    Special case by quality hd1080:

    Installation of ffmpeg is necessary for hd1080

    ffmpeg   //check ffmpeg is installed, if not please download ffmpeg and set to your PATH.
    youtubedr download -q hd1080 https://www.youtube.com/watch?v=rFejpH_tAHM
    
  • Download video with specific itag

    go get github.com/kkdai/youtube/v2/youtubedr

    Download video from dotGo 2015 - Rob Pike - Simplicity is Complicated

    youtubedr download -q 18 https://www.youtube.com/watch?v=rFejpH_tAHM
    

How it works

  • Parse the video ID you input in URL
    • ex: https://www.youtube.com/watch?v=rFejpH_tAHM, the video id is rFejpH_tAHM
  • Get video information via video id.
    • Use URL: http://youtube.com/get_video_info?video_id=
  • Parse and decode video information.
    • Download URL in "url="
    • title in "title="
  • Download video from URL
    • Need the string combination of "url"

Inspired

Project52

It is one of my project 52.

License

This package is licensed under MIT license. See LICENSE for details.

Documentation

Overview

Package youtube implement youtube download package in go.

Index

Examples

Constants

View Source
const (
	Size1Kb  = 1024
	Size1Mb  = Size1Kb * 1024
	Size10Mb = Size1Mb * 10
)
View Source
const (
	ErrCipherNotFound             = constError("cipher not found")
	ErrSignatureTimestampNotFound = constError("signature timestamp not found")
	ErrInvalidCharactersInVideoID = constError("invalid characters in video id")
	ErrVideoIDMinLength           = constError("the video id must be at least 10 characters long")
	ErrReadOnClosedResBody        = constError("http: read on closed response body")
	ErrNotPlayableInEmbed         = constError("embedding of this video has been disabled")
	ErrLoginRequired              = constError("login required to confirm your age")
	ErrVideoPrivate               = constError("user restricted access to this video")
	ErrInvalidPlaylist            = constError("no playlist detected or invalid playlist ID")
)

Variables

View Source
var (
	// WebClient, better to use Android client but go ahead.
	WebClient = clientInfo{
				// contains filtered or unexported fields
	}

	// AndroidClient, download go brrrrrr.
	AndroidClient = clientInfo{
					// contains filtered or unexported fields
	}

	// EmbeddedClient, not really tested.
	EmbeddedClient = clientInfo{
					// contains filtered or unexported fields
	}
)
View Source
var DefaultClient = AndroidClient

DefaultClient type to use. No reason to change but you could if you wanted to.

View Source
var (
	ErrNoFormat = errors.New("no video format provided")
)
View Source
var (
	ErrTranscriptDisabled = errors.New("transcript is disabled on this video")
)
View Source
var Logger = getLogger(os.Getenv("LOGLEVEL"))

The global logger for all Client instances

Functions

func ExtractVideoID

func ExtractVideoID(videoID string) (string, error)

ExtractVideoID extracts the videoID from the given string

func SetLogLevel

func SetLogLevel(value string)

Types

type CaptionTrack

type CaptionTrack struct {
	BaseURL string `json:"baseUrl"`
	Name    struct {
		SimpleText string `json:"simpleText"`
	} `json:"name"`
	VssID          string `json:"vssId"`
	LanguageCode   string `json:"languageCode"`
	Kind           string `json:"kind,omitempty"`
	IsTranslatable bool   `json:"isTranslatable"`
}

type Client

type Client struct {
	// HTTPClient can be used to set a custom HTTP client.
	// If not set, http.DefaultClient will be used
	HTTPClient *http.Client

	// MaxRoutines to use when downloading a video.
	MaxRoutines int

	// ChunkSize to use when downloading videos in chunks. Default is Size10Mb.
	ChunkSize int64

	YtApiv3Key string
	// contains filtered or unexported fields
}

Client offers methods to download video metadata and video streams.

Example

ExampleDownload : Example code for how to use this package for download video.

package main

import (
	"io"
	"os"

	youtube "github.com/KarlMul/youtubeGo/v3"
)

func main() {
	videoID := "BaW_jenozKc"
	client := youtube.Client{}

	video, err := client.GetVideo(videoID)
	if err != nil {
		panic(err)
	}

	formats := video.Formats.WithAudioChannels() // only get videos with audio
	stream, _, err := client.GetStream(video, &formats[0])
	if err != nil {
		panic(err)
	}
	defer stream.Close()

	file, err := os.Create("video.mp4")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	_, err = io.Copy(file, stream)
	if err != nil {
		panic(err)
	}
}
Output:

func (*Client) GetPlaylist

func (c *Client) GetPlaylist(url string) (*Playlist, error)

GetPlaylist fetches playlist metadata

func (*Client) GetPlaylistContext

func (c *Client) GetPlaylistContext(ctx context.Context, url string) (*Playlist, error)

GetPlaylistContext fetches playlist metadata, with a context, along with a list of Videos, and some basic information for these videos. Playlist entries cannot be downloaded, as they lack all the required metadata, but can be used to enumerate all IDs, Authors, Titles, etc.

func (*Client) GetStream

func (c *Client) GetStream(video *Video, format *Format) (io.ReadCloser, int64, error)

GetStream returns the stream and the total size for a specific format

Example
video, err := testClient.GetVideo("https://www.youtube.com/watch?v=9_MbW9FK1fA")
if err != nil {
	panic(err)
}

// Typically youtube only provides separate streams for video and audio.
// If you want audio and video combined, take a look a the downloader package.
format := video.Formats.FindByQuality("medium")
reader, _, err := testClient.GetStream(video, format)
if err != nil {
	panic(err)
}

// do something with the reader

reader.Close()
Output:

func (*Client) GetStreamContext

func (c *Client) GetStreamContext(ctx context.Context, video *Video, format *Format) (io.ReadCloser, int64, error)

GetStreamContext returns the stream and the total size for a specific format with a context.

func (*Client) GetStreamURL

func (c *Client) GetStreamURL(video *Video, format *Format) (string, error)

GetStreamURL returns the url for a specific format

func (*Client) GetStreamURLContext

func (c *Client) GetStreamURLContext(ctx context.Context, video *Video, format *Format) (string, error)

GetStreamURLContext returns the url for a specific format with a context

func (*Client) GetTranscript

func (c *Client) GetTranscript(video *Video) (VideoTranscript, error)

GetTranscript fetches the video transcript if available.

Not all videos have transcripts, only relatively new videos. If transcripts are disabled or not available, ErrTranscriptDisabled is returned.

func (*Client) GetTranscriptCtx

func (c *Client) GetTranscriptCtx(ctx context.Context, video *Video) (VideoTranscript, error)

GetTranscriptCtx fetches the video transcript if available.

Not all videos have transcripts, only relatively new videos. If transcripts are disabled or not available, ErrTranscriptDisabled is returned.

func (*Client) GetVideo

func (c *Client) GetVideo(url string) (*Video, error)

GetVideo fetches video metadata

func (*Client) GetVideoContext

func (c *Client) GetVideoContext(ctx context.Context, url string) (*Video, error)

GetVideoContext fetches video metadata with a context

func (*Client) SearchWithQuery

func (c *Client) SearchWithQuery(query string) (QueryResponseData, error)

YtApiv3Key has to bet set when creating a new Client

func (*Client) VideoFromPlaylistEntry

func (c *Client) VideoFromPlaylistEntry(entry *PlaylistEntry) (*Video, error)

func (*Client) VideoFromPlaylistEntryContext

func (c *Client) VideoFromPlaylistEntryContext(ctx context.Context, entry *PlaylistEntry) (*Video, error)

type DecipherOperation

type DecipherOperation func([]byte) []byte

type ErrPlayabiltyStatus

type ErrPlayabiltyStatus struct {
	Status string
	Reason string
}

func (ErrPlayabiltyStatus) Error

func (err ErrPlayabiltyStatus) Error() string

type ErrPlaylistStatus

type ErrPlaylistStatus struct {
	Reason string
}

func (ErrPlaylistStatus) Error

func (err ErrPlaylistStatus) Error() string

type ErrUnexpectedStatusCode

type ErrUnexpectedStatusCode int

ErrUnexpectedStatusCode is returned on unexpected HTTP status codes

func (ErrUnexpectedStatusCode) Error

func (err ErrUnexpectedStatusCode) Error() string

type Format

type Format struct {
	ItagNo           int    `json:"itag"`
	URL              string `json:"url"`
	MimeType         string `json:"mimeType"`
	Quality          string `json:"quality"`
	Cipher           string `json:"signatureCipher"`
	Bitrate          int    `json:"bitrate"`
	FPS              int    `json:"fps"`
	Width            int    `json:"width"`
	Height           int    `json:"height"`
	LastModified     string `json:"lastModified"`
	ContentLength    int64  `json:"contentLength,string"`
	QualityLabel     string `json:"qualityLabel"`
	ProjectionType   string `json:"projectionType"`
	AverageBitrate   int    `json:"averageBitrate"`
	AudioQuality     string `json:"audioQuality"`
	ApproxDurationMs string `json:"approxDurationMs"`
	AudioSampleRate  string `json:"audioSampleRate"`
	AudioChannels    int    `json:"audioChannels"`

	// InitRange is only available for adaptive formats
	InitRange *struct {
		Start string `json:"start"`
		End   string `json:"end"`
	} `json:"initRange"`

	// IndexRange is only available for adaptive formats
	IndexRange *struct {
		Start string `json:"start"`
		End   string `json:"end"`
	} `json:"indexRange"`
}

type FormatList

type FormatList []Format

func (FormatList) AudioChannels

func (list FormatList) AudioChannels(n int) (result FormatList)

AudioChannels returns a new FormatList filtered by the matching AudioChannels

func (FormatList) FindByItag

func (list FormatList) FindByItag(itagNo int) *Format

FindByItag returns the first format matching the itag number

func (FormatList) FindByQuality

func (list FormatList) FindByQuality(quality string) *Format

FindByQuality returns the first format matching Quality or QualityLabel

Examples: tiny, small, medium, large, 720p, hd720, hd1080

func (FormatList) Quality

func (list FormatList) Quality(quality string) (result FormatList)

Quality returns a new FormatList filtered by quality, quality label or itag, but not audio quality

func (FormatList) Sort

func (list FormatList) Sort()

Sort sorts all formats fields

func (FormatList) Type

func (list FormatList) Type(t string) (result FormatList)

Type returns a new FormatList filtered by mime type of video

func (FormatList) WithAudioChannels

func (list FormatList) WithAudioChannels() (result FormatList)

AudioChannels returns a new FormatList filtered by the matching AudioChannels

type Playlist

type Playlist struct {
	ID          string
	Title       string
	Description string
	Author      string
	Videos      []*PlaylistEntry
}
Example

Example usage for playlists: downloading and checking information.

package main

import (
	"fmt"
	"io"
	"os"
	"strings"

	youtube "github.com/KarlMul/youtubeGo/v3"
)

func main() {
	playlistID := "PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP"
	client := youtube.Client{}

	playlist, err := client.GetPlaylist(playlistID)
	if err != nil {
		panic(err)
	}

	/* ----- Enumerating playlist videos ----- */
	header := fmt.Sprintf("Playlist %s by %s", playlist.Title, playlist.Author)
	println(header)
	println(strings.Repeat("=", len(header)) + "\n")

	for k, v := range playlist.Videos {
		fmt.Printf("(%d) %s - '%s'\n", k+1, v.Author, v.Title)
	}

	/* ----- Downloading the 1st video ----- */
	entry := playlist.Videos[0]
	video, err := client.VideoFromPlaylistEntry(entry)
	if err != nil {
		panic(err)
	}
	// Now it's fully loaded.

	fmt.Printf("Downloading %s by '%s'!\n", video.Title, video.Author)

	stream, _, err := client.GetStream(video, &video.Formats[0])
	if err != nil {
		panic(err)
	}

	file, err := os.Create("video.mp4")

	if err != nil {
		panic(err)
	}

	defer file.Close()
	_, err = io.Copy(file, stream)

	if err != nil {
		panic(err)
	}

	println("Downloaded /video.mp4")
}
Output:

type PlaylistEntry

type PlaylistEntry struct {
	ID         string
	Title      string
	Author     string
	Duration   time.Duration
	Thumbnails Thumbnails
}

type QueryResponseData

type QueryResponseData struct {
	Query string
	Items []struct {
		ID struct {
			VideoID string `json:"videoId"`
		} `json:"id"`
		Snippet struct {
			Title        string `json:"title"`
			Description  string `json:"description"`
			ChannelTitle string `json:"channelTitle"`
			Thumbnails   struct {
				Default struct {
					URL string `json:"url"`
				} `json:"default"`
				Medium struct {
					URL string `json:"url"`
				} `json:"medium"`
				High struct {
					URL string `json:"url"`
				} `json:"high"`
			} `json:"thumbnails"`
		} `json:"snippet"`
	} `json:"items"`
}

type Thumbnail

type Thumbnail struct {
	URL    string
	Width  uint
	Height uint
}

type Thumbnails

type Thumbnails []Thumbnail

type TranscriptSegment

type TranscriptSegment struct {
	// Text is the transcipt text.
	Text string `json:"text"`

	// StartMs is the start timestamp in ms.
	StartMs int `json:"offset"`

	// OffsetText e.g. '4:00'.
	OffsetText string `json:"offsetText"`

	// Duration the transcript segment spans in ms.
	Duration int `json:"duration"`
}

TranscriptSegment is a single transcipt segment spanning a few milliseconds.

func (TranscriptSegment) String

func (tr TranscriptSegment) String() string

type Video

type Video struct {
	ID              string
	Title           string
	Description     string
	Author          string
	ChannelID       string
	ChannelHandle   string
	Views           int
	Duration        time.Duration
	PublishDate     time.Time
	Formats         FormatList
	Thumbnails      Thumbnails
	DASHManifestURL string // URI of the DASH manifest file
	HLSManifestURL  string // URI of the HLS manifest file
	CaptionTracks   []CaptionTrack
}

func (*Video) FilterQuality

func (v *Video) FilterQuality(quality string)

FilterQuality reduces the format list to formats matching the quality

func (*Video) SortBitrateAsc

func (v *Video) SortBitrateAsc(i int, j int) bool

func (*Video) SortBitrateDesc

func (v *Video) SortBitrateDesc(i int, j int) bool

type VideoTranscript

type VideoTranscript []TranscriptSegment

func (VideoTranscript) String

func (vt VideoTranscript) String() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL