Commit graph

63 commits

Author SHA1 Message Date
Sebastian Dröge 3b4c48d9f5 Fix various new clippy warnings
Part-of: <https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs/-/merge_requests/1062>
2023-01-25 10:31:19 +02:00
François Laignel 5ca033049e ts/pad: use gst::Pad in handlers trait functions...
... instead of the `Pad{Src,Sink}Ref` wrappers:

- In practice, only the `gst::Pad` is useful in these functions.
  Some of these which need a `Pad{Src,Sink}Ref`, but it's the one
  for the opposite stream direction. In those cases, it is accessed
  via the element's implementation.
- It saves a few `clone`s.
- The implementations usually use the `gst::Pad` for logging.
  They no longer need to access it via `pad.gst_pad()`.
2022-10-24 13:15:13 +02:00
François Laignel 554ce7e7d6 ts/pad: don't pass self as ref in remaining handler traits functions
- They are either unit types or `Clone` (in which case they are implemented
  as pointers).
- Internally, we already use an owned version, so there's no need to get a
  reference.
- It facilitates implementation if the handler must be moved into a closure
  or a `Future`.
2022-10-24 12:01:09 +02:00
Sebastian Dröge 9a68f6e221 Move from imp.instance() to imp.obj()
It's doing the same thing and is shorter.
2022-10-23 23:08:46 +03:00
François Laignel 86776be58c Remove & for obj in log macros
This is no longer necessary.

See https://gitlab.freedesktop.org/gstreamer/gstreamer-rs/-/merge_requests/1137
2022-10-23 21:22:31 +02:00
Sebastian Dröge e49138516c Update for pad default functions API changes 2022-10-12 19:50:15 +03:00
François Laignel 2bffdec691 ts: better use of imp & elem args in Pad{Sink,Src}Handlers
This is a follow-up to commit 7ee4afac.

This commit cleans up the `Pad{Sink,Src}Handler` by

- Keeping arguments which are strictly necessary.
- Passing arguments by value for the trait functions which return
  a `Future`. The arguments which were previously passed by reference
  were `clone`d internally and then `clone`d again in most
  implementations.

There are unfortunate differences in trait function signatures
between those which return a `Future` and the sync functions. This
is due to the requirement for the arguments to be moved to the
resulting `Future`, whereas sync functions can rely on references.
One particular notable difference is the use of the `imp` in sync
functions instead of the `elem` in functions returning a `Future`.
Because the `imp` is not guaranteed to implement `Clone`, we can't
move it to the resulting `Future`, so the `elem` is used.
2022-10-12 12:35:20 +02:00
Sebastian Dröge 7ee4afacf4 Change *Impl trait methods to only take &self and not Self::Type in addition 2022-10-10 15:03:25 +03:00
François Laignel 1be30b8ecc ts/scheduler: fix shutdown
A strong handle reference was held in the `block_on_priv` `Result`
handler in the thread for the `Scheduler::start` code path, which
lead to the `Handler` strong count not dropping to 0 when it
should, leading to the shutdown request not being triggered.

Use an Arc<AtomicBool> instead of a oneshot channel for shutdown.
The main Future is always polled and never relies on a waker, a
`poll_fn` is cheap and does the job.

Unpark the scheduler after posting a request to shutdown.
2022-09-13 07:29:50 +00:00
François Laignel ab327be9af ts/scheduler: improve tasks / io & timers polling balance
Set a limit to the nb of task checked before checking the reactor
and the main future again.
2022-09-13 07:29:50 +00:00
François Laignel d39aabe054 ts/Task: don't drain sub tasks after state transition and iteration
Subtasks are used when current async processing needs to execute
a `Future` via a sync function (eg. a call to a C function).
In this case `Context::block_on` would block the whole `Context`,
leading to a deadlock.

The main use case for this is the `Pad{Src,Sink}` functions:
when we `PadSrc::push` and the peer pad is a `PadSink`, we want
`PadSrc::push` to complete after the async function on the
`PadSink` completes. In this case the `PadSink` async function
is added as a subtask of current scheduler task and
`PadSrc::push` only returns when the subtask is executed.

In `runtime::Task` (`Task` here is the execution Task with a
state machine, not a scheduler task), we used to spawn state
transition actions and iteration loop (leading to a new
scheduler Task). At the time, it seemed convenient for the user
to automatically drain sub tasks after a state transition action
or an iteration. User wouldn't have to worry about this, similarly
to the `Pad{Src,Sink}` case.

In current implementation, the `Task` state machine now operates
directly on the target `Context`. State transtions actions and
the iteration loop are no longer spawned. It seems now useless to
abstract the subtasks draining from the user. Either they
transitively use a mechanism such as `Pad{Src,Sink}` which already
handles this automatically, or they add substasks on purpose, in
which case they know better when subtasks must be drained.
2022-09-13 07:29:50 +00:00
François Laignel af12bce141 ts/executor: clear the reactor instead of closing it...
... so that it can be reused on current thread for subsequent
Scheduler instantiations (e.g. block_on) without the need to
reallocate internal data structures.
2022-09-13 07:29:50 +00:00
François Laignel 61c62ee1e8 ts/timers: multiple improvements
This commit improves threadshare timers predictability
by better making use of current time slice.

Added a dedicate timer BTreeMap for after timers (those
that are guaranteed to fire no sooner than the expected
instant) so as to avoid previous workaround which added
half the max throttling duration. These timers can now
be checked against the reactor processing instant.

Oneshot timers only need to be polled as `Future`s when
intervals are `Stream`s. This also reduces the size for
oneshot timers and make user call `next` on intervals.
Intervals can also implement `FusedStream`, which can help
when used in features such as `select!`.

Also drop the `time` module, which was kepts for
compatibility when the `executor` was migrated from tokio
based to smol-like.
2022-09-13 07:29:50 +00:00
François Laignel 235ded35fd ts: add feature to add counters for performance evaluation
Add a `tuning` feature which adds counters that help with performance
evaluation. The only counter added so far accumulates the duration a
Scheduler has been parked, which is pretty accurate an indication of
CPU usage of the Scheduler.
2022-09-13 07:29:50 +00:00
François Laignel 72acbebff0 ts/standalone: multiple improvements
- Reworked buffer push.
- Reworked stats.
- Make first elements logs stand out. This make it possible to
  follow what's going on with pipelines containing 1000s of
  elements.
- Actually handle EOS.
- Use more significant defaults.
- Allow building without `clap` feature.
2022-09-13 07:29:50 +00:00
François Laignel 2bb071a950 ts/runtime: slight optimizations for sub tasks related operations
Using callgrind with the standalone test showed opportunities for
improvements for sub tasks addition and drain.

All sub task additions were performed after making sure we were
operating on a Context Task. The Context and Task were checked
again when adding the sub task.

Draining sub tasks was perfomed in a loop on every call places,
checking whether there were remaining sub tasks first. This
commit implements the loop and checks directly in
`executor::Task::drain_subtasks`, saving one `Mutex` lock and
one `thread_local` access per iteration when there are sub
tasks to drain.

The `PadSink` functions wrapper were performing redundant checks
on the `Context` presence and were adding the delayed Future only
when there were already sub tasks.
2022-08-18 18:42:18 +02:00
François Laignel 8b54c3fed6 ts/Task: split iterate into try_next and handle_item
Previous Task iteration model suffered from the following
shortcomings:

- When an iteration was engaged it could be cancelled at
  await points by Stop or Flush state transitions,
  which could lead to inconsistent states.
- When an iteration was engaged it could not be cancelled
  by a Pause state transition so as to prevent data loss.
  This meant we couldn't block on the Pause request because
  the mechanism couldn't guarantee Paused would be reached
  in a timely manner.

This commit split the Task iteration into:

- `try_next`: this function returns a future that awaits
  for a new iteration to begin. The regular use case is
  to return an item to process. The item can be left to
  `()` if `try_next` acts as a tick generator. It can
  also return an error. This function can be cancelled at
  await points when a state transition request occurs.
- `handle_item`: this function is called with the item
  returned by `try_next` and is guaranteed to run to
  completion even if a transition request is received.

Note that this model plays well with the common Future
cancellation pitfalls in Rust.
2022-08-10 20:02:53 +02:00
Sebastian Dröge bdaa39e267 threadshare: Fix some new clippy beta warnings
warning: this expression borrows a value the compiler would automatically borrow
   --> generic/threadshare/src/runtime/executor/async_wrapper.rs:402:19
    |
402 |             match (&mut *self).get_mut().read(buf) {
    |                   ^^^^^^^^^^^^ help: change this to: `(*self)`
    |
    = note: `#[warn(clippy::needless_borrow)]` on by default
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
2022-08-10 12:58:28 +03:00
François Laignel d4061774a4 ts/Task: return a future for state transitions
State transitions request functions hid the synchronization
details to the caller:

- If the transition was requested from a Context, a subtask was
  added or the transition ack was not awaited if the new transition
  was requested from a running transition or an iteration function.
- If the transition was not requested from a Context, current
  thread was blocked until the ack was received.

This strategy facilitated code in elements, but it suffered from
the following shortcomings:

- The `prepare` transition request didn't comply with the above
  strategy and would always return an `Async` form. This was
  designed to accomodate the `Prepare` function for elements
  such as `ts-tcpclientsrc` which takes times due to the
  TCP socket connection delays. The idea was that the actual
  transition result would be available after calling `start`.
  This was a disadvantage for elements which would prefer to
  error immediately in the event of a preparation failure.
- Hidding the transition request synchronization to the caller
  meant that they had no options but relying on the internal
  mechanism. E.g.: it was not possible to `start` from another
  async runtime without blocking. Also it was not possible
  to request a transition and choose not to await for the
  ack.

This commit introduces a more flexible API for state
transitions requests:

- The transition request function now return a `TransitionStatus`,
  which is a Future.
- When an error occurs immediately (e.g. the transition
  request is not autorized due to current state of the Task),
  the `TransitionStatus` is resolved immediately and can be
  `check`ed for errors. This is useful for functions such as
  `pepare` in the case of `ts-tcpclientsrc` (see above).
  This is also useful for `pause`, because in current design,
  the transition is always async. Note however, that `pause` is
  forseen to adhere to the same behaviour as the other transition
  requests in the near future [1].
- If the caller chooses to await for the ack and they don't know
  if they are running on a ts Context (e.g. in `Pad{Src,Sink}`
  handlers), they can call `await_maybe_on_context`. This is mostly
  the same behaviour as the one that used to be performed internaly.
- If the caller knows for sure they can't possibly block an async
  executor, they can call `block_on` which is more explicite, but
  will nonetheless make sure no ts Context is being blocked. This
  last check was introduced as it was considered low overhead
  while it should ease preventing missues in cases where the above
  functions should be used.

[1]: https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs/-/merge_requests/793#note_1464400
2022-08-09 19:48:06 +02:00
François Laignel 625fce3934 ts/Task: spawn StateMachine on ts Context
Task state machines used to execute in an executor from the Futures
crate. State transitions actions and iteration functions were then
spawned on the target threadshare Context.

This commit directly spawns the task state machine on the threadshare
Context. This simplifies code a bit and paves the way for the changes
described in [1].

Also introduces struct `StateMachineHandle`, which gather together
fields to communicate and synchronize with the StateMachine. Renamed
`StateMachine::run` as `spawn` and return `StateMachineHandle`.

[1]: https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs/-/merge_requests/793#note_1464400
2022-08-09 19:48:06 +02:00
François Laignel 28a62e622e ts/scheduler: rename awake / wake_up as unpark 2022-08-09 13:17:21 +00:00
François Laignel 833331ab66 ts/Task: wake up after the triggering event is pushed
The scheduler is awaken when aborting a task loop, but not after
a triggering event is pushed. This can cause throttling to induce
long state transitions for pipelines with many streams.

Observed for Unprepare with:

GST_DEBUG=ts-benchmark:4 ../../target/debug/examples/benchmark 2000 ts-udpsrc 2 20 5000
2022-08-09 13:17:21 +00:00
Sebastian Dröge 51c7d0652e Fix/silence a couple new clippy warnings 2022-06-30 16:07:32 +03:00
François Laignel a45f944edd ts/async_wrapper: remove fd from reactor before dropping its handle
The I/O handle was dropped prior to removing it from the reactor,
which caused `Poller::delete` to fail due to an invalid file
descriptor. This used to happen silently unless the same fd was
added again, e.g. by changing states in the pipeline as follow:

    Null -> Playing -> Null -> Playing.

In which case `Poller::add` failed due to an already existing file.

This commit makes sure the fd is removed from the reactor prior to
dropping the handle. In order to achieve this, a new task is spawned
on the `Context` on which the I/O was originally registered, allowing
it to access the proper `Reactor`. The I/O can then safely be dropped.

Because the I/O handle is moved to the spawned future, this solution
requires adding the `Send + 'static` bounds to the I/O handle used
within the `Async` wrapper. This appears not too restrictive for
existing implementations though. Other attempts were considered,
but they would cause deadlocks.

This new approach also solves a potential race condition where a
fd could be re-registered in a `Reactor` before it was removed.
2022-06-30 11:13:39 +00:00
Tim-Philipp Müller 90c203857a threadshare: fix build on Windows 2022-04-27 00:13:46 +01:00
François Laignel 59ca466081 ts: log max throttling when creating Context 2022-03-28 08:47:32 +00:00
François Laignel 8eb8ea0e7d ts/rt/Task: use light weight executor blocking on ack or join handle
Previous version used the Context::block_on_or_add_sub_task which
spawns a full-fledged executor with timer and io Reactor for no
reason when we just need to wait for a Receiver or JoinHandle.
2022-03-28 08:47:32 +00:00
François Laignel c1615d01e6 ts/rt/Task: awake the iteration loop when it needs to be aborted
When the iteration loop is throttling, the call to `abort` on the
`loop_abort_handle` returns immediately, but the actual `Future`
for the iteration loop is aborted only when the scheduler throttling
completes. State transitions which requires the loop to be aborted &
which are serialized at the pipeline level can incur long delays.

This commit makes sure the Task Context's scheduler is awaken as soon
as the task loop is aborted.
2022-03-28 08:47:32 +00:00
François Laignel 72d9d3dc58 generic/threadshare: fix for nightly build 2022-02-22 00:18:28 +01:00
François Laignel 422ea740ca Update to gst::_log_macro_
See the details:
https://gitlab.freedesktop.org/gstreamer/gstreamer-rs/-/merge_requests/980
2022-02-21 20:50:01 +01:00
Sebastian Dröge 51f8e963d6 Add SPDX-License-Identifier to all file headers 2022-01-15 21:18:47 +02:00
François Laignel 64dd588734 ts/runtime/scheduler: check must_awake before sleeping 2022-01-05 19:00:00 +01:00
François Laignel 1573522520 ts/runtime: rewrite runnable loop
Previous version relied on a plain loop / match / break because
I experimented different strategies. The while variant is better
for the final solution.
2022-01-05 18:59:43 +01:00
François Laignel 5e4fc8b138 ts/executor: relax the static bound on enter
The function `enter` is executed in a blocking way from the caller's
point of view. This means that we can guaranty that the provided
function and its output will outlive the underlying Scheduler Task
execution. This requires an unsafe call to
`async_task::spawn_unchecked`. See:

https://docs.rs/async-task/latest/async_task/fn.spawn_unchecked.html
2021-12-25 11:25:56 +00:00
François Laignel 6163589ac7 ts/executor: replace tokio with smol-like implementation
The threadshare executor was based on a modified version of tokio
which implemented the throttling strategy in the BasicScheduler.
Upstream tokio codebase has significantly diverged from what it
was when the throttling strategy was implemented making it hard
to follow. This means that we can hardly get updates from the
upstream project and when we cherry pick fixes, we can't reflect
the state of the project on our fork's version. As a consequence,
tools such as cargo-deny can't check for RUSTSEC fixes in our fork.

The smol ecosystem makes it quite easy to implement and maintain
a custom async executor. This MR imports the smol parts that
need modifications to comply with the threadshare model and implements
a throttling executor in place of the tokio fork.

Networking tokio specific types are replaced with Async wrappers
in the spirit of [smol-rs/async-io]. Note however that the Async
wrappers needed modifications in order to use the per thread
Reactor model. This means that higher level upstream networking
crates such as [async-net] can not be used with our Async
implementation.

Based on the example benchmark with ts-udpsrc, performances seem on par
with what we achieved using the tokio fork.

Fixes https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs/-/issues/118

Related to https://gitlab.freedesktop.org/gstreamer/gst-plugins-rs/-/merge_requests/604
2021-12-25 11:25:56 +00:00
François Laignel db9c38aa93 ts/runtime: shuffle some structs to dedicated modules 2021-12-25 11:25:56 +00:00
François Laignel c5ef83d5b0 ts/runtime: use a directory for executor module
This will ease the introduction of other concepts which are required
for our own executor implementation.
2021-12-25 11:25:56 +00:00
François Laignel cd0773662f ts: migrate most tests so that they don't use tokio 2021-12-25 11:25:56 +00:00
François Laignel 27b9f0d868 Improve usability thanks to opt-ops
The crate option-operations simplifies usage when dealing with
`Option`s, which is often the case with `ClockTime`.
2021-10-18 15:09:47 +02:00
François Laignel ed90b338f8 ts: runtime: add delay_for_at_least
The time driver for the threadshare runtime assigns the timer
entries to the nearest throttling time frame so that the timer
fires as close as possible to the expected instant. This means
that the timer might fire before or after the expected instant
(at most `wait / 2` away).

In some cases, we don't want the timer to fire early. The new
function `delay_for_at_least` ensures that the timer is assigned
to the time frame after the expected instant.
2021-09-30 09:00:05 +02:00
Sebastian Dröge 052365ba1a Fix various needless-borrow clippy warnings and others 2021-07-30 13:53:35 +03:00
François Laignel 8f81cb8812 generic: migrate to new ClockTime design 2021-06-05 10:36:21 +02:00
François Laignel 06accc8d98 fix-getters-{def,calls} pass 2021-04-12 15:57:19 +02:00
Sebastian Dröge 39a75632c8 threadshare: Update for glib subclass API cleanups 2021-03-08 12:50:03 +02:00
Sebastian Dröge 3d617371af Update for macro renames 2020-12-20 20:43:45 +02:00
Sebastian Dröge 1c9c22df0c generic: Update to 2018 edition 2020-11-23 10:28:33 +02:00
Sebastian Dröge df6a229f58 Fix or silence various clippy warnings 2020-11-19 15:31:50 +00:00
Sebastian Dröge af0337c26c generic: Update for subclassing API changes 2020-11-15 18:25:42 +02:00
François Laignel 4eacce80a5 threadshare: runtime: simplify a function thanks to clippy 2020-10-20 23:45:01 +02:00
François Laignel 7c3e69bb4a Fix ClockTime comparisons not being Ord and use saturating_sub
See:
https://gitlab.freedesktop.org/gstreamer/gstreamer-rs/-/merge_requests/607
2020-10-20 23:45:01 +02:00