video_transcoding package

Submodules

video_transcoding.admin module

class video_transcoding.admin.VideoAdmin(model, admin_site)

Bases: ModelAdmin

video_transcoding.admin.short_description(name: str) Callable[[C], C]

Sets short description for function.

video_transcoding.helpers module

video_transcoding.helpers.send_transcode_task(video: Video) AsyncResult

Send a video transcoding task.

If task is successfully sent to broker, Video status is changed to QUEUED and Celery task identifier is saved.

Parameters

video (video.models.Video) – video object

Returns

Celery task result

Return type

celery.result.AsyncResult

video_transcoding.models module

class video_transcoding.models.Video(*args, **kwargs)

Bases: TimeStampedModel

Video model.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

change_status(status: int, **fields: Any) None

Changes video status.

Also saves another model fields and always updates modified value.

Parameters
  • status – one of statuses for Video.status (see STATUS_CHOICES)

  • fields – dict with model field values.

format_video_url(edge: str) str

Returns a link to m3u8 playlist on one of randomly chosen edges.

video_transcoding.tasks module

class video_transcoding.tasks.TranscodeVideo(*args: Any, **kwargs: Any)

Bases: LoggerMixin, Task

Video processing task.

download(source: str, destination: str) None

Downloads source to temporary directory :param source: source file link :param destination: path to downloaded file

lock_video(video_id: int) Video

Gets video in QUEUED status from DB and changes status to PROCESS.

Parameters

video_id – Video primary key

Returns

Video object

Raises

Retry – in case of unexpected video status or task_id

process_video(video: Video, basename: str, download: bool = False) None

Video processing workflow.

  1. Create temporary directory

  2. Transcode source file

  3. Upload resulting file to origins

  4. Cleanup temporary directory

Parameters
  • video – Video object

  • basename – video files common base name

  • download – download source to temp dir

run(video_id: int, download: bool = False) Optional[str]

Process video.

  1. Locks video changing status from QUEUED to PROCESS

  2. Transcodes video and stores result to origins

  3. Changes video status to DONE, stores result basename

  4. On errors changes video status ERROR, stores error message

Parameters
  • video_id – Video id.

  • download – Download source file to tmp dir before processing.

select_for_update(video_id: int, status: int) Video

Lock video in DB for current task.

Parameters
  • video_id – Video primary key

  • status – expected video status

Returns

Video object from db

Raises
  • models.Video.DoesNotExist – in case of missing or locked Video for primary key

  • ValueError – in case of unexpected Video status or task_id

store(destination: str) None

Stores transcoded video to origin list

Parameters

destination – transcoded video path.

transcode(source: str, destination: str) None

Starts video transcoding

Parameters
  • source – source file link (http/ftp or file path)

  • destination – result temporary file path.

unlock_video(video_id: int, status: int, error: Optional[str], basename: Optional[str]) None

Marks video with final status.

Parameters
  • video_id – Video primary key

  • status – final video status (Video.DONE, Video.ERROR)

  • error – error message

  • basename – UUID-like result file identifier

Raises

RuntimeError – in case of unexpected video status or task id

acks_late = True

When enabled messages for this task will be acknowledged after the task has been executed, and not just before (the default behavior).

Please note that this means the task may be executed twice if the worker crashes mid execution.

The application default can be overridden with the :setting:`task_acks_late` setting.

acks_on_failure_or_timeout = True

When enabled messages for this task will be acknowledged even if it fails or times out.

Configuring this setting only applies to tasks that are acknowledged after they have been executed and only if :setting:`task_acks_late` is enabled.

The application default can be overridden with the :setting:`task_acks_on_failure_or_timeout` setting.

ignore_result = False

If enabled the worker won’t store task state and return values for this task. Defaults to the :setting:`task_ignore_result` setting.

name = 'video.transcode'

Name of the task.

priority = None

Default task priority.

rate_limit = None

None (no rate limit), ‘100/s’ (hundred tasks a second), ‘100/m’ (hundred tasks a minute),`’100/h’` (hundred tasks an hour)

Type

Rate limit for this task type. Examples

reject_on_worker_lost = True

Even if acks_late is enabled, the worker will acknowledge tasks when the worker process executing them abruptly exits or is signaled (e.g., :sig:`KILL`/:sig:`INT`, etc).

Setting this to true allows the message to be re-queued instead, so that the task will execute again by the same worker, or another worker.

Warning: Enabling this can cause message loops; make sure you know what you’re doing.

request_stack = <celery.utils.threads._LocalStack object>

Task request stack, the current request will be the topmost.

serializer = 'json'

The name of a serializer that are registered with kombu.serialization.registry. Default is ‘json’.

store_errors_even_if_ignored = False

When enabled errors will be stored even if the task is otherwise configured to ignore results.

track_started = False

If enabled the task will report its status as ‘started’ when the task is executed by a worker. Disabled by default as the normal behavior is to not report that level of granularity. Tasks are either pending, finished, or waiting to be retried.

Having a ‘started’ status can be useful for when there are long running tasks and there’s a need to report what task is currently running.

The application default can be overridden using the :setting:`task_track_started` setting.

typing = True

Enable argument checking. You can set this to false if you don’t want the signature to be checked when calling the task. Defaults to app.strict_typing.

video_transcoding.transcoding module

exception video_transcoding.transcoding.TranscodeError(message: str)

Bases: Exception

Video transcoding error.

class video_transcoding.transcoding.AudioCodec(codec: str = None, bitrate: int = 0, rate: float = None, channels: int = None)

Bases: AudioCodec

channels: int = None
rate: float = None
class video_transcoding.transcoding.Transcoder(source: str, destination: str)

Bases: LoggerMixin

Video transcoder.

>>> t = Transcoder('http://source.localhost/source.mp4', '/tmp/result.mp4')
>>> t.transcode()
fix_frames(t: Track) None

Fix frames count to satisfy equation:

Duration = FPS * frames

fix_par(t: Track) None

Fix PAR to satisfy equation DAR = width / height * PAR.

fix_samples(t: Track) None

Fix sample count to satisfy equation:

Duration = Sampling rate * samples

get_media_info(video: Optional[VideoMeta], audio: Optional[AudioMeta]) Dict[str, Any]

Transforms video and audio metadata to a dict

Parameters
  • video – video stream metadata

  • audio – audio stream metadata

Returns

metadata single level dictionary

get_meta_data(filename: str) Tuple[Optional[AudioMeta], Optional[VideoMeta]]
static run(ff: FFMPEG) None

Starts ffmpeg process and captures errors from it’s logs

transcode() None

Transcodes video

  • checks source mediainfo

  • runs ffmpeg

  • validates result

static validate(source_media_info: Dict[str, Any], dest_media_info: Dict[str, Any]) None

Validate video transcoding result.

Parameters
  • source_media_info – source metadata

  • dest_media_info – result metadata

class video_transcoding.transcoding.VideoCodec(codec: str = None, bitrate: int = 0, force_key_frames: str = None, constant_rate_factor: int = None, preset: str = None, max_rate: int = None, buf_size: int = None, profile: str = None, gop: int = None, rate: float = None, pix_fmt: str = None)

Bases: VideoCodec

buf_size: int = None
constant_rate_factor: int = None
force_key_frames: str = None
gop: int = None
max_rate: int = None
pix_fmt: str = None
preset: str = None
profile: str = None
rate: float = None
video_transcoding.transcoding.Metadata

File metadata type.

alias of Dict[str, Any]

video_transcoding.utils module

class video_transcoding.utils.LoggerMixin(*args: Any, **kwargs: Any)

Bases: object

A mixin for logger injection.

Should not be used with Django models, because Logger contains non-serializable threading.Lock object.