
Recherche avancée
Autres articles (103)
-
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 (...) -
Formulaire personnalisable
21 juin 2013, parCette page présente les champs disponibles dans le formulaire de publication d’un média et il indique les différents champs qu’on peut ajouter. Formulaire de création d’un Media
Dans le cas d’un document de type média, les champs proposés par défaut sont : Texte Activer/Désactiver le forum ( on peut désactiver l’invite au commentaire pour chaque article ) Licence Ajout/suppression d’auteurs Tags
On peut modifier ce formulaire dans la partie :
Administration > Configuration des masques de formulaire. (...) -
Qu’est ce qu’un masque de formulaire
13 juin 2013, parUn masque de formulaire consiste en la personnalisation du formulaire de mise en ligne des médias, rubriques, actualités, éditoriaux et liens vers des sites.
Chaque formulaire de publication d’objet peut donc être personnalisé.
Pour accéder à la personnalisation des champs de formulaires, il est nécessaire d’aller dans l’administration de votre MediaSPIP puis de sélectionner "Configuration des masques de formulaires".
Sélectionnez ensuite le formulaire à modifier en cliquant sur sont type d’objet. (...)
Sur d’autres sites (3852)
-
Queue in Python processing more than one video at a time ? [closed]
12 novembre 2024, par Mateus CoelhoI have an raspberry pi, that i proccess videos, rotate and put 4 water marks, but, when i run into the raspberry pi, it uses 100% of 4CPUS threads and it reboots. I solved this using -threads 1, to prevent the usage of just one of the 4 CPUS cores, it worked.


I made a Queue to procces one at a time, because i have 4 buttons that trigger the videos. But, when i send more then 3 videos to the Queue, the rasp still reboots, and im monitoring the CPU usage, is 100% for only one of the four CPUS



But, if i send 4 or 5 videos to the thread folder, it completly reboots, and the most awkward, its after the reboot, it made its way to proceed all the videos.



import os
import time
import subprocess
from google.cloud import storage
import shutil

QUEUE_DIR = "/home/abidu/Desktop/ApertaiRemoteClone"
ERROR_VIDEOS_DIR = "/home/abidu/Desktop/ApertaiRemoteClone/ErrorVideos"
CREDENTIALS_PATH = "/home/abidu/Desktop/keys.json"
BUCKET_NAME = "videos-283812"

def is_valid_video(file_path):
 try:
 result = subprocess.run(
 ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path],
 stdout=subprocess.PIPE,
 stderr=subprocess.PIPE
 )
 return result.returncode == 0
 except Exception as e:
 print(f"Erro ao verificar o vídeo: {e}")
 return False

def overlay_images_on_video(input_file, image_files, output_file, positions, image_size=(100, 100), opacity=0.7):
 inputs = ['-i', input_file]
 for image in image_files:
 if image:
 inputs += ['-i', image]
 filter_complex = "[0:v]transpose=2[rotated];"
 current_stream = "[rotated]"
 for i, (x_offset, y_offset) in enumerate(positions):
 filter_complex += f"[{i+1}:v]scale={image_size[0]}:{image_size[1]},format=rgba,colorchannelmixer=aa={opacity}[img{i}];"
 filter_complex += f"{current_stream}[img{i}]overlay={x_offset}:{y_offset}"
 if i < len(positions) - 1:
 filter_complex += f"[tmp{i}];"
 current_stream = f"[tmp{i}]"
 else:
 filter_complex += ""
 command = ['ffmpeg', '-y', '-threads', '1'] + inputs + ['-filter_complex', filter_complex, '-threads', '1', output_file]

 try:
 result = subprocess.run(command, check=True)
 result.check_returncode() # Verifica se o comando foi executado com sucesso
 print(f"Vídeo processado com sucesso: {output_file}")
 except subprocess.CalledProcessError as e:
 print(f"Erro ao processar o vídeo: {e}")
 if "moov atom not found" in str(e):
 print("Vídeo corrompido ou sem o moov atom. Pulando o arquivo.")
 raise # Relança a exceção para ser tratada no nível superior

def process_and_upload_video():
 client = storage.Client.from_service_account_json(CREDENTIALS_PATH)
 bucket = client.bucket(BUCKET_NAME)
 
 while True:
 # Aguarda 10 segundos antes de verificar novos vídeos
 time.sleep(10)

 # Verifica se há arquivos no diretório de fila
 queue_files = [f for f in os.listdir(QUEUE_DIR) if f.endswith(".mp4")]
 
 if queue_files:
 video_file = os.path.join(QUEUE_DIR, queue_files[0]) # Pega o primeiro vídeo na fila
 
 # Define o caminho de saída após o processamento com o mesmo nome do arquivo de entrada
 output_file = os.path.join(QUEUE_DIR, "processed_" + os.path.basename(video_file))
 if not is_valid_video(video_file):
 print(f"Arquivo de vídeo inválido ou corrompido: {video_file}. Pulando.")
 os.remove(video_file) # Remove arquivo corrompido
 continue

 # Processa o vídeo com a função overlay_images_on_video
 try:
 overlay_images_on_video(
 video_file,
 ["/home/abidu/Desktop/ApertaiRemoteClone/Sponsor/image1.png", 
 "/home/abidu/Desktop/ApertaiRemoteClone/Sponsor/image2.png", 
 "/home/abidu/Desktop/ApertaiRemoteClone/Sponsor/image3.png", 
 "/home/abidu/Desktop/ApertaiRemoteClone/Sponsor/image4.png"],
 output_file,
 [(10, 10), (35, 1630), (800, 1630), (790, 15)],
 image_size=(250, 250),
 opacity=0.8
 )
 
 if os.path.exists(output_file):
 blob = bucket.blob(os.path.basename(video_file).replace("-", "/"))
 blob.upload_from_filename(output_file, content_type='application/octet-stream')
 print(f"Uploaded {output_file} to {BUCKET_NAME}")
 os.remove(video_file)
 os.remove(output_file)
 print(f"Processed and deleted {video_file} and {output_file}.")
 
 except subprocess.CalledProcessError as e:
 print(f"Erro ao processar {video_file}: {e}")
 
 move_error_video_to_error_directory(video_file)

 continue # Move para o próximo vídeo na fila após erro

def move_error_video_to_error_directory(video_file):
 print(f"Movendo arquivo de vídeo com erro {video_file} para {ERROR_VIDEOS_DIR}")

 if not os.path.exists(ERROR_VIDEOS_DIR):
 os.makedirs(ERROR_VIDEOS_DIR)
 
 shutil.move(video_file, ERROR_VIDEOS_DIR)

if __name__ == "__main__":
 process_and_upload_video()




-
RTSP to HLS conversion with error on some devices
2 septembre 2024, par Wallace KetlerI'm trying to convert, on a node server, RTSP IP camera devices to HLS to run livestreams on the web. The following code works well for some RTSP devices, but for others I encounter problems.


function startLive(rtspUrl, outputDir, id_local, id_camera) {
 return new Promise((resolve, reject) => {
 const processKey = `${id_local}_${id_camera}`;
 if (ffmpegProcesses[processKey]) {
 return reject(new Error('Conversão já está em andamento para esta câmera'));
 }
 
 const process = ffmpeg(rtspUrl)
 .inputOptions([
 '-rtsp_transport', 'tcp',
 '-fflags', 'nobuffer',
 '-max_delay', '1000000',
 '-analyzeduration', '1000000',
 '-probesize', '1000000',
 '-flush_packets', '1',
 '-avioflags', 'direct'
 ])
 .outputOptions([
 '-c:v', 'libx264',
 '-preset', 'ultrafast',
 '-tune', 'zerolatency',
 '-c:a', 'aac',
 '-hls_time', '10',
 '-hls_flags', 'delete_segments',
 '-hls_list_size', '5',
 '-hls_wrap', '5',
 '-strict', '-2'
 ])
 .output(path.join(outputDir, 'stream.m3u8'))
 .on('start', (commandLine) => {
 console.log('Spawned FFmpeg with command: ' + commandLine);
 })
 .on('stderr', (stderrLine) => {
 console.log('FFmpeg stderr: ' + stderrLine);
 })
 .on('end', () => {
 console.log('Conversão concluída');
 delete ffmpegProcesses[processKey]; 
 resolve();
 })
 .on('error', (err, stdout, stderr) => {
 console.error('Erro na conversão', err);
 console.error('FFmpeg stdout:', stdout);
 console.error('FFmpeg stderr:', stderr);
 delete ffmpegProcesses[processKey]; 
 reject(err);
 })
 .run();
 
 ffmpegProcesses[processKey] = process; 
 });
 }



When the conversion succeeds, it continues indefinitely with the logs :


FFmpeg stderr: frame= 61 fps= 48 q=13.0 size=N/A time=00:00:02.03 bitrate=N/A dup=60 drop=0 speed= 1.6x 
FFmpeg stderr: frame= 75 fps= 42 q=17.0 size=N/A time=00:00:02.52 bitrate=N/A dup=62 drop=0 speed=1.41x 
FFmpeg stderr: frame= 91 fps= 39 q=16.0 size=N/A time=00:00:03.04 bitrate=N/A dup=65 drop=0 speed=1.31x 
FFmpeg stderr: frame= 108 fps= 38 q=15.0 size=N/A time=00:00:03.60 bitrate=N/A dup=68 drop=0 speed=1.27x 
FFmpeg stderr: frame= 121 fps= 36 q=24.0 size=N/A time=00:00:04.03 bitrate=N/A dup=70 drop=0 speed=1.21x 
FFmpeg stderr: frame= 138 fps= 36 q=16.0 size=N/A time=00:00:04.60 bitrate=N/A dup=73 drop=0 speed= 1.2x 
FFmpeg stderr: frame= 152 fps= 35 q=17.0 size=N/A time=00:00:05.08 bitrate=N/A dup=75 drop=0 speed=1.17x 
FFmpeg stderr: frame= 168 fps= 35 q=16.0 size=N/A time=00:00:05.60 bitrate=N/A dup=78 drop=0 speed=1.15x 
FFmpeg stderr: frame= 183 fps= 34 q=21.0 size=N/A time=00:00:06.11 bitrate=N/A dup=80 drop=0 speed=1.13x 
FFmpeg stderr: frame= 198 fps= 34 q=16.0 size=N/A time=00:00:06.60 bitrate=N/A dup=83 drop=0 speed=1.12x 
FFmpeg stderr: frame= 215 fps= 33 q=16.0 size=N/A time=00:00:07.16 bitrate=N/A dup=86 drop=0 speed=1.11x 
FFmpeg stderr: frame= 230 fps= 33 q=16.0 size=N/A time=00:00:07.66 bitrate=N/A dup=88 drop=0 speed= 1.1x 
FFmpeg stderr: frame= 246 fps= 33 q=19.0 size=N/A time=00:00:08.20 bitrate=N/A dup=91 drop=0 speed= 1.1x 



And with the segments saved in the folder configured as output. But for certain devices, after creating the stream.m3u8 file and saving the first segment, the conversion is considered finished and falls into
.on('end')
. The error log is as follows :

FFmpeg stderr: frame= 0 fps=0.0 q=0.0 size=N/A time=00:00:01.12 bitrate=N/A speed=2.08x 
FFmpeg stderr: [hls @ 0x55e00dfc4380] Opening 'my_path/stream0.ts' for writing
FFmpeg stderr: [hls @ 0x55e00dfc4380] Opening 'my_path/stream.m3u8.tmp' for writing
FFmpeg stderr: frame= 0 fps=0.0 q=0.0 Lsize=N/A time=00:00:01.37 bitrate=N/A speed= 2.5x 
FFmpeg stderr: video:0kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
FFmpeg stderr: [aac @ 0x55e00dfff840] Qavg: 65536.000
FFmpeg stderr: 
Conversão concluída



The
muxing overhead: unknown
only appears when the error occurs and the conversion is complete.

I've already tried changing the video and audio encoders, as well as the various input and output parameters of the conversion. I also tried updating ffmpeg (it's already on the latest version, using fluent-ffmpeg,
"fluent-ffmpeg": "^2.1.3",
)

I would like to understand why this happens on some devices and how to fix it. Thanks.


-
Remove audio from specific audio track
9 août 2024, par Ronaldo JúdiceI have this code, and i would like to remove audio from tracks 5 and 6. I had tried everything but is not working, I can mute the audio tracks but on edition program i can see the waves, can you help me ?


if (conv.format === 'mxf') {
 // Add 8 audio tracks
 ffmpeg(inputFile)
 .audioCodec('pcm_s16le') // Codec de áudio para MXF
 .outputOptions([
 '-c:v mpeg2video', // Codec de vídeo para MXF
 '-q:v 2', // Qa vídeo
 '-map 0:v:0', 
 '-map 0:a:0', 
 '-map 0:a:0',
 '-map 0:a:0', 
 '-map 0:a:0', 
 '-map 0:a:0', // this track i want to remove the audio but keep the track
 '-map 0:a:0', //this track i want to remove the audio but keep the track
 '-map 0:a:0', 
 '-map 0:a:0', 
 '-disposition:a:0 default' // Marcar trilha 1 como padrão
 ])
 .save(outputFile)
 .on('start', commandLine => console.log(`FFmpeg comando iniciado: ${commandLine}`))
 .on('progress', progress => console.log(`Progresso: ${progress.percent}%`))
 .on('end', () => console.log(`Conversão concluída: ${outputFile}`))
 .on('error', err => console.error(`Erro na conversão de ${inputFile} para ${outputFile}: ${err.message}`));
 } else {
 // Outras conversões
 ffmpeg(inputFile)
 .outputOptions(conv.options)
 .save(outputFile)
 .on('start', commandLine => console.log(`FFmpeg comando iniciado: ${commandLine}`))
 .on('progress', progress => console.log(`Progresso: ${progress.percent}%`))
 .on('end', () => console.log(`Conversão concluída: ${outputFile}`))
 .on('error', err => console.error(`Erro na conversão de ${inputFile} para ${outputFile}: ${err.message}`));
 }



I tried to use ffmpeg comands to remove audio from track.