vidpickr

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: MIT Imports: 14 Imported by: 0

README

vidpickr — Go SDK

Official Go SDK for the VidPickr API. Download YouTube videos with one function call.

package main

import (
    "context"
    "log"
    "os"

    vidpickr "github.com/vidpickr/sdk-go"
)

func main() {
    vp := vidpickr.New(os.Getenv("VIDPICKR_API_KEY"))
    err := vp.Download(context.Background(),
        "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
        vidpickr.Out("video.mp4"),
        vidpickr.Quality(1080),
    )
    if err != nil {
        log.Fatal(err)
    }
}

That's it. The SDK:

  1. Resolves the URL through /api/v1/info
  2. Picks the best 1080p video track and the highest-bitrate audio track
  3. Exchanges the merge token via /api/v1/split_token
  4. Streams both tracks in parallel from /api/v1/stream
  5. Muxes them into one fragmented MP4 with a pure-Go box rewrite
  6. Writes the result to video.mp4 and cleans up temp files

Requirements

  • Go 1.21+
  • A VidPickr Plus subscription ($1/mo) and an API key, minted at vidpickr.com/account/api-keys
  • Zero runtime dependencies as of v0.2 — the mux step runs in pure Go via mp4ff. No ffmpeg, no subprocess, no temp binaries.

Install

go get github.com/vidpickr/sdk-go

CLI binary:

go install github.com/vidpickr/sdk-go/cmd/vidpickr@latest

vidpickr --key vpk_live_... --quality 1080 -o video.mp4 \
    https://www.youtube.com/watch?v=dQw4w9WgXcQ

API

vidpickr.New(apiKey string, opts ...Option) *VidPickr

Construct the high-level SDK. Options:

  • WithBaseURL(url string) — override API host (default: https://api.vidpickr.com/v1)
  • WithHTTPClient(*http.Client) — supply your own HTTP client (custom transport, retries, telemetry, etc.)
(*VidPickr).Download(ctx, url, opts ...DownloadOption) error

Resolve, stream, mux, write to disk. Options:

Option Type / Values Default Description
Out string Output file path. Required.
Quality "best" / "highest" / "lowest" / int "best" Target height in px.
Codec "av1" / "vp9" / "avc" / "hevc" Preferred codec when multiple at the same height.
OnProgress func(Progress) nil Callback fired on phase transitions.
(*VidPickr).Info(ctx, url) (*VideoInfo, error)

Resolve only. Use when you want to inspect formats before deciding.

(*VidPickr).Client() *Client

Returns the low-level HTTP client. Use for custom pipelines (e.g. piping audio bytes directly into a transcription service without writing to disk).

Errors

import vidpickr "github.com/vidpickr/sdk-go"

if err := vp.Download(ctx, url, vidpickr.Out("x.mp4")); err != nil {
    var apiErr *vidpickr.APIError
    if errors.As(err, &apiErr) {
        switch apiErr.Code {
        case "rate_limited":
            log.Printf("retry in %ds", apiErr.RetryAfter)
        case "plus_required":
            log.Fatal("subscribe to Plus first")
        }
    }
    var noFmt *vidpickr.NoFormatError
    if errors.As(err, &noFmt) {
        log.Printf("requested format unavailable: %s", noFmt.Reason)
    }
}

Subtitles

info, _ := vp.Info(ctx, url)
for _, s := range info.Subtitles {
    if s.Code == "en" && !s.IsAuto {
        srt, _ := vp.Client().Subtitle(ctx, s.DownloadToken, "srt")
        os.WriteFile("captions.srt", []byte(srt), 0o644)
        break
    }
}

Roadmap

  • v0.2 (current) — pure-Go MP4 muxer via mp4ff. Zero runtime dependencies, single-binary install. Output is fragmented MP4 with both tracks (plays natively in VLC, QuickTime, every modern browser, and ffmpeg -c copy).
  • v0.3 (planned) — context cancellation propagation through the mux step, optional progressive (non-fragmented) output via flag, and per-segment progress callbacks during the byte stream.

License

MIT

Documentation

Overview

Package vidpickr is the official Go SDK for the VidPickr API.

Quick start:

import "github.com/vidpickr/sdk-go"

vp := vidpickr.New(os.Getenv("VIDPICKR_API_KEY"))
err := vp.Download(ctx, "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    vidpickr.Out("video.mp4"),
    vidpickr.Quality(1080),
)

One call: resolve, split, stream both tracks in parallel, mux locally with a pure-Go MP4 muxer (no ffmpeg dependency), write to disk.

Index

Constants

View Source
const DefaultBaseURL = "https://api.vidpickr.com/v1"

DefaultBaseURL is the production API host. Override via WithBaseURL for self-hosted deployments or local dev.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code       string
	Message    string
	Status     int
	RetryAfter int // seconds; 0 when not provided
}

APIError mirrors the {"error": {"code", "message"}} JSON the API returns on 4xx/5xx. Branch on Code rather than Message for stable behaviour across API versions.

func (*APIError) Error

func (e *APIError) Error() string

type AudioFormat

type AudioFormat struct {
	Ext           string  `json:"ext"`
	ACodec        string  `json:"acodec"`
	Bitrate       int     `json:"bitrate"`
	SizeMB        float64 `json:"size_mb"`
	DownloadToken string  `json:"download_token"`
	Endpoint      string  `json:"endpoint"`
}

AudioFormat is a standalone audio track.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the low-level HTTP client. Most callers use the higher-level VidPickr type, which embeds a Client. Reach for Client directly when you need fine-grained control (custom retry policies, piping bytes into your own pipeline, etc.).

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient constructs a low-level HTTP client.

func (*Client) Info

func (c *Client) Info(ctx context.Context, target string) (*VideoInfo, error)

Info resolves a YouTube URL into the full format list.

func (*Client) OpenStream

func (c *Client) OpenStream(ctx context.Context, token string) (*http.Response, error)

OpenStream returns a response whose body streams the requested track. Caller MUST close res.Body. Use this when piping bytes directly into another consumer; for "stream to file" use StreamToFile.

func (*Client) SplitToken

func (c *Client) SplitToken(ctx context.Context, mergeToken string) (*SplitTokenResult, error)

SplitToken exchanges a merge token (bundled video+audio) for two single-source tokens you can stream separately.

func (*Client) StreamToFile

func (c *Client) StreamToFile(ctx context.Context, token, path string) (int64, error)

StreamToFile downloads a single track to disk. Returns total bytes written and any error.

func (*Client) Subtitle

func (c *Client) Subtitle(ctx context.Context, token, format string) (string, error)

Subtitle fetches a caption track in the requested format (srt|vtt|txt). Returns the track as a string.

type DownloadOption

type DownloadOption func(*downloadConfig)

DownloadOption configures a single Download call.

func Codec

func Codec(name string) DownloadOption

Codec picks a preferred video codec when multiple variants exist at the same height. One of: "av1", "vp9", "avc", "hevc".

func OnProgress

func OnProgress(fn func(Progress)) DownloadOption

OnProgress wires a callback invoked between phases.

func Out

func Out(path string) DownloadOption

Out specifies the output file path. Required.

func Quality

func Quality(q any) DownloadOption

Quality selects the target video height. Accepts:

"best", "highest"  → top available resolution
"lowest"           → smallest available
int (e.g. 1080)    → exact match, fall back to next-lower

type MuxError

type MuxError struct{ Reason string }

MuxError wraps a failure from the local MP4 mux step.

func (*MuxError) Error

func (e *MuxError) Error() string

type NoFormatError

type NoFormatError struct{ Reason string }

NoFormatError is returned when the caller requested a quality / codec combination that doesn't exist in the /info response.

func (*NoFormatError) Error

func (e *NoFormatError) Error() string

type Option

type Option func(*config)

Option tweaks the Client at construction.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL overrides the default API host. Useful for staging, self-hosted deployments, or pointing at a local Go server in dev.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient lets the caller supply a custom *http.Client (custom transport, retries, instrumentation, etc.).

type Progress

type Progress struct {
	Phase      string // "resolving" | "fetching" | "muxing" | "finalizing" | "done"
	VideoBytes int64
	AudioBytes int64
	VideoTotal int64
	AudioTotal int64
}

Progress reports state during a Download call.

type Resolution

type Resolution struct {
	Height        int           `json:"height"`
	QualityLabel  string        `json:"quality_label"`
	SizeMB        float64       `json:"size_mb"`
	IsProgressive bool          `json:"is_progressive"`
	DownloadToken string        `json:"download_token"`
	Endpoint      string        `json:"endpoint"`
	Filename      string        `json:"filename"`
	VideoOnly     []VideoFormat `json:"video_only,omitempty"`
}

Resolution is one available video height with its codec options.

type SplitTokenResult

type SplitTokenResult struct {
	VideoToken string `json:"video_token"`
	AudioToken string `json:"audio_token"`
}

SplitTokenResult is what /v1/split_token returns for a merge token.

type SubtitleTrack

type SubtitleTrack struct {
	Code          string `json:"code"`
	Name          string `json:"name"`
	IsAuto        bool   `json:"is_auto"`
	DownloadToken string `json:"download_token"`
	Filename      string `json:"filename"`
}

SubtitleTrack is one caption track (manual or auto-generated).

type VidPickr

type VidPickr struct {
	// contains filtered or unexported fields
}

VidPickr is the high-level SDK. Construct one, call Download per URL.

func New

func New(apiKey string, opts ...Option) *VidPickr

New constructs a VidPickr backed by a low-level Client. Pass Option values (WithBaseURL, WithHTTPClient) to tune transport behaviour.

func (*VidPickr) Client

func (vp *VidPickr) Client() *Client

Client returns the underlying low-level client for custom pipelines.

func (*VidPickr) Download

func (vp *VidPickr) Download(ctx context.Context, url string, opts ...DownloadOption) error

Download resolves, streams, muxes, and writes to disk in one call. Use the Out / Quality / Codec / Progress functional options to customise behaviour.

func (*VidPickr) Info

func (vp *VidPickr) Info(ctx context.Context, url string) (*VideoInfo, error)

Info resolves a URL without downloading. Useful when you want to inspect formats before deciding.

type VideoFormat

type VideoFormat struct {
	Ext           string  `json:"ext"`
	VCodec        string  `json:"vcodec"`
	SizeMB        float64 `json:"size_mb"`
	DownloadToken string  `json:"download_token"`
	Bitrate       int     `json:"bitrate"`
}

VideoFormat is one codec variant at a given resolution height.

type VideoInfo

type VideoInfo struct {
	Title       string          `json:"title"`
	Thumbnail   string          `json:"thumbnail"`
	Platform    string          `json:"platform"`
	DurationSec int             `json:"duration_sec"`
	Resolutions []Resolution    `json:"resolutions"`
	AudioOnly   []AudioFormat   `json:"audio_only"`
	Subtitles   []SubtitleTrack `json:"subtitles"`
}

VideoInfo is the full /v1/info response shape.

Directories

Path Synopsis
cmd
vidpickr command
vidpickr CLI — wraps the Go SDK as a single-binary command.
vidpickr CLI — wraps the Go SDK as a single-binary command.
examples
basic command
Basic example.
Basic example.
internal
mp4mux
Package mp4mux performs the local "join video.mp4 + audio.m4a into out.mp4" step using a pure-Go MP4 box rewrite.
Package mp4mux performs the local "join video.mp4 + audio.m4a into out.mp4" step using a pure-Go MP4 box rewrite.

Jump to

Keyboard shortcuts

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