# `Membrane.Pipeline`
[🔗](https://github.com/membraneframework/membrane-core/blob/v1.2.7/lib/membrane/pipeline.ex#L1)

A behaviour module for implementing pipelines.

`Membrane.Pipeline` contains the callbacks and functions for constructing and supervising pipelines.
Pipelines facilitate the convenient instantiation, linking, and management of elements and bins.\
Linking pipeline children together enables them to pass and process data.

To create a pipeline, use `use Membrane.Pipeline` and implement callbacks of `Membrane.Pipeline`  behaviour.
See `Membrane.ChildrenSpec` for details on instantiating and linking children.
## Starting and supervision

Start a pipeline with `start_link/2` or `start/2`. Pipelines always spawn under a dedicated supervisor, so
in the case of success, either function will return `{:ok, supervisor_pid, pipeline_pid}` .

The supervisor never restarts the pipeline, but it does ensure that the pipeline and its children terminate properly.
If the pipeline needs to be restarted, it should be spawned under a different supervisor with the appropriate strategy.

### Starting under a supervision tree

 A pipeline can be spawned under a supervision tree like any other `GenServer`.\
 `use Membrane.Pipeline` injects a `child_spec/1` function. A simple scenario could look like this:

    defmodule MyPipeline do
      use Membrane.Pipeline

      def start_link(options) do
        Membrane.Pipeline.start_link(__MODULE__, options, name: MyPipeline)
      end

      # ...
    end

    Supervisor.start_link([{MyPipeline, option: :value}], strategy: :one_for_one)
    send(MyPipeline, :message)

### Starting outside of a supervision tree

When starting a pipeline outside a supervision tree, use the `pipeline_pid` pid to interact with the pipeline.
 A simple scenario could look like this:

    {:ok, _supervisor_pid, pipeline_pid} = Membrane.Pipeline.start_link(MyPipeline, option: :value)
    send(pipeline_pid, :message)

### Visualizing the supervision tree

Use the [Applications tab](https://www.erlang.org/doc/apps/observer/observer_ug#applications-tab) in Erlang's Observer GUI
(or the `Kino` library in Livebook) to visualize a pipeline's internal supervision tree. Use the following configuration for debugging purposes only:

      config :membrane_core, unsafely_name_processes_for_observer: [:components]

This improves the readability of the Observer's process tree graph by naming the pipeline descendants, as demonstrated here:

![Observer graph](assets/images/observer_graph.png).

# `callback_return`

```elixir
@type callback_return() :: {[Membrane.Pipeline.Action.t()], state()}
```

Defines return values from Pipeline callback functions.

## Return values

  * `{[action], state}` - Returns a list of actions that will be performed within the
    pipeline, e.g., starting new children, sending messages to specific children, etc.
    Actions are tuples of `{type, arguments}`, so they can be expressed as a keyword list.
    See `Membrane.Pipeline.Action` for more info.

# `config`

```elixir
@type config() :: [config_entry()]
```

List of configurations used by `start/3` and `start_link/3`.

# `config_entry`

```elixir
@type config_entry() :: {:name, name()}
```

Defines configuration value used by the `start/3` and `start_link/3`.

# `name`

```elixir
@type name() :: GenServer.name()
```

The Pipeline name

# `on_start`

```elixir
@type on_start() ::
  {:ok, supervisor_pid :: pid(), pipeline_pid :: pid()}
  | {:error, {:already_started, pid()} | term()}
```

Defines the return value of the `start/3` and `start_link/3`."

# `pipeline_options`

```elixir
@type pipeline_options() :: any()
```

Defines options passed to the `start/3` and `start_link/3` and subsequently received
in the `c:handle_init/2` callback.

# `state`

```elixir
@type state() :: any()
```

The pipeline state.

# `handle_call`
*optional* 

```elixir
@callback handle_call(
  message :: any(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) ::
  {[
     Membrane.Pipeline.Action.common_actions()
     | Membrane.Pipeline.Action.reply()
   ], state()}
```

Callback invoked when the pipeline is called using a synchronous call.

Context passed to this callback contains an additional field `:from`.
By default, it does nothing.

# `handle_child_notification`
*optional* 

```elixir
@callback handle_child_notification(
  notification :: Membrane.ChildNotification.t(),
  element :: Membrane.Child.name(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when a notification comes in from a child.

By default, it ignores the notification.

# `handle_child_pad_removed`
*optional* 

```elixir
@callback handle_child_pad_removed(
  child :: Membrane.Child.name(),
  pad :: Membrane.Pad.ref(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state :: state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when a child removes its pad.

The callback won't be invoked, when you have initiated the pad removal,
eg. when you have returned `t:Membrane.Pipeline.Action.remove_link()`
action which made one of your children's pads be removed.
By default, it does nothing.

# `handle_child_playing`
*optional* 

```elixir
@callback handle_child_playing(
  child :: Membrane.Child.name(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when a child enters `playing` playback.

By default, it does nothing.

# `handle_child_setup_completed`
*optional* 

```elixir
@callback handle_child_setup_completed(
  child :: Membrane.Child.name(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when a child completes its setup.

By default, it does nothing.

# `handle_child_terminated`
*optional* 

```elixir
@callback handle_child_terminated(
  child :: Membrane.Child.name(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: callback_return()
```

Callback invoked after a child terminates.

Context passed to this callback contains 3 additional fields: `:exit_reason`, `:group_name` and `:crash_initiator`.
Terminated child won't be present in the context of this callback. It is allowed to spawn a new child
with the same name.
By default, it does nothing.

# `handle_crash_group_down`
*optional* 

```elixir
@callback handle_crash_group_down(
  group_name :: Membrane.Child.group(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when a crash group crashes, when all children from
the crash group are already dead.

You can use this callback to respawn the children from the failed crashed crash group.
Context passed to this callback contains 3 additional fields: `:members`, `:crash_initiator` and `:crash_reason`.
By default, it does nothing.

# `handle_element_end_of_stream`
*optional* 

```elixir
@callback handle_element_end_of_stream(
  child :: Membrane.Child.name(),
  pad :: Membrane.Pad.ref(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when a child element finishes processing a stream via the given pad.

By default, it does nothing.

# `handle_element_start_of_stream`
*optional* 

```elixir
@callback handle_element_start_of_stream(
  child :: Membrane.Child.name(),
  pad :: Membrane.Pad.ref(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when a child element starts processing a stream via the given pad.

By default, it does nothing.

# `handle_info`
*optional* 

```elixir
@callback handle_info(
  message :: any(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when the pipeline receives a message that is not recognized
as an internal Membrane message.

Useful for receiving data sent from NIFs or other external sources.
By default, it logs and ignores the received message.

# `handle_init`
*optional* 

```elixir
@callback handle_init(
  context :: Membrane.Pipeline.CallbackContext.t(),
  options :: pipeline_options()
) ::
  {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked on initialization of the pipeline.

This callback is synchronous: the process that started the pipeline waits until `handle_init`
finishes, so it's important to do any long-lasting or complex work in `c:handle_setup/2`.
`handle_init` should be used for things, like parsing options, initializing state, or spawning
children. By default, `handle_init` converts `opts` to a map if they're a struct and sets them as the pipeline state.

# `handle_playing`
*optional* 

```elixir
@callback handle_playing(
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when the pipeline switches the playback to `:playing`.
By default, it does nothing.

# `handle_setup`
*optional* 

```elixir
@callback handle_setup(
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked on pipeline startup, right after `c:handle_init/2`.

Any long-lasting or complex initialization should happen here.
By default, it does nothing.

# `handle_spec_started`
*optional* 

```elixir
@callback handle_spec_started(
  children :: [Membrane.Child.name()],
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

This callback is deprecated since v1.1.0.

Callback invoked when children of `Membrane.ChildrenSpec` are started.

It is invoked, only if pipeline module contains its definition. Otherwise, nothing happens.

# `handle_terminate_request`
*optional* 

```elixir
@callback handle_terminate_request(
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) ::
  {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked when the pipeline is requested to terminate with `terminate/2`.
By default, it returns `t:Membrane.Pipeline.Action.terminate/0` with reason `:normal`.

# `handle_tick`
*optional* 

```elixir
@callback handle_tick(
  timer_id :: any(),
  context :: Membrane.Pipeline.CallbackContext.t(),
  state()
) :: {[Membrane.Pipeline.Action.common_actions()], state()}
```

Callback invoked upon each timer tick. A timer can be started with `Membrane.Pipeline.Action.start_timer`
action.

# `__using__`
*macro* 

Brings all the stuff necessary to implement a pipeline.

Options:
  - `:bring_spec?` - if true (default) imports and aliases `Membrane.ChildrenSpec`
  - `:bring_pad?` - if true (default) requires and aliases `Membrane.Pad`

# `call`

```elixir
@spec call(pid(), any(), timeout()) :: term()
```

Calls the pipeline with a message.

Returns the result of the pipeline call.

# `list_pipelines`

```elixir
@spec list_pipelines() :: [pid()]
```

Returns list of pipeline PIDs currently running on the current node.

Use for debugging only.

# `list_pipelines`

```elixir
@spec list_pipelines(node()) :: [pid()]
```

Returns list of pipeline PIDs currently running on the passed node. \
Compare to `list_pipelines/0`.

# `pipeline?`

```elixir
@spec pipeline?(module()) :: boolean()
```

Checks whether the module is a pipeline.

# `start`

```elixir
@spec start(module(), pipeline_options(), config()) :: on_start()
```

Starts the pipeline outside a supervision tree. Compare to `start_link/3`.

# `start_link`

```elixir
@spec start_link(module(), pipeline_options(), config()) :: on_start()
```

Starts the pipeline based on the given module and links it to the current process.

Pipeline options are passed to the `c:handle_init/2` callback.
Note that this function returns `{:ok, supervisor_pid, pipeline_pid}` in case of
success. Check the 'Starting and supervision' section of the moduledoc for details.

# `terminate`

```elixir
@spec terminate(pipeline :: pid(),
  timeout: timeout(),
  force?: boolean(),
  asynchronous?: boolean()
) ::
  :ok | {:ok, pid()} | {:error, :timeout}
```

Terminates the pipeline.

Accepts three options:
* `asynchronous?` - if set to `true`, pipeline termination won't be blocking and
  will be executed in the process whose pid is returned as a function result.
  If set to `false`, pipeline termination will be blocking and will be executed in
  the process that called this function. Defaults to `false`.
* `timeout` - specifies how much time (ms) to wait for the pipeline to gracefully
  terminate. Defaults to 5000.
* `force?` - determines how to handle a pipeline still alive after `timeout`.
  If set to `true`, `Process.exit/2` kills the pipeline with reason `:kill` and returns
  `{:error, :timeout}`.
  If set to `false`, it raises an error. Defaults to `false`.

Returns:
* `{:ok, pid}` - option `asynchronous?: true` was passed.
* `:ok` - pipeline gracefully terminated within `timeout`.
* `{:error, :timeout}` - pipeline was killed after `timeout`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
