API

filmalize is split up into several modules whose organization hopefully makes some sort of sense.

Models

Core classes for filmalize.

This module contains the classes that do most of the heavy lifting. It should stand alone, and allow for other interfaces to be built using it. The main class is the Container, which may be created manually, or with the classmethod Container.from_file or Container.from_dict.

class models.Container(file_name, duration, streams, subtitle_files=None, selected=None, output_name=None, labels=None)[source]

Multimedia container file object.

Parameters:
  • file_name (str) – The name of the input file.
  • duration (float) – The duration of the streams in the container in seconds.
  • streams (list of Stream) – The mutimedia streams in this Container.
  • subtitle_files (list of SubtitleFile, optional) – Subtitle files to add to the output file.
  • selected (list of int, optional) – Indexes of the Stream instances to include in the output file. If not specified, the first audio and video stream will be selected.
  • output_name (str, optional) – Output filename. If not specified, the output filename will be set to be the same as the input file, but with the extension replaced with the proper one for the output format.
  • labels (ContainerLabel, optional) – Informational metadata about the input file.
file_name

str – The name of the input file.

duration

float – The duration of the streams in the container in seconds.

streams

list of Stream – The mutimedia streams in this Container.

subtitle_files

list of SubtitleFile – Subtitle files to add to the output file.

output_name

str – Output filename.

labels

ContainerLabel – Informational metadata about the input file.

microseconds

int – The duration of the file expressed in microseconds.

temp_file

tempfile.NamedTemporaryFile – The temporary file for ffmpeg to write status information to.

process

subprocess.Popen – The subprocess in which ffmpeg processes the file.

equality_ignore

list of string – Attributes to ignore when checking for equality of Container instances.

add_subtitle_file(file_name, encoding=None)[source]

Add an external subtitle file. Optionally set a custom file encoding.

Parameters:
  • file_name (str) – The name of the subtitle file.
  • encoding (str, optional) – The encoding of the subtitle file.
build_command()[source]

Build the ffmpeg command to process this container.

Generate appropriate ffmpeg options to process the streams selected in self.selected.

Returns:The ffmpeg command and options to execute.
Return type:list of str
convert()[source]

Start the conversion of this container in a subprocess.

default_name

str – The input filename reformatted with the selected output file extension.

default_streams

list of int – The indexes of the first video and audio Stream.

classmethod from_dict(info)[source]

Build a Container from a given dictionary.

Parameters:info (dict) – Container information in dictionary format structured in the manner of ffprobe json output.
Returns:Instance representing the given info.
Return type:Container
Raises:ProbeError – If the info does not contain a ‘duraton’ tag.
classmethod from_file(file_name)[source]

Build a Container from a given multimedia file.

Attempt to probe the file with ffprobe. If the probe is succesful, finish instatiation by passing the results to Container.from_dict.

Parameters:file_name (str) – The file (a multimedia container) to represent.
Returns:Instance representing the given file.
Return type:Container
Raises:ProbeError – If ffprobe is unable to successfully probe the file.
progress

int – The number of microseconds that ffmpeg has processed.

Raises:ProgressFinishedError – If the subprocess is not running (either finished or errored out).
selected

list of int – Indexes of the Stream instances to include in the output file.

Note

At this time filmalize can only output audio, video, and subtitle streams.

Raises:ValueError – If list contains an index that does not correspond to any Stream in Container.streams or if Stream.type is unsupported.
streams_dict

dict of {intStream} – The Stream instances in Container.streams keyed by their indexes.

class models.ContainerLabel(title=None, size=None, bitrate=None, container_format=None, length=None)[source]

Labels for Container objects

Note

The information stored here is simply for display and will not affect the output file.

Parameters:
  • title (str, optional) – Container title.
  • size (float, optional) – Container file size in MiBs.
  • bitrate (float, optional) – Container overall bitrate in Mib/s.
  • container_format (str, optional) – Container file format.
  • length (datetime.timedelta, optional) – The duration of the file as a timedelta.
title

str – Container title.

size

float – Container file size in MiBs.

bitrate

float – Container overall bitrate in Mib/s.

container_format

str – Container file format.

length

datetime.timedelta – The duration of the file as a timedelta.

classmethod from_dict(info)[source]

Build a ContainerLabel instance from a dictionary.

Parameters:info (dict) – Container information in dictionary format structured in the manner of ffprobe json output.
Returns:Instance populated wtih data from the given dictionary.
class models.EqualityMixin[source]

Mixin class that adds equality checking.

Note

Equality checks are performed by checking the equality of the object.__dict__ methods of the classes at issue.

To exclude attributes from the comparison, add an attribute equality_ignore to the class. Populate this attribute with a list of str names of attributes to exclude.

class models.Stream(index, stream_type, codec, custom_crf=None, custom_bitrate=None, labels=None)[source]

Multimedia stream object.

Note

At this time, Stream instances will only be included in the output file if they have type of ‘audio’, ‘video’, or ‘subtitle’.

Parameters:
  • index (int) – The stream index.
  • stream_type (str) – The multimedia type of the stream as reported by ffprobe.
  • codec (str) – The codec with which the stream is encoded as as reported by ffprobe.
  • custom_crf (int, optional) – Video stream Constant Rate Factor. If specified, this stream will be transcoded using this crf even if the input stream is suitable for copying to the output file.
  • custom_bitrate (float, optional) – Audio stream ouput bitrate in Kib/s. If specified, this audio stream will be transcoded using this as the target bitrate even if the input stream is suitable for copying and even if there is a bitrate set in the StreamLabel.
  • labels (StreamLabel, optional) – Informational metadata about the input stream.
index

int – The stream index.

stream_type

str – The multimedia type of the stream as reported by ffprobe.

codec

str – The codec with which the stream is encoded as as reported by ffprobe.

custom_crf

int – Video stream Constant Rate Factor. If set, this stream will be transcoded using this crf even if the input stream is suitable for copying to the output file.

custom_bitrate

float – Audio stream ouput bitrate in Kib/s. If set, this audio stream will be transcoded using this as the target bitrate even if the input stream is suitable for copying and even if there is a bitrate set in the StreamLabel.

labels

StreamLabel – Informational metadata about the input stream.

build_options(number=0)[source]

Generate ffmpeg codec/bitrate options for this Stream.

The options generated will use custom values for video CRF or audio bitrate, if specified, or the default values. The option_summary is updated to reflect the selected options.

Parameters:number (int, optional) – The number of Streams of this type that have been added to the command.
Returns:The ffmpeg options for this Stream.
Return type:list of str
classmethod from_dict(info)[source]

Build a Stream instance from a dictionary.

Parameters:info (dict) – Stream information in dictionary format structured in the manner of ffprobe json output.
Returns:Instance populated with data from the given dictionary.
Return type:Stream
class models.StreamLabel(title=None, bitrate=None, resolution=None, language=None, channels=None, default=None)[source]

Labels for Stream objects.

Note

The information stored here is simply for display and (with one exception) will not affect the output file.

For audio streams, if this stream cannot be copied and must be transcoded, if there is not a Stream.custom_bitrate set, and if there is a value stored in StreamLabel.bitrate, that value will be chosen by default as the output stream target bitrate.

Parameters:
  • title (str) – Stream title.
  • bitrate (float) – Stream bitrate in Mib/s for video streams or Kib/s for audio streams.
  • resolution (str) – Stream resolution.
  • language (str) – Language name or abbreviation.
  • channels (str) – Audio channel information (stereo, 5.1, etc.).
  • default (bool) – True if this stream is the default stream of its type, else False.
title

str – Stream title.

bitrate

float – Stream bitrate in Mib/s for video streams or Kib/s for audio streams.

resolution

str – Stream resolution.

language

str – Language name or abbreviation.

channels

str – Audio channel information (stereo, 5.1, etc.).

default

str – ‘default’ if this stream is the default stream of its type, else ‘’.

Parameters:is_default (bool) – True if this stream is the default stream of its type, else False.
classmethod from_dict(info)[source]

Build a StreamLabel instance from a dictionary.

Parameters:info (dict) – Stream information in dictionary format structured in the manner of ffprobe json output.
Returns:Instance populated with the data from the given directory.
class models.SubtitleFile(file_name, encoding=None)[source]

Subtitle file object.

Parameters:
  • file_name (str) – The subtitle file to represent.
  • encoding (str, optional) – The file encoding of the subtitle file.
file_name

str – The subtitle file represented.

encoding

str – The file encoding of the subtitle file.

guess_encoding()[source]

Guess the encoding of the subtitle file.

Open the given file, read a line, and pass that line to chardet.detect to produce a guess at the file’s encoding.

Returns:The best guess for the subtitle file encoding.
Return type:str

CLI Models

CLI classes for filmalize.

This module contains classes for use by the cli and menus modules as well as core classes extended with additional functionality for command-line use.

class cli_models.CliContainer(writer=None, pr_bar=None, **kwargs)[source]

Multimedia container file object with CLI extensions.

Parameters:
  • writer (Writer, optional) – Object with which to display the progress bar.
  • pr_bar (progressbar.bar.ProgressBar, optional) – Progress bar to display the progress of converting this container.
  • **kwargsContainer arguments.
writer

Writer – Object with which to write.

pr_bar

progressbar.bar.ProgressBar – Progress bar to write.

add_progress(terminal, line_number, padding)[source]

Build a progressbar.bar.Progressbar instance for this Container.

Parameters:
  • terminal (blessed.terminal.Terminal) – Terminal to display to.
  • line_number (int) – The line number to display on.
  • padding (int) – The number of characters to pad the filename with.
display()[source]

Echo a pretty representation of this Container.

display_command()[source]

Echo the current compiled command for this Container.

display_conversion()[source]

Echo a pretty representation of the conversion actions to perform on this Container.

classmethod from_dict(info)[source]

Build a CliContainer from a given dictionary.

Parameters:info (dict) – Container information in dictionary format structured in the manner of ffprobe json output.
Returns:Instance representing the given info.
Return type:CliContainer
Raises:ProbeError – If the info does not contain a ‘duraton’ tag.
class cli_models.CliStream(index, stream_type, codec, custom_crf=None, custom_bitrate=None, labels=None)[source]

Multimedia stream object with CLI extensions.

Parameters:**kwargsStream arguments.
display()[source]

Echo a pretty representation of this Stream.

class cli_models.CliSubFile(file_name, encoding=None)[source]

Subtitle file object with CLI extensions.

Parameters:**kwargsSubtitleFile arguments.
display()[source]

Echo a pretty representation of this subtitle file.

class cli_models.ErrorWriter(terminal)[source]

Write error messages in bright red to the bottom of a Terminal.

Parameters:terminal (blessed.terminal.Terminal) – Where to write.
terminal

blessed.terminal.Terminal – Where to write.

line

int – The highest line to write to. Starts at the bottom of the screen and increments upward as additional messages are written.

messages

list of str – The messages to write.

write(message)[source]

Add a message to the list and display all messages at the bottom of the Terminal.

As subsequent messages are written, earlier messages are moved upward.

Parameters:message (str) – The message to display.
class cli_models.SelectStreams(container)[source]

Custom Click parameter type to set the selected streams for a Container.

This class can be set as the type option in a Click.prompt or other click input and, with the convert method, will check the users input to ensure that the indexes that they have entered match a Stream in the Container specified at instantiation.

Parameters:container (Container) – The Container to check for Stream indexes.
convert(value, param, ctx)[source]

Attempt to set input indexes as Container.streams.

class cli_models.Writer(line, terminal, color=None)[source]

Writes messages to a specific line on the screen, defined at instantiation.

Parameters:
  • line (int) – The line of the screen for this instance to write to.
  • terminal (blessed.terminal.Terminal) – Where to write.
  • color (str, optional) – The color to print in. Must conform to the blessed color function format.
line

int – The line of the screen that this instance writes to.

terminal

blessed.terminal.Terminal – Where to write.

color

str – The color to print in.

static flush()[source]

Pretend to flush as if Writer was a real file descriptor.

progressbar.bar.ProgressBar objects expect to flush their file descriptors, but since we’re actually printing to a blessed.terminal.Terminal, this method is needed to keep the progress bars happy.

Returns:True
Return type:bool
write(message)[source]

Write a message to the screen.

The message is written to the Writer.terminal, on the Writer.line, and in Writer.color, if set.

Parameters:message (str) – The message to display

CLI

Command-Line Interface for filmalize.

This module contains the Click command definitions as well as helper functions. It also contains classes used for the progress bars that are displayed to the user once the transcoding has been started.

cli.build_containers(file_list)[source]

Utility function to build a list of Container instances given a list of filenames.

Note

If a container fails to build as the result of a ffprobe error, that error is echoed after building has completed. If no containers are built, an empty list is returned.

Parameters:file_list (list of str) – File names to attempt to build into containers.
Returns:Succesfully built containers.
Return type:list of Container
cli.exclusive(ctx_params, exclusive_params, error_message)[source]

Utility function for enforcing exclusivity between click options.

Call at the top of a click.group or click.command definition.

Parameters:
  • ctx_params (dict) – The context parameters to search.
  • exclusive_params (list of str) – Mutually exclusive parameters.
  • error_message (str) – The error message to display.
Raises:

click.UsageError – If more than one exclusive parameter is present in the context parameters.

Examples:

@click.command()
@click.option('-s', '--song', default='')
@click.option('-a', '--album', default='')
def music(song, album):
    ctx_params = click.get_current_context().ctx_params
    exclusive_params = ['song', 'album']
    error_message = 'song and album are mutually exclusive'
    exclusive(ctx_params, exclusive_params, error_message)
    ...

# You can also include parameters from multiple layers of a nested app.
...
ctx_params = {**ctx.params, **ctx.parent.params}
exclusive_params = ['a', 'b']
error_message = 'command option b conflicts with parent option a'
exclusive(ctx_params, exclusive_params, error_message)
...
cli.cli(ctx, file, directory, recursive)

The click.Group that is the core of the cli.

By default filmalize operates on all files in the current directory. If desired, you may specify an individual file or a different working directory. Directory operation may be recursive. A command (display or convert) is required.

The exclusive function is used to ensure that the file and directory or file and recursive parameters cannot by passed simultaneously.

Depending on the options passed, assign a list of str file names to the user context object click.Context.obj.

Parameters:
  • ctx (click.Context) – The click.Context instance for this execution of the command
  • file (click.Path, optional) – The file on which to operate.
  • directory (click.Path, optional) – The directory on which to operate.
  • recursive (bool) – Flag to initiate recursive directory processing.
cli.display(ctx)

The click.Command to display information about multimedia files.

Take the list of filenames stored in click.Context.obj, use build_contaners to create an list of Container instances, and display those instances with display_contianer.

Parameters:ctx – The click.Context instance for this execution of the command
cli.convert(ctx)

The click.Command to convert multimedia files.

Take the list of filenames stored in click.Context.obj, use cli.build_contaners to create a list of Container instances. Those instances are displayed to the user for consideration using menus.main_menu, which passes back a list of the instances that the user has started. Finally, an informative display, which uses progressbar.bar.ProgressBar instances for each Container on a blessed.terminal.Terminal, is shown to the user until the transcoding process has finished.

Parameters:ctx – The click.Context instance for this execution of the command

Menus

CLI menu functions for filmalize.

This module contains the functions that define the menu system that the user uses to select the streams to transcode and/or edit transcoding parameters.

Prompt the user to add an external subtitle file (SubtitleFile) to a given Container.

Raises:UserCancelError – If the user cancels adding a subtitle file.

Prompt the user to specify a name for the output file produced by a given Container instance.

Raises:UserCancelError – If the user cancels entering a name.

Promt the user to set a custom encoding for a SubtitleFile in a given:obj:Container.

Raises:UserCancelError – If there are no subtitle files to change or the user cancels changing a subtitle file.

The edit menu, which is accessible from the main menu.

The user may elect to edit the Stream or SubtitleFile instances associated with the given Container, change the ouput filename, display the raw ffmpeg command, or return to the main menu.

Parameters:container (Container) – The Container instance to edit.

Prompt the user to select a Stream instance from a given Container and edit its conversion options.

Raises:UserCancelError – If the user cancels editing a stream.

The main menu, which is loaded when running the convert command.

The main menu is presented for each container given, preceeded by a pretty representation of the container and a description of the actions to be taken. The user may select from the options Convert, Skip, Edit, and Quit. If convert is selected, the conversion is started immediately in a subprocess. However, those processes will be terminated if Quit is subsequently selected. If the user selects Edit, the edit menu is loaded.

Parameters:containers (list of Container) – Candidates for conversion.
Returns:The instances that were approved by the user and started.
Return type:list of Container

Utility function to ask the user a multple choice question.

Note

The user must enter one of the characters in the responses list, and will be prompted repeatedly until they do so.

Parameters:
  • prompt (str) – The question to ask the user.
  • responses (list of str) – The possible answers to the question in the form of individual characters. The characters will be displayed to the user separated by ‘/’ characters.
  • key (str, optional) – A key to relate the characters in the responses list to answers to the prompt.
Returns:

The character from the responses list that the user selected.

Return type:

str

Prompt the user to remove a chosen SubtitleFile instance from a given Container.

Raises:UserCancelError – If the user cancels removing a subtitle file, or if there are no subtitle files to remove.

Prompt the user to select the Stream instances of a given Container to include in the output file.

Raises:UserCancelError – If the user cancels selecting streams.

The stream menu, which is accessible from the edit menu.

The user may elect to select the Stream instances to be included in the output file or edit the parameters of one of those streams.

Parameters:container (Container) – The Container object whose Stream instances to select from or edit.

The subtitle menu, which is accessible from the edit menu.

The user may elect to add, remove, or change the encoding of a SubtitleFile.

Parameters:container (Container) – The Container instance whose SubtitleFile instances to add to, remove, or change.

Utility function to ask the user a yes/no question.

Note

The user must enter ‘y’ or ‘n’, and will be prompted repeatedly until they do so.

Parameters:prompt (str) – The question to ask the user.
Returns:True if the user enters ‘y’ or False if the user enters ‘n’.
Return type:bool

Errors

Custom error classes for filmalize.

exception errors.Error[source]

Base class for filmalize Exceptions.

exception errors.ProbeError(file_name, message=None)[source]

Custom Exception for when ffprobe is unable to parse a file.

exception errors.ProgressFinishedError[source]

Custom Exception for when a container has finished processing.

exception errors.UserCancelError[source]

Custom Exception for when the user cancels an action.