media

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: May 3, 2026 License: AGPL-3.0 Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package media provides the Temporal workflow definition for processing media files (movies and TV episodes) using a single parameterised workflow.

Index

Constants

View Source
const (
	ProbeActivityName         = "Probe"
	DetectCropActivityName    = "DetectCrop"
	TranscodeActivityName     = "Transcode"
	NotifyActivityName        = "Notify"
	CleanupActivityName       = "Cleanup"
	NotifyFailureActivityName = "NotifyFailure"
)

Registered activity names. Workflows reference activities by these strings so registration and invocation cannot drift from one another. Each name maps 1:1 to a method on Activities; the operational boundary (idempotency, retry policy, data inputs) is what determines the split, so each activity owns exactly one concern and each concern is invoked under the retry policy that fits it.

View Source
const (
	// DefaultDetectCropTimeout is the default Temporal StartToCloseTimeout for
	// the detectcrop activity, used when MediaWorkflowConfig.DetectCropTimeout
	// is zero.
	DefaultDetectCropTimeout = 30 * time.Minute
	// DefaultTranscodeTimeout is the default Temporal StartToCloseTimeout for
	// the transcode activity, used when MediaWorkflowConfig.TranscodeTimeout is
	// zero.
	DefaultTranscodeTimeout = 4 * time.Hour
)
View Source
const MediaWorkflowName = mediatypes.MediaWorkflowName

MediaWorkflowName is the registered Temporal workflow name. Re-exported from the types package for callers that import workflows/media directly.

Variables

This section is empty.

Functions

func NotifyWorkflowFailure added in v0.0.6

func NotifyWorkflowFailure(ctx context.Context, step, errMsg, workflowName, filePath string, webhookClient *webhook.Client) error

NotifyWorkflowFailure sends a single-step failure notification to webhookClient. step is the failing activity name; errMsg is the underlying error message. workflowName is included in the webhook payload; filePath is the file being processed. Returns nil (no-op) when step is empty.

func RunCleanup added in v0.0.6

func RunCleanup(filePath, watchRoot string, retainEmptyDirs bool) error

RunCleanup deletes the original source file after successful processing and, unless retainEmptyDirs is true, removes any parent directories that become empty as a result, stopping at watchRoot.

func RunDetectCrop added in v0.0.6

func RunDetectCrop(ctx context.Context, filePath string, inputW, inputH, minCropX, minCropY int) (*ffmpeg.CropParams, error)

RunDetectCrop runs the ffmpeg cropdetect filter over filePath and returns the crop region to apply, or nil when no crop is needed.

minCropX and minCropY are the minimum number of pixels that must be trimmed on each horizontal/vertical axis for a crop to be applied. A value of -1 disables the threshold for that axis (any detected crop is accepted). When both are -1 the crop detection step is skipped entirely and ffmpeg.DetectCrop is never called.

inputW and inputH are the pixel dimensions of the source video (from the ProbeOutput). They are used to compute how many pixels would be trimmed on each axis.

func SelectVideoCodec added in v0.0.6

func SelectVideoCodec(videoCodecName, format string) ffmpeg.Codec

SelectVideoCodec returns CodecCopy when the video is already H.264 or H.265 in an MKV container, and CodecH265 otherwise.

func WriteSentinel added in v0.0.6

func WriteSentinel(filePath string) error

WriteSentinel creates a zero-byte hidden sentinel file alongside filePath to mark it as processed, preventing the watcher from re-dispatching it. The sentinel path is .BASENAME.done in the same directory (e.g. /dl/movie.mkv → /dl/.movie.mkv.done). The write is idempotent.

Types

type Activities added in v0.0.6

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

Activities holds the dependencies needed by the activity methods. A single instance is registered with the worker; all activities share its fields.

func NewActivities added in v0.0.6

func NewActivities(cfg MediaWorkflowConfig, radarrClient, sonarrClient medialib.ArrLibrary, webhookClient *webhook.Client) (*Activities, error)

NewActivities constructs an Activities ready for registration. Defaults are applied to cfg.DetectCropTimeout and cfg.TranscodeTimeout when zero.

func (*Activities) Cleanup added in v0.0.6

func (a *Activities) Cleanup(ctx context.Context, input MediaInput) error

Cleanup deletes the source file or writes the .done sentinel. RunCleanup tolerates ErrNotExist so retrying after a partial cleanup is safe; WriteSentinel re-writes the same zero-byte file. Shared between the valid and invalid paths — in the invalid path the source has already been removed by Probe and Cleanup is a near-no-op for the file, but the sentinel branch is still exercised when PreserveSource is set.

func (*Activities) DetectCrop added in v0.0.6

func (a *Activities) DetectCrop(ctx context.Context, input MediaInput, probe ProbeOutput) (DetectCropOutput, error)

DetectCrop is the Temporal activity that wraps RunDetectCrop. It returns a DetectCropOutput with a nil Crop when the cropdetect filter produced no usable crop region.

func (*Activities) MediaWorkflow added in v0.0.6

func (a *Activities) MediaWorkflow(ctx workflow.Context, input MediaInput) (err error)

MediaWorkflow processes one media file end-to-end. The body is straight-line Go: probe, branch on validity, run the per-path activities. A defer block invokes the failure-webhook activity when the workflow returns an error.

Each activity is invoked with the retry policy that fits its idempotency profile: idempotent operations (Notify, Cleanup) use retryableMaxAttempts so transient flakes do not fail the run; everything else (Probe, DetectCrop, Transcode, NotifyFailure) uses defaultMaxAttempts (single attempt) because retrying would either duplicate non-idempotent side effects or repeat expensive work that will not recover.

Per-run application metrics are emitted by the activities themselves through the SDK MetricsHandler. End-to-end workflow latency comes for free from the SDK's temporal_workflow_endtoend_latency_seconds histogram (tagged with workflow_type), so the workflow body does not emit a duration metric.

func (*Activities) Notify added in v0.0.6

func (a *Activities) Notify(ctx context.Context, input MediaInput, transcode TranscodeOutput) error

Notify issues the library import (Sonarr/Radarr scan command). The import is idempotent in practice — re-issuing the same scan for an already-imported file is a no-op — so the workflow retries this activity on transient failures. Pure-data errors (unknown media type, output_remote_path outside the output tree) are returned as non-retryable so Temporal does not burn the retry budget on inputs that cannot recover.

func (*Activities) NotifyFailure added in v0.0.6

func (a *Activities) NotifyFailure(ctx context.Context, input MediaInput, failedStep, failureMsg string) error

NotifyFailure sends the configured failure webhook for a workflow that returned an error. Invoked from the workflow's defer block on any non-nil return; the failed step name comes from temporal.ActivityError.ActivityType() and the message from the wrapped activity error.

func (*Activities) Probe added in v0.0.6

func (a *Activities) Probe(ctx context.Context, input MediaInput) (ProbeOutput, error)

Probe is the Temporal activity that wraps RunProbe. Per-run metrics are emitted inline: source-duration histogram + audio/subtitle gauges for valid media, or the invalid-files counter when the file fails to probe as media.

func (*Activities) Register added in v0.0.6

func (a *Activities) Register(r Registrar)

Register attaches the workflow function and the activities to the given Temporal registrar (a worker.Worker in production, a TestWorkflowEnvironment in tests). The slice literals below are the single source of truth for the (name, function) pairs the worker and tests register.

func (*Activities) Transcode added in v0.0.6

func (a *Activities) Transcode(ctx context.Context, input MediaInput, probe ProbeOutput, cropOut DetectCropOutput) (TranscodeOutput, error)

Transcode is the Temporal activity that wraps RunTranscode. After a successful transcode it emits the per-run file-size and transcode-duration histograms and the artwork-fetch-skipped counter when applicable. When high-cardinality labels are enabled it also looks up per-item metadata from the arr library to attach as tags. The SDK's temporal_activity_execution_latency_seconds also tracks transcode wall-clock, but only with worker-context tags; the application metric carries the media tags (codec, container, hardware_accelerated, crop_applied, …) that make runtime correlatable with source size, source duration, and codec choice.

type AudioStreamInfo added in v0.0.6

type AudioStreamInfo struct {
	StreamInfo
	// ReportedChannelCount is the channel count as reported by ffprobe.
	// A value of 0 means the channel layout could not be detected.
	ReportedChannelCount int `json:"reported_channel_count"`
	// EffectiveChannelCount is the channel count used for processing decisions
	// such as downmix synthesis. When ReportedChannelCount is 0 (unknown layout),
	// this is set to a conservative surround value (6) so that unknown streams
	// are treated as surround rather than inadvertently blocking downmix synthesis.
	EffectiveChannelCount int  `json:"effective_channel_count"`
	HasLFE                bool `json:"has_lfe,omitempty"`
}

AudioStreamInfo holds stream info for an audio stream, including channel count.

type DetectCropOutput added in v0.0.6

type DetectCropOutput struct {
	// Crop is the detected crop region, or nil when no crop should be applied.
	Crop *ffmpeg.CropParams `json:"crop,omitempty"`
}

DetectCropOutput is the output of the detectcrop workflow task.

type MediaInput

type MediaInput = mediatypes.MediaInput

MediaInput is an alias for the shared input type so existing callers within this package do not need to be updated.

type MediaWorkflowConfig

type MediaWorkflowConfig struct {
	// HardwareDevicePath is the device path passed to CreateHardwareDeviceContext
	// for hardware-accelerated transcoding. An empty string uses libav auto-select.
	HardwareDevicePath string
	// HighCardinalityLabels controls whether per-item labels (id, title, year, etc.)
	// are attached to metric observations. Corresponds to METRICS_HIGH_CARDINALITY_LABELS.
	HighCardinalityLabels bool
	// MinCropX is the minimum number of pixels that must be trimmed horizontally
	// for a crop to be applied. -1 disables the threshold (any crop is accepted).
	// 0 means no minimum (any detected crop is applied).
	MinCropX int
	// MinCropY is the minimum number of pixels that must be trimmed vertically
	// for a crop to be applied. -1 disables the threshold (any crop is accepted).
	// 0 means no minimum (any detected crop is applied).
	MinCropY int
	// DetectCropTimeout is the Temporal StartToCloseTimeout for the detectcrop
	// activity. When zero, NewActivities applies a default of 30 minutes.
	DetectCropTimeout time.Duration
	// TranscodeTimeout is the Temporal StartToCloseTimeout for the transcode
	// activity. When zero, NewActivities applies a default of 4 hours.
	TranscodeTimeout time.Duration
	// H265CRF is the constant-quality value passed to H.265 encoders. 0 means
	// use the encoder's built-in default.
	H265CRF int
	// ProgressLogInterval controls how often a progress log line is emitted
	// during transcoding. Zero disables progress logging.
	ProgressLogInterval time.Duration
}

MediaWorkflowConfig holds the configuration for the media processing workflow and its activities.

type ProbeOutput added in v0.0.6

type ProbeOutput struct {
	// IsValidMedia is false when the file is not a recognisable media file with a
	// video stream. All downstream steps are skipped when this is false.
	IsValidMedia bool `json:"is_valid_media"`
	// VideoCodec is the codec name of the first video stream (e.g. "h264", "hevc").
	// Only meaningful when IsValidMedia is true.
	VideoCodec string `json:"video_codec"`
	// Format is the container format name as reported by ffprobe (e.g. "matroska,webm").
	// Only meaningful when IsValidMedia is true.
	Format string `json:"format"`
	// DurationSeconds is the total duration of the media file in seconds.
	// Only meaningful when IsValidMedia is true; zero otherwise.
	DurationSeconds float64 `json:"duration_seconds"`
	// AudioStreams lists every audio stream found in the file, in stream order.
	// Only meaningful when IsValidMedia is true.
	AudioStreams []AudioStreamInfo `json:"audio_streams,omitempty"`
	// SubtitleStreams lists every subtitle stream found in the file, in stream order.
	// Only meaningful when IsValidMedia is true.
	SubtitleStreams []StreamInfo `json:"subtitle_streams,omitempty"`
	// VideoWidth and VideoHeight are the pixel dimensions of the first video stream.
	// Only meaningful when IsValidMedia is true; zero otherwise.
	VideoWidth  int `json:"video_width,omitempty"`
	VideoHeight int `json:"video_height,omitempty"`
}

ProbeOutput is the output of the probe step.

func RunProbe added in v0.0.6

func RunProbe(ctx context.Context, filePath, watchRoot string, retainEmptyDirs bool) (ProbeOutput, error)

RunProbe reads codec and container info for filePath. If the file is not a recognised media file or has no video stream, it deletes the file and returns IsValidMedia=false (without error), causing all downstream steps to be skipped. When retainEmptyDirs is false and a deletion occurs, empty parent directories up to watchRoot are also removed via pruneEmptyParents.

type Registrar added in v0.0.6

type Registrar interface {
	RegisterWorkflowWithOptions(w any, options workflow.RegisterOptions)
	RegisterActivityWithOptions(a any, options activity.RegisterOptions)
}

Registrar is the subset of registration methods that both worker.Worker and *testsuite.TestWorkflowEnvironment expose. Accepting this interface lets the production worker and the workflow test environment share one registration list, so adding or renaming an activity only requires editing Register.

type StreamInfo added in v0.0.6

type StreamInfo struct {
	Index    int    `json:"index"`
	Language string `json:"language"`
	Title    string `json:"title,omitempty"`
}

StreamInfo holds the input stream index, language tag, and source title for one audio or subtitle stream.

type TranscodeOutput added in v0.0.6

type TranscodeOutput struct {
	// DestCodec is the video codec written to the output file (e.g. "hevc", "copy").
	DestCodec string `json:"dest_codec"`
	// DestContainer is the container format of the output file (always "mkv").
	DestContainer string `json:"dest_container"`
	// DestFilePath is the path of the output file.
	DestFilePath string `json:"dest_file_path"`
	// SourceFileSizeBytes is the size of the input file in bytes, measured before transcoding.
	SourceFileSizeBytes int64 `json:"source_file_size_bytes"`
	// DestFileSizeBytes is the size of the output file in bytes, measured after transcoding.
	DestFileSizeBytes int64 `json:"dest_file_size_bytes"`
	// TranscodeDurationSeconds is the wall-clock time spent in RunTranscode (the ffmpeg call
	// plus surrounding stat/rename operations), in seconds.
	TranscodeDurationSeconds float64 `json:"transcode_duration_seconds"`
	// ArtworkFetchSkipped is true when artwork fetch was attempted but yielded no
	// embeddable image (library unreachable, no poster available, or unsupported type).
	ArtworkFetchSkipped bool `json:"artwork_fetch_skipped,omitempty"`
	// CropApplied is true when a crop filter was applied during transcoding.
	CropApplied bool `json:"crop_applied,omitempty"`
	// HardwareAccelerated is true when at least one video stream was encoded
	// using a hardware encoder (e.g. NVENC, QSV, VAAPI) at runtime. False when
	// the encoder fell back to software (e.g. libx265) even if
	// MEDIA_HARDWARE_DEVICE_PATH is set.
	HardwareAccelerated bool `json:"hardware_accelerated,omitempty"`
}

TranscodeOutput is the output of a successful RunTranscode call.

func RunTranscode added in v0.0.6

func RunTranscode(ctx context.Context, req TranscodeRequest) (TranscodeOutput, error)

RunTranscode transcodes req.FilePath into req.OutputDir, writing to a temp file named "._<stem>.mkv.tmp" and atomically renaming it to "<stem>.mkv" on success. The output always carries a .mkv extension to match the forced MKV container. Writing directly to the output directory avoids a cross-filesystem copy and guarantees the rename is atomic on Linux (same directory).

type TranscodeRequest added in v0.0.6

type TranscodeRequest struct {
	// FilePath is the absolute path of the source media file to transcode.
	FilePath string
	// Probe is the output of RunProbe for FilePath.
	Probe ProbeOutput
	// CropParams is the crop region to apply, or nil for no cropping.
	// When non-nil and the selected video codec would be CodecCopy, the codec
	// is promoted to CodecH265 so the crop filter can be applied.
	CropParams *ffmpeg.CropParams
	// OutputDir is the directory the final .mkv is written into.
	OutputDir string
	// WatcherRoot is the root directory that the watcher monitors. When non-empty,
	// the subdirectory of FilePath relative to WatcherRoot is mirrored under OutputDir,
	// preserving the download client's directory structure. When empty, the output is
	// written flat into OutputDir.
	WatcherRoot string
	// HardwareDevicePath is the device path passed to CreateHardwareDeviceContext;
	// an empty string uses the libav default (auto-select).
	HardwareDevicePath string
	// H265CRF is the constant-quality value for H.265 encoders. 0 means use the
	// encoder's built-in default; valid explicit values are 1–51 (lower = higher
	// quality). For libx265 this is the CRF; for hevc_nvenc it is the CQ value;
	// for hevc_qsv and hevc_vaapi it is the global_quality (ICQ) value. Values
	// outside 1–51 are silently ignored and the encoder default is used.
	H265CRF int
	// ProgressLogInterval controls how often a progress log line is emitted during
	// transcoding. Zero disables progress logging.
	ProgressLogInterval time.Duration
	// Heartbeat, when non-nil, is invoked from the progress-consumer goroutine on
	// every FFmpeg progress tick AND on every ProgressLogInterval ticker tick (so
	// the copy/remux path, which produces no FFmpeg progress packets, still
	// signals liveness within HeartbeatTimeout). The activity wrapper supplies a
	// callback that forwards to activity.RecordHeartbeat so a stalled worker is
	// detected via the configured Temporal HeartbeatTimeout. Tests pass nil.
	// Heartbeat is only invoked when ProgressLogInterval > 0, since the progress
	// goroutine that drives it is gated on that interval.
	Heartbeat func(ffmpeg.Progress)
	// Library is the arr library used to fetch poster artwork. When nil, no fetch
	// is attempted and transcoding proceeds without an embedded attachment, and
	// ArtworkFetchSkipped is not set. When non-nil and the fetch yields no
	// embeddable image, transcoding proceeds without an embedded attachment and
	// ArtworkFetchSkipped is set to true.
	Library medialib.ArrLibrary
}

TranscodeRequest is the input to RunTranscode.

Directories

Path Synopsis
Package types defines the shared workflow name and input payload for the media processing workflow.
Package types defines the shared workflow name and input payload for the media processing workflow.

Jump to

Keyboard shortcuts

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