
Recherche avancée
Médias (1)
-
The pirate bay depuis la Belgique
1er avril 2013, par
Mis à jour : Avril 2013
Langue : français
Type : Image
Autres articles (8)
-
Encoding and processing into web-friendly formats
13 avril 2011, parMediaSPIP automatically converts uploaded files to internet-compatible formats.
Video files are encoded in MP4, Ogv and WebM (supported by HTML5) and MP4 (supported by Flash).
Audio files are encoded in MP3 and Ogg (supported by HTML5) and MP3 (supported by Flash).
Where possible, text is analyzed in order to retrieve the data needed for search engine detection, and then exported as a series of image files.
All uploaded files are stored online in their original format, so you can (...) -
D’autres logiciels intéressants
12 avril 2011, parOn ne revendique pas d’être les seuls à faire ce que l’on fait ... et on ne revendique surtout pas d’être les meilleurs non plus ... Ce que l’on fait, on essaie juste de le faire bien, et de mieux en mieux...
La liste suivante correspond à des logiciels qui tendent peu ou prou à faire comme MediaSPIP ou que MediaSPIP tente peu ou prou à faire pareil, peu importe ...
On ne les connais pas, on ne les a pas essayé, mais vous pouvez peut être y jeter un coup d’oeil.
Videopress
Site Internet : (...) -
Menus personnalisés
14 novembre 2010, parMediaSPIP utilise le plugin Menus pour gérer plusieurs menus configurables pour la navigation.
Cela permet de laisser aux administrateurs de canaux la possibilité de configurer finement ces menus.
Menus créés à l’initialisation du site
Par défaut trois menus sont créés automatiquement à l’initialisation du site : Le menu principal ; Identifiant : barrenav ; Ce menu s’insère en général en haut de la page après le bloc d’entête, son identifiant le rend compatible avec les squelettes basés sur Zpip ; (...)
Sur d’autres sites (4078)
-
CGO : How do I write to a file in Golang using a pointer to the C data ?
24 avril 2018, par nevernewI’m writing an app for the windows platform using FFmpeg and it’s golang wrapper goav, but I’m having trouble understanding how to use the C pointers to gain access to an array.
I’m trying to write the frame data, pointed to by a uint8 pointer from C, to a .ppm file in golang.
Once I have this done, for proof of concept that FFmpeg is doing what I expect it to, I want to set the frames to a texture in OpenGl to make a video player with cool transitions ; any pointers to do that nice and efficiently would be so very helpful ! I’m guessing I need to write some shader code to draw the ppm as a texture...
I’m starting to understanding how to cast the pointers between C and Go types, but how can I access the data and write it in Go with the same result as C ? In C I just have to set the pointer offset for the data and state how much of it to write :
for (y = 0; y < height; y++) {
fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width*3, pFile);
}I’ve stripped out all the relevant parts of the C code, the wrapper and my code, shown below :
C code - libavutil/frame.h
#include
typedef struct AVFrame {
#define AV_NUM_DATA_POINTERS 8
uint8_t *data[AV_NUM_DATA_POINTERS];
int linesize[AV_NUM_DATA_POINTERS];
}Golang goav wrapper
package avutil
/*
#cgo pkg-config: libavutil
#include <libavutil></libavutil>frame.h>
#include
*/
import "C"
import (
"unsafe"
)
type Frame C.struct_AVFrame
func Data(f *Frame) *uint8 {
return (*uint8)(unsafe.Pointer((*C.uint8_t)(unsafe.Pointer(&f.data))))
}
func Linesize(f *Frame) int {
return int(*(*C.int)(unsafe.Pointer(&f.linesize)))
}My Golang code
package main
import "github.com/giorgisio/goav/avutil"
func saveFrame(videoFrame *avutil.Frame, width int, height int, iFrame int) {
var szFilename string
var y int
var file *os.File
var err error
szFilename = ""
// Open file
szFilename = fmt.Sprintf("frame%d.ppm", iFrame)
if file, err = os.Open(szFilename); err != nil {
log.Println("Error Reading")
}
// Write header
fh := []byte(fmt.Sprintf("P6\n%d %d\n255\n", width, height))
file.Write(fh)
var b byte = 0
// Write pixel data
for y = 0; y < height; y++ {
d := avutil.Data(videoFrame) // d should be a pointer to the first byte of data
l := avutil.Linesize(videoFrame)
// I'm basically lost trying to figure out how to write this to a file
data := make([]byte, width*3)
addr := int(*d) + y*l // figure out the address
for i := 0; i < l; i++ {
// This is where I'm having the problem, I get an "invalid
// memory address or nil pointer dereference" error
byteArrayPtr := (*byte)(unsafe.Pointer(uintptr(addr) + uintptr(i)*unsafe.Sizeof(b)))
data = append(data, *byteArrayPtr)
fmt.Println(*byteArrayPtr)
}
file.Write(data)
}
file.Close()
}So, how can I write to a file using a pointer to the data, like you can do in C ?
-
[ffmpeg][asyncio] main process is held by ffmpeg command
5 octobre 2024, par Michael LopezI created a python program for handling my Arlo Camera. To do that I have been using the
pyaarlo
library (https://github.com/twrecked/pyaarlo) to catch camera's events.
The goal is to monitor if there is an active stream on cameras, get the RTSP stream url and reStream it to a HLS playlist for local usage.

Here the python code :


import asyncio
from decouple import config
import logging
from my_pyaarlo import PyArlo
import urllib.parse
from queue import Queue
import signal

# Read config from ENV (unchanged)
ARLO_USER = config('ARLO_USER')
ARLO_PASS = config('ARLO_PASS')
IMAP_HOST = config('IMAP_HOST')
IMAP_USER = config('IMAP_USER')
IMAP_PASS = config('IMAP_PASS')
DEBUG = config('DEBUG', default=False, cast=bool)
PYAARLO_BACKEND = config('PYAARLO_BACKEND', default=None)
PYAARLO_REFRESH_DEVICES = config('PYAARLO_REFRESH_DEVICES', default=0, cast=int)
PYAARLO_STREAM_TIMEOUT = config('PYAARLO_STREAM_TIMEOUT', default=0, cast=int)
PYAARLO_STORAGE_DIR = config('PYAARLO_STORAGE_DIR', default=None)
PYAARLO_ECDH_CURVE = config('PYAARLO_ECDH_CURVE', default=None)

# Initialize logging
logging.basicConfig(
 level=logging.DEBUG if DEBUG else logging.INFO,
 format='%(asctime)s [%(levelname)s] %(name)s: %(message)s'
)
logger = logging.getLogger(__name__)

ffmpeg_processes = {}
event_queue = Queue()
shutdown_event = asyncio.Event()

async def handle_idle_event(camera):
 logger.info(f"Idle event detected for camera: {camera.name}")
 await stop_ffmpeg_stream(camera.name)

async def get_stream_url(camera):
 try:
 # Attempt to get the stream URL
 stream_url = await asyncio.to_thread(camera.get_stream()
 if stream_url:
 return stream_url
 else:
 logger.warning(f"Unable to get stream URL for {camera.name}. Stream might not be active.")
 return None
 except Exception as e:
 logger.error(f"Error getting stream URL for {camera.name}: {e}")
 return None

async def handle_user_stream_active_event(camera):
 logger.info(f"User stream active event detected for camera: {camera.name}")

 # Get the stream URL
 stream_url = await get_stream_url(camera)
 if stream_url:
 logger.info(f"Stream URL for {camera.name}: {stream_url}")
 await start_ffmpeg_stream(camera.name, stream_url)
 else:
 logger.warning(f"No stream URL available for {camera.name}")

async def event_handler(device, attr, value):
 logger.debug(f"Event: {device.name}, Attribute: {attr}, Value: {value}")
 if attr == 'activityState':
 if value == 'idle':
 await handle_idle_event(device)
 elif value in ['userStreamActive']:
 await handle_user_stream_active_event(device)
 elif attr == 'mediaUploadNotification':
 logger.info(f"Media uploaded for camera: {device.name}")

def sync_event_handler(device, attr, value):
 # This function will be called by PyArlo's synchronous callbacks
 event_queue.put((device, attr, value))

async def process_event_queue():
 while not shutdown_event.is_set():
 try:
 if not event_queue.empty():
 device, attr, value = event_queue.get()
 await event_handler(device, attr, value)
 await asyncio.sleep(0.1) # Small delay to prevent busy-waiting
 except asyncio.CancelledError:
 break
 except Exception as e:
 logger.error(f"Error processing event: {e}")

async def display_status(arlo):
 while not shutdown_event.is_set():
 print("\n--- Camera Statuses ---")
 for camera in arlo.cameras:
 print(f"{camera.name}: {camera.state}")
 print("------------------------")
 await asyncio.sleep(5)

async def start_ffmpeg_stream(camera_name, stream_url):
 if camera_name not in ffmpeg_processes:
 output_hls = f"/tmp/{camera_name}.m3u8"

 try:
 new_url = urllib.parse.quote(stream_url.encode(), safe=':/?&=')
 logger.info(f"NEW_URL: {new_url}")

 ffmpeg_cmd = [
 "ffmpeg", "-hide_banner", "-loglevel", "quiet", "-nostats", "-nostdin", "-y", "-re",
 "-i", new_url,
 "-c:v", "libx264", "-preset", "veryfast",
 "-an", "-sn",
 "-f", "hls", "-hls_time", "4", "-hls_list_size", "10",
 "-hls_flags", "delete_segments", output_hls,
 ]
 logger.info(f"Starting FFmpeg command: {ffmpeg_cmd}")
 
 process = await asyncio.create_subprocess_exec(
 *ffmpeg_cmd,
 stdout=asyncio.subprocess.DEVNULL,
 stderr=asyncio.subprocess.DEVNULL
 )
 ffmpeg_processes[camera_name] = process
 logger.info(f"Started ffmpeg process with PID: {process.pid}")

 except Exception as e:
 logger.error(f"Error starting FFmpeg for {camera_name}: {e}")

async def stop_ffmpeg_stream(camera_name):
 logger.info(f"Stopping ffmpeg process for {camera_name}")
 ffmpeg_process = ffmpeg_processes.pop(camera_name, None)
 if ffmpeg_process:
 ffmpeg_process.terminate()

 try:
 await ffmpeg_process.wait()
 logger.info(f"{camera_name} stopped successfully")
 except Exception as e:
 print(f"FFMPEG Process didn't stop in time, forcefully terminating: {e}")
 ffmpeg_process.kill()
 else:
 logger.info(f"FFmpeg process for {camera_name} already stopped")

async def shutdown(signal, loop):
 logger.info(f"Received exit signal {signal.name}...")
 shutdown_event.set()
 tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
 [task.cancel() for task in tasks]
 logger.info(f"Cancelling {len(tasks)} outstanding tasks")
 await asyncio.gather(*tasks, return_exceptions=True)
 loop.stop()

async def main():
 # Initialize PyArlo
 arlo_args = {
 'username': ARLO_USER,
 'password': ARLO_PASS,
 'tfa_source': 'imap',
 'tfa_type': 'email',
 'tfa_host': IMAP_HOST,
 'tfa_username': IMAP_USER,
 'tfa_password': IMAP_PASS,
 'save_session': True,
 'verbose_debug': DEBUG
 }

 # Add optional arguments
 for arg, value in [
 ('refresh_devices_every', PYAARLO_REFRESH_DEVICES),
 ('stream_timeout', PYAARLO_STREAM_TIMEOUT),
 ('backend', PYAARLO_BACKEND),
 ('storage_dir', PYAARLO_STORAGE_DIR),
 ('ecdh_curve', PYAARLO_ECDH_CURVE)
 ]:
 if value:
 arlo_args[arg] = value
 
 try:
 arlo = await asyncio.to_thread(PyArlo, **arlo_args)
 except Exception as e:
 logger.error(f"Failed to initialize PyArlo: {e}")
 return

 logger.info("Connected to Arlo. Monitoring events...")

 # Register event handlers for each camera
 for camera in arlo.cameras:
 camera.add_attr_callback('*', sync_event_handler)

 # Start the status display task
 status_task = asyncio.create_task(display_status(arlo))

 # Start the event processing task
 event_processing_task = asyncio.create_task(process_event_queue())

 # Set up signal handlers
 loop = asyncio.get_running_loop()
 for s in (signal.SIGHUP, signal.SIGTERM, signal.SIGINT):
 loop.add_signal_handler(
 s, lambda s=s: asyncio.create_task(shutdown(s, loop)))

 try:
 # Keep the main coroutine running
 while not shutdown_event.is_set():
 try:
 await asyncio.sleep(1)
 except asyncio.CancelledError:
 break
 except Exception as e:
 logger.error(f"Unexpected error in main loop: {e}")
 finally:
 logger.info("Shutting down...")
 for camera_name in list(ffmpeg_processes.keys()):
 await stop_ffmpeg_stream(camera_name)
 
 # Cancel and wait for all tasks
 tasks = [status_task, event_processing_task]
 for task in tasks:
 if not task.done():
 task.cancel()
 await asyncio.gather(*tasks, return_exceptions=True)
 
 logger.info("Program terminated.")

if __name__ == "__main__":
 try:
 asyncio.run(main())
 except KeyboardInterrupt:
 logger.info("Keyboard interrupt received. Exiting.")
 except Exception as e:
 logger.error(f"Unhandled exception: {e}")
 finally:
 logger.info("Program exit complete.")



My issue is about the ffmpeg command which is hold the main process (or the event loop) when it runs, blocking the events coming from the pyaarlo library. The state of the camera continues to work with the good information.


I tried lot of things, without asyncio, with multiprocessing, with subprocess, ... the behavior is always the same. In some cases, I received the idle event after the key interrupt.


Another information :


- 

- When I stop the active stream, the event is not received but when I start the stream just after, that event is received.
- When I run the same ffmpeg command but with a local long video file, everything is Ok. So, it why I guess that the ffmpeg command is impacting the main process.






I succedeed in running the ffmpeg command with rtsp url stream but without a loop event monitoring :


import asyncio
import signal
import sys
import os

async def run_infinite_command():
 # Start a simple HTTP server as our "infinite" command
 url = "rstp://localhost:8554/camera1/stream" # it is a fake url
 ffmpeg_cmd = [
 "ffmpeg", "-re", "-i", url,
 "-c:v", "libx264", "-preset", "veryfast",
 "-c:a", "copy",
 "-f", "hls", "-hls_time", "4", "-hls_list_size", "10",
 "-hls_flags", "delete_segments", "/tmp/output.m3u8"
 ]
 
 process = await asyncio.create_subprocess_exec(
 *ffmpeg_cmd,
 stdout=asyncio.subprocess.DEVNULL,
 stderr=asyncio.subprocess.DEVNULL
 )
 
 print(f"Started HTTP server with PID: {process.pid}")
 return process

async def main():
 # Start the infinite command
 process = await run_infinite_command()

 # Run the main loop for a few seconds
 for i in range(10):
 print(f"Main loop iteration {i+1}")
 await asyncio.sleep(1)

 # Stop the infinite command
 print("Stopping the HTTP server...")
 if sys.platform == "win32":
 # On Windows, we need to use CTRL_C_EVENT
 os.kill(process.pid, signal.CTRL_C_EVENT)
 else:
 # On Unix-like systems, we can use SIGTERM
 process.send_signal(signal.SIGTERM)

 # Wait for the process to finish
 try:
 await asyncio.wait_for(process.wait(), timeout=5.0)
 print("HTTP server stopped successfully")
 except asyncio.TimeoutError:
 print("HTTP server didn't stop in time, forcefully terminating")
 process.kill()

 print("Program finished")

if __name__ == "__main__":
 asyncio.run(main())



With this script, the ffmpeg command is correctly launched and terminated after the for loop.


Could you help ?


-
Main process is held by ffmpeg command
6 octobre 2024, par Michael LopezI created a python program for handling my Arlo Camera. To do that I have been using the
pyaarlo
library (https://github.com/twrecked/pyaarlo) to catch camera's events.
The goal is to monitor if there is an active stream on cameras, get the RTSP stream url and reStream it to a HLS playlist for local usage.

Here the python code :


import asyncio
from decouple import config
import logging
from my_pyaarlo import PyArlo
import urllib.parse
from queue import Queue
import signal

# Read config from ENV (unchanged)
ARLO_USER = config('ARLO_USER')
ARLO_PASS = config('ARLO_PASS')
IMAP_HOST = config('IMAP_HOST')
IMAP_USER = config('IMAP_USER')
IMAP_PASS = config('IMAP_PASS')
DEBUG = config('DEBUG', default=False, cast=bool)
PYAARLO_BACKEND = config('PYAARLO_BACKEND', default=None)
PYAARLO_REFRESH_DEVICES = config('PYAARLO_REFRESH_DEVICES', default=0, cast=int)
PYAARLO_STREAM_TIMEOUT = config('PYAARLO_STREAM_TIMEOUT', default=0, cast=int)
PYAARLO_STORAGE_DIR = config('PYAARLO_STORAGE_DIR', default=None)
PYAARLO_ECDH_CURVE = config('PYAARLO_ECDH_CURVE', default=None)

# Initialize logging
logging.basicConfig(
 level=logging.DEBUG if DEBUG else logging.INFO,
 format='%(asctime)s [%(levelname)s] %(name)s: %(message)s'
)
logger = logging.getLogger(__name__)

ffmpeg_processes = {}
event_queue = Queue()
shutdown_event = asyncio.Event()

async def handle_idle_event(camera):
 logger.info(f"Idle event detected for camera: {camera.name}")
 await stop_ffmpeg_stream(camera.name)

async def get_stream_url(camera):
 try:
 # Attempt to get the stream URL
 stream_url = await asyncio.to_thread(camera.get_stream()
 if stream_url:
 return stream_url
 else:
 logger.warning(f"Unable to get stream URL for {camera.name}. Stream might not be active.")
 return None
 except Exception as e:
 logger.error(f"Error getting stream URL for {camera.name}: {e}")
 return None

async def handle_user_stream_active_event(camera):
 logger.info(f"User stream active event detected for camera: {camera.name}")

 # Get the stream URL
 stream_url = await get_stream_url(camera)
 if stream_url:
 logger.info(f"Stream URL for {camera.name}: {stream_url}")
 await start_ffmpeg_stream(camera.name, stream_url)
 else:
 logger.warning(f"No stream URL available for {camera.name}")

async def event_handler(device, attr, value):
 logger.debug(f"Event: {device.name}, Attribute: {attr}, Value: {value}")
 if attr == 'activityState':
 if value == 'idle':
 await handle_idle_event(device)
 elif value in ['userStreamActive']:
 await handle_user_stream_active_event(device)
 elif attr == 'mediaUploadNotification':
 logger.info(f"Media uploaded for camera: {device.name}")

def sync_event_handler(device, attr, value):
 # This function will be called by PyArlo's synchronous callbacks
 event_queue.put((device, attr, value))

async def process_event_queue():
 while not shutdown_event.is_set():
 try:
 if not event_queue.empty():
 device, attr, value = event_queue.get()
 await event_handler(device, attr, value)
 await asyncio.sleep(0.1) # Small delay to prevent busy-waiting
 except asyncio.CancelledError:
 break
 except Exception as e:
 logger.error(f"Error processing event: {e}")

async def display_status(arlo):
 while not shutdown_event.is_set():
 print("\n--- Camera Statuses ---")
 for camera in arlo.cameras:
 print(f"{camera.name}: {camera.state}")
 print("------------------------")
 await asyncio.sleep(5)

async def start_ffmpeg_stream(camera_name, stream_url):
 if camera_name not in ffmpeg_processes:
 output_hls = f"/tmp/{camera_name}.m3u8"

 try:
 new_url = urllib.parse.quote(stream_url.encode(), safe=':/?&=')
 logger.info(f"NEW_URL: {new_url}")

 ffmpeg_cmd = [
 "ffmpeg", "-hide_banner", "-loglevel", "quiet", "-nostats", "-nostdin", "-y", "-re",
 "-i", new_url,
 "-c:v", "libx264", "-preset", "veryfast",
 "-an", "-sn",
 "-f", "hls", "-hls_time", "4", "-hls_list_size", "10",
 "-hls_flags", "delete_segments", output_hls,
 ]
 logger.info(f"Starting FFmpeg command: {ffmpeg_cmd}")
 
 process = await asyncio.create_subprocess_exec(
 *ffmpeg_cmd,
 stdout=asyncio.subprocess.DEVNULL,
 stderr=asyncio.subprocess.DEVNULL
 )
 ffmpeg_processes[camera_name] = process
 logger.info(f"Started ffmpeg process with PID: {process.pid}")

 except Exception as e:
 logger.error(f"Error starting FFmpeg for {camera_name}: {e}")

async def stop_ffmpeg_stream(camera_name):
 logger.info(f"Stopping ffmpeg process for {camera_name}")
 ffmpeg_process = ffmpeg_processes.pop(camera_name, None)
 if ffmpeg_process:
 ffmpeg_process.terminate()

 try:
 await ffmpeg_process.wait()
 logger.info(f"{camera_name} stopped successfully")
 except Exception as e:
 print(f"FFMPEG Process didn't stop in time, forcefully terminating: {e}")
 ffmpeg_process.kill()
 else:
 logger.info(f"FFmpeg process for {camera_name} already stopped")

async def shutdown(signal, loop):
 logger.info(f"Received exit signal {signal.name}...")
 shutdown_event.set()
 tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
 [task.cancel() for task in tasks]
 logger.info(f"Cancelling {len(tasks)} outstanding tasks")
 await asyncio.gather(*tasks, return_exceptions=True)
 loop.stop()

async def main():
 # Initialize PyArlo
 arlo_args = {
 'username': ARLO_USER,
 'password': ARLO_PASS,
 'tfa_source': 'imap',
 'tfa_type': 'email',
 'tfa_host': IMAP_HOST,
 'tfa_username': IMAP_USER,
 'tfa_password': IMAP_PASS,
 'save_session': True,
 'verbose_debug': DEBUG
 }

 # Add optional arguments
 for arg, value in [
 ('refresh_devices_every', PYAARLO_REFRESH_DEVICES),
 ('stream_timeout', PYAARLO_STREAM_TIMEOUT),
 ('backend', PYAARLO_BACKEND),
 ('storage_dir', PYAARLO_STORAGE_DIR),
 ('ecdh_curve', PYAARLO_ECDH_CURVE)
 ]:
 if value:
 arlo_args[arg] = value
 
 try:
 arlo = await asyncio.to_thread(PyArlo, **arlo_args)
 except Exception as e:
 logger.error(f"Failed to initialize PyArlo: {e}")
 return

 logger.info("Connected to Arlo. Monitoring events...")

 # Register event handlers for each camera
 for camera in arlo.cameras:
 camera.add_attr_callback('*', sync_event_handler)

 # Start the status display task
 status_task = asyncio.create_task(display_status(arlo))

 # Start the event processing task
 event_processing_task = asyncio.create_task(process_event_queue())

 # Set up signal handlers
 loop = asyncio.get_running_loop()
 for s in (signal.SIGHUP, signal.SIGTERM, signal.SIGINT):
 loop.add_signal_handler(
 s, lambda s=s: asyncio.create_task(shutdown(s, loop)))

 try:
 # Keep the main coroutine running
 while not shutdown_event.is_set():
 try:
 await asyncio.sleep(1)
 except asyncio.CancelledError:
 break
 except Exception as e:
 logger.error(f"Unexpected error in main loop: {e}")
 finally:
 logger.info("Shutting down...")
 for camera_name in list(ffmpeg_processes.keys()):
 await stop_ffmpeg_stream(camera_name)
 
 # Cancel and wait for all tasks
 tasks = [status_task, event_processing_task]
 for task in tasks:
 if not task.done():
 task.cancel()
 await asyncio.gather(*tasks, return_exceptions=True)
 
 logger.info("Program terminated.")

if __name__ == "__main__":
 try:
 asyncio.run(main())
 except KeyboardInterrupt:
 logger.info("Keyboard interrupt received. Exiting.")
 except Exception as e:
 logger.error(f"Unhandled exception: {e}")
 finally:
 logger.info("Program exit complete.")



My issue is about the ffmpeg command which is hold the main process (or the event loop) when it runs, blocking the events coming from the pyaarlo library. The state of the camera continues to work with the good information.


I tried lot of things, without asyncio, with multiprocessing, with subprocess, ... the behavior is always the same. In some cases, I received the idle event after the key interrupt.


Another information :


- 

- When I stop the active stream, the event is not received but when I start the stream just after, that event is received.
- When I run the same ffmpeg command but with a local long video file, everything is Ok. So, it why I guess that the ffmpeg command is impacting the main process.






I succedeed in running the ffmpeg command with rtsp url stream but without a loop event monitoring :


import asyncio
import signal
import sys
import os

async def run_infinite_command():
 # Start a simple HTTP server as our "infinite" command
 url = "rstp://localhost:8554/camera1/stream" # it is a fake url
 ffmpeg_cmd = [
 "ffmpeg", "-re", "-i", url,
 "-c:v", "libx264", "-preset", "veryfast",
 "-c:a", "copy",
 "-f", "hls", "-hls_time", "4", "-hls_list_size", "10",
 "-hls_flags", "delete_segments", "/tmp/output.m3u8"
 ]
 
 process = await asyncio.create_subprocess_exec(
 *ffmpeg_cmd,
 stdout=asyncio.subprocess.DEVNULL,
 stderr=asyncio.subprocess.DEVNULL
 )
 
 print(f"Started HTTP server with PID: {process.pid}")
 return process

async def main():
 # Start the infinite command
 process = await run_infinite_command()

 # Run the main loop for a few seconds
 for i in range(10):
 print(f"Main loop iteration {i+1}")
 await asyncio.sleep(1)

 # Stop the infinite command
 print("Stopping the HTTP server...")
 if sys.platform == "win32":
 # On Windows, we need to use CTRL_C_EVENT
 os.kill(process.pid, signal.CTRL_C_EVENT)
 else:
 # On Unix-like systems, we can use SIGTERM
 process.send_signal(signal.SIGTERM)

 # Wait for the process to finish
 try:
 await asyncio.wait_for(process.wait(), timeout=5.0)
 print("HTTP server stopped successfully")
 except asyncio.TimeoutError:
 print("HTTP server didn't stop in time, forcefully terminating")
 process.kill()

 print("Program finished")

if __name__ == "__main__":
 asyncio.run(main())



With this script, the ffmpeg command is correctly launched and terminated after the for loop.


Could you help ?