jonghwanhyeon / python-ffmpeg

A python binding for FFmpeg which provides sync and async APIs
MIT License
302 stars 52 forks source link

Support asynchronous event handlers for asyncio API #24

Closed sumebrius closed 1 year ago

sumebrius commented 1 year ago

This is probably a re-open of #5 .

Currently ffmpeg.asyncio.FFmpeg inherits from pyee's EventEmitter, which means that only synchronous methods are supported for event handlers.

However, if you inherit from AsyncIOEventEmitter instead, you should be able to support async methods as well without breaking backwards compatibility with existing synchronous method implementations.

jonghwanhyeon commented 1 year ago

I considered to use AsyncIOEventEmitter, but there is a problem.

As stated in the document, AsyncIOEventEmitter emits error event when an exception is raised.

Unlike the case with the EventEmitter, all exceptions raised by event handlers are automatically emitted on the error event. This is important for asyncio coroutines specifically but is also handled for synchronous functions for consistency.

This unfortunately breaks compatibility with the synchronous API.

In the future, I plan to write an EventEmitter from the scratch which supports both synchronous and asynchronous functions with same interface.

sumebrius commented 1 year ago

Ah yes, of course. AsyncIOEventEmitter doesn't re-raise the exception.

The error event passes the exception itself, so as a slightly hacky workaround to maintain compatibility, you could add a listener to catch the exception from the event and re-raise it directly. It would make sense to do this in __init__ with an optional flag to over-ride this behaviour, to avoid explicitly de-registering that listener if you wanted to handle the error event yourself.

sumebrius commented 1 year ago

If you're happy with such an approach, I'd be keen to create a PR implementing it.

jonghwanhyeon commented 1 year ago

Sure, I am totally fine.