
Recherche avancée
Autres articles (18)
-
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 (...) -
Demande de création d’un canal
12 mars 2010, parEn fonction de la configuration de la plateforme, l’utilisateur peu avoir à sa disposition deux méthodes différentes de demande de création de canal. La première est au moment de son inscription, la seconde, après son inscription en remplissant un formulaire de demande.
Les deux manières demandent les mêmes choses fonctionnent à peu près de la même manière, le futur utilisateur doit remplir une série de champ de formulaire permettant tout d’abord aux administrateurs d’avoir des informations quant à (...) -
Installation en mode ferme
4 février 2011, parLe mode ferme permet d’héberger plusieurs sites de type MediaSPIP en n’installant qu’une seule fois son noyau fonctionnel.
C’est la méthode que nous utilisons sur cette même plateforme.
L’utilisation en mode ferme nécessite de connaïtre un peu le mécanisme de SPIP contrairement à la version standalone qui ne nécessite pas réellement de connaissances spécifique puisque l’espace privé habituel de SPIP n’est plus utilisé.
Dans un premier temps, vous devez avoir installé les mêmes fichiers que l’installation (...)
Sur d’autres sites (4489)
-
How to fetch from Node Js once
6 septembre 2023, par OffeyicialI want to trim a video if it is longer than 10 minutes and fetch the trimmed video but it happens to work in an infinite loop, which is what i am trying to stop. i just dont know how


- 

-
Initially, the video processing is triggered when a video longer than 10 minutes is selected.


-
While the video processing is ongoing, the user interface (UI) code continues to execute, and if the video selection remains the same, it might trigger the processing again


-
This leads to multiple instances of FFmpeg processing the same video file concurrently, creating the infinite loop behavior.










function previewReels(event) {
 const videos = document.getElementById('videos').files;
 const previewItems = document.querySelector('.preview-items');
 const buttons = document.querySelector('.buttons');

 // Display videos
 for (let i = 0; i < videos.length; i++) {
 // const videoElement = document.createElement('video');
 // videoElement.controls = true;
 // videoElement.autoplay = true;
 const previewItem = document.createElement('div');
 previewItem.className = 'preview-item';
 previewItems.appendChild(previewItem);

 const formData = new FormData();

 const videoInput = document.getElementById('videos');

 if (videoInput.files.length > 0) {
 const videoFile = videoInput.files[0];
 console.log('VideoFile:', videoFile);
 console.log('Uploaded file mimetype:', videoFile.type);

 formData.append('Video', videoFile);

 const videoElement = document.createElement('video');
 videoElement.src = URL.createObjectURL(videoFile);

 videoElement.addEventListener('loadedmetadata', () => {
 const videoDuration = videoElement.duration;
 const videoinmins = videoDuration / 60;
 console.log('Video Duration:', videoinmins);

 if (videoDuration > 600) {
 videoElement.style.display = "none";
 const loader = document.createElement('img');
 loader.src = 'icons/internet.gif';
 loader.classList.add('loader');
 previewItems.style.backgroundColor = "white";
 previewItem.appendChild(loader);

 fetch('http://localhost:8888/trimVideo', {
 method: 'POST',
 body: formData,
 })
 .then((response) => {
 if (!response.ok) {
 throw new Error('Error fetching trimmed video data.');
 }
 return response.blob(); // Get the video data as a Blob
 })
 .then((videoBlob) => {
 previewItem.removeChild(loader);
 videoElement.style.display = "block";
 loader.style.display = "none";
 buttons.style.display = "block";
 const trimmedVideoURL = URL.createObjectURL(videoBlob);
 videoElement.src = trimmedVideoURL;
 previewItem.appendChild(videoElement);
 previewItem.style.backgroundColor = "#333";
 })
 .catch((error) => {
 console.error(error);
 });
 } else {
 videoElement.controls = true;
 buttons.style.display = "block";
 previewItems.style.backgroundColor = "#333";
 previewItem.appendChild(videoElement);
 }
 });
 }

 // Listen for file selection change
 document.getElementById('videos').addEventListener('change', previewReels);



and for this server side


app.post("/trimVideo", (req, res) => {
 console.log("Received a POST request to /trim-video");
 res.header("Access-Control-Allow-Origin", "*");
 res.header(
 "Access-Control-Allow-Headers",
 "Origin, X-Requested-With, Content-Type, Accept"
 );
 // Access the video file and log its details
 const videoFile = req.files.Video;
 console.log("Received video file:", videoFile);
 console.log(" - Name:", videoFile.name);
 console.log(" - Type:", videoFile.mimetype);
 console.log(" - Size:", videoFile.size, "bytes");
 console.log(" - Data length:", videoFile.data.length);

 if (!req.files || !req.files.Video) {
 console.log("not working");
 return res.status(400).send("No video file uploaded.");
 }

 console.log("started");

 if (videoFile.mimetype.startsWith("video/")) {
 const progressFilePath = 'progress.txt';
 fs.writeFileSync(videoFile.name, videoFile.data);
 const inputFormat = videoFile.name.split(".").pop().toLowerCase();
 console.log("Trimming video...");
 console.log(inputFormat);
 console.log(videoFile.data);
 ffmpeg()
 .input(videoFile.name)
 .inputFormat(inputFormat)
 .outputOptions("-t 600")
 .outputFormat("ismv")
 .on("end", () => {
 console.log("Video trimming completed.");

 // Read the trimmed video data from the temporary file
 const trimmedVideoBuffer = fs.readFileSync(videoFile.name);

 // Delete the temporary file
 fs.unlinkSync(videoFile.name);

 res.setHeader("Content-Type", "Video/ismv");
 res.setHeader("Content-Length", trimmedVideoBuffer.length);
 res.send(trimmedVideoBuffer);
 })
 .on("error", (err, stdout, stderr) => {
 console.error("Error trimming video:", err);
 console.error("FFmpeg stdout:", stdout);
 console.error("FFmpeg stderr:", stderr);
 res.status(500).send(`Error trimming the video: ${err.message}`);
 })
 .on("progress", (progress) => {
 console.log("trimming-progress", progress);
 })
 .save(progressFilePath);
 } else {
 res.status(400).send("Invalid video file format.");
 }
});





-
-
Discord music bot doesn't play songs
9 octobre 2023, par Gam3rsCZI have made myself a discord bot that also plays music(it's only for my server so strings with messages are in Czech, but code is in English).
Bot worked a while ago but now it stopped, and I don't know where the problem is


I'm getting these errors : HTTP error 403 Forbidden Server returned 403 Forbidden (access denied) and
C :\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\player.py:711 : RuntimeWarning : coroutine 'music_cog.play_next' was never awaited
self.after(error)
RuntimeWarning : Enable tracemalloc to get the object allocation traceback
[2023-10-09 16:23:47] [INFO ] discord.player : ffmpeg process 17496 successfully terminated with return code of 1.
INFO : ffmpeg process 17496 successfully terminated with return code of 1.


My code is :


import discord
from discord.ext import commands
from yt_dlp import YoutubeDL

class music_cog(commands.Cog):
 def __init__(self, bot):
 self.bot = bot

 self.is_playing = False
 self.is_paused = False
 self.current = ""

 self.music_queue = []
 self.YDL_OPTIONS = {"format": "m4a/bestaudio/best", "noplaylist": "True"}
 self.FFMPEG_OPTIONS = {"before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5", "options": "-vn"}

 self.vc = None

 def search_yt(self, item):
 with YoutubeDL(self.YDL_OPTIONS) as ydl:
 try:
 info = ydl.extract_info("ytsearch:%s" % item, download=False)["entries"][0]
 except Exception:
 return False
 info = ydl.sanitize_info(info)
 url = info['url']
 title = info['title']
 return {'title': title, 'source': url}

 async def play_next(self):
 if len(self.music_queue) > 0:
 self.is_playing = True
 self.current = self.music_queue[0][0]["title"]
 m_url = self.music_queue[0][0]["source"]

 self.music_queue.pop(0)

 await self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
 else:
 self.is_playing = False

 async def play_music(self, ctx):
 try:
 if len(self.music_queue) > 0:
 self.is_playing = True
 m_url = self.music_queue[0][0]["source"]

 if self.vc == None or not self.vc.is_connected():
 self.vc = await self.music_queue[0][1].connect()

 if self.vc == None:
 await ctx.send("Nepodařilo se připojit do hlasového kanálu.")
 return
 else:
 await self.vc.move_to(self.music_queue[0][1])

 self.current = self.music_queue[0][0]["title"]
 self.music_queue.pop(0)

 self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
 else:
 self.is_playing = False

 except:
 print("Something went wrong")
 await ctx.send(content="Něco se pokazilo")

 @commands.command(name="play", help="Plays selected song from YouTube")
 async def play(self, ctx, *args):
 query = " ".join(args)

 voice_channel = ctx.author.voice.channel
 if voice_channel is None:
 await ctx.send("Připojte se do hlasového kanálu!")
 elif self.is_paused:
 self.vc.resume()
 else:
 song = self.search_yt(query)
 if type(song) == type(True):
 await ctx.send("Písničku se nepodařilo stáhnout. Špatný formát, možná jste se pokusili zadat playlist nebo livestream.")
 else:
 await ctx.send("Písnička přidána do řady.")
 self.music_queue.append([song, voice_channel])

 if self.is_playing == False:
 await self.play_music(ctx)
 self.is_playing = True

 @commands.command(name="pause", aliases=["p"], help="Pauses the BOT")
 async def pause(self, ctx, *args):
 if self.is_playing:
 self.is_playing = False
 self.is_paused = True
 self.vc.pause()
 await ctx.send(content="Písnička byla pozastavena.")
 
 elif self.is_paused:
 self.is_playing = True
 self.is_paused = False
 self.vc.resume()
 await ctx.send(content="Písnička byla obnovena.")

 @commands.command(name="resume", aliases=["r"], help="Resumes playing")
 async def resume(self, ctx, *args):
 if self.is_paused:
 self.is_paused = False
 self.is_playing = True
 self.vc.resume()
 await ctx.send(content="Písnička byla obnovena.")

 @commands.command(name="skip", aliases=["s"], help="Skips current song")
 async def skip(self, ctx, *args):
 if self.vc != None and self.vc:
 self.vc.stop()
 await self.play_next()
 await ctx.send(content="Písnička byla přeskočena.")

 @commands.command(name="queue", aliases=["q"], help="Displays song queue")
 async def queue(self, ctx, songs=5):
 retval = ""

 for i in range(0, len(self.music_queue)):
 if i > songs: break
 retval += " " + self.music_queue[i][0]["title"] + "\n"

 if retval != "":
 retval += "```"
 await ctx.send(content=("```Aktuální fronta:\n" + retval))
 else:
 await ctx.send("Řada je prázdná.")

 @commands.command(name="clear", help="Clears the queue")
 async def clear(self, ctx):
 if self.vc != None and self.is_playing:
 self.vc.stop()
 self.music_queue = []
 await ctx.send("Řada byla vymazána.")

 @commands.command(name="leave", aliases=["dc", "disconnect"], help="Disconnects the BOT")
 async def leave(self, ctx):
 self.is_playing = False
 self.is_paused = False

 if self.vc != None:
 return await self.vc.disconnect(), await ctx.send(content="BOT byl odpojen.")

 else:
 return await ctx.send("BOT není nikde připojen.")
 
 @commands.command(name="current", help="Displays the current song")
 async def current(self, ctx):
 current = self.current
 retval = f"```Právě hraje:\n {current}```"
 if current != "":
 await ctx.send(retval)
 else:
 await ctx.send("Aktuálně nic nehraje.")



I already tried everything I can think of(which isn't a lot because I suck at programming), and also tried searching for some solution on the internet, but nothing worked.


-
Unable to extract KLV data from .mpg file
2 novembre 2023, par Arjun ShastryI need to extract the klv data embedded in the following file :
https://samples.ffmpeg.org/MPEG2/mpegts-klv/Day%20Flight.mpg


Currently, I am doing it using ffmpeg and python.
The code works for .ts files like the example given below, but not the above mpg file. :
https://www.arcgis.com/home/item.html?id=55ec6f32d5e342fcbfba376ca2cc409a


I used the following python command, using subprocess, ffmpeg to extract klv data in a binary file and then using klvdata library to tranlate to a readable text file.


#Extract klv data and output as binary file
command=['ffmpeg', '-i', input_video, '-map', 'd','-codec','copy','-f', 'data','out.bin']
process=subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()

print(stdout)
print(stderr)

#Open text file to write json data
outjson=open("./outjson.txt","w")
print("Flag 1")

# Open the out.bin file for reading as binary
with open("./out.bin", "rb") as f:
 sample=[]
 cnt=0
 for packet in klvdata.streamparser.StreamParser(f):
 pack=[]
 metadata = packet.MetadataList()
 for i in (5,6,7,13,14,15,18,19,23,24,25,26,27,28,29,30,31,32,33):#Only extracting required data
 pack.append(metadata[i][-1])
 sample.append(pack)
 sampleLength=(len(sample))
 json.dump(sample,outjson,indent=4) # Convert the metadata to a string and write it to outtext.txt



When doing it for "Day Flight.mpg", the following error occurs :


58. 19.100 / 58. 19.100\r\n libavcodec 60. 26.100 / 60. 26.100\r\n libavformat 60. 11.100 / 60. 11.100\r\n libavdevice 60. 2.101 / 60. 2.101\r\n libavfilter 9. 11.100 / 9. 11.100\r\n libswscale 7. 3.100 / 7. 3.100\r\n libswresample 4. 11.100 / 4. 11.100\r\n libpostproc 57. 2.100 / 57. 2.100\r\n[mpegts @ 0000026bb99387c0] start time for stream 1 is not set in estimate_timings_from_pts\r\nInput #0, mpegts, from 'C:/Users/ashastry/Downloads/Day Flight.mpg':\r\n Duration: 00:03:14.88, start: 10.000000, bitrate: 4187 kb/s\r\n Program 1 \r\n Stream #0:0[0x1e1]: Video: h264 (Main) ([27][0][0][0] / 0x001B), yuv420p(progressive), 1280x720, 60 fps, 60 tbr, 90k tbn\r\n Stream #0:1[0x1f1]: Data: klv (KLVA / 0x41564C4B)\r\nOutput #0, data, to 'out.bin':\r\n Metadata:\r\n encoder : Lavf60.11.100\r\n Stream #0:0: Data: klv (KLVA / 0x41564C4B)\r\nStream mapping:\r\n Stream #0:1 -> #0:0 (copy)\r\nPress [q] to stop, [?] for help\r\nsize= 0kB time=00:00:00.00 bitrate=N/A speed=N/A \rsize= 0kB time=00:00:00.00 bitrate=N/A speed= 0x \rsize= 1kB time=00:00:00.00 bitrate=N/A speed= 0x \r[out#0/data @ 0000026bbb61b300] video:0kB audio:0kB subtitle:0kB other streams:1kB global headers:0kB muxing overhead: 0.000000%\r\nsize= 1kB time=00:00:00.00 bitrate=N/A speed= 0x \r\n"
Flag 1
Traceback (most recent call last):

 File C:\ProgramData\anaconda3\Lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
 exec(code, globals, locals)

 File c:\users\ashastry\desktop\gis\javascript\extract.py:34
 metadata = packet.MetadataList()

AttributeError: 'UnknownElement' object has no attribute 'MetadataList'