
Recherche avancée
Autres articles (48)
-
Websites made with MediaSPIP
2 mai 2011, parThis page lists some websites based on MediaSPIP.
-
Creating farms of unique websites
13 avril 2011, parMediaSPIP platforms can be installed as a farm, with a single "core" hosted on a dedicated server and used by multiple websites.
This allows (among other things) : implementation costs to be shared between several different projects / individuals rapid deployment of multiple unique sites creation of groups of like-minded sites, making it possible to browse media in a more controlled and selective environment than the major "open" (...) -
Publier sur MédiaSpip
13 juin 2013Puis-je poster des contenus à partir d’une tablette Ipad ?
Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir
Sur d’autres sites (6598)
-
Things I Have Learned About Emscripten
1er septembre 2015, par Multimedia Mike — Cirrus Retro3 years ago, I released my Game Music Appreciation project, a website with a ludicrously uninspired title which allowed users a relatively frictionless method to experience a range of specialized music files related to old video games. However, the site required use of a special Chrome plugin. Ever since that initial release, my #1 most requested feature has been for a pure JavaScript version of the music player.
“Impossible !” I exclaimed. “There’s no way JS could ever run fast enough to run these CPU emulators and audio synthesizers in real time, and allow for the visualization that I demand !” Well, I’m pleased to report that I have proved me wrong. I recently quietly launched a new site with what I hope is a catchier title, meant to evoke a cloud-based retro-music-as-a-service product : Cirrus Retro. Right now, it’s basically the same as the old site, but without the wonky Chrome-specific technology.
Along the way, I’ve learned a few things about using Emscripten that I thought might be useful to share with other people who wish to embark on a similar journey. This is geared more towards someone who has a stronger low-level background (such as C/C++) vs. high-level (like JavaScript).
General Goals
Do you want to cross-compile an entire desktop application, one that relies on an extensive GUI toolkit ? That might be difficult (though I believe there is a path for porting qt code directly with Emscripten). Your better wager might be to abstract out the core logic and processes of the program and then create a new web UI to access them.Do you want to compile a game that basically just paints stuff to a 2D canvas ? You’re in luck ! Emscripten has a porting path for SDL. Make a version of your C/C++ software that targets SDL (generally not a tall order) and then compile that with Emscripten.
Do you just want to cross-compile some functionality that lives in a library ? That’s what I’ve done with the Cirrus Retro project. For this, plan to compile the library into a JS file that exports some public functions that other, higher-level, native JS (i.e., JS written by a human and not a computer) will invoke.
Memory Levels
When porting C/C++ software to JavaScript using Emscripten, you have to think on 2 different levels. Or perhaps you need to force JavaScript into a low level C lens, especially if you want to write native JS code that will interact with Emscripten-compiled code. This often means somehow allocating chunks of memory via JS and passing them to the Emscripten-compiled functions. And you wouldn’t believe the type of gymnastics you need to execute to get native JS and Emscripten-compiled JS to cooperate.
“Emscripten : Pointers and Pointers” is the best (and, really, ONLY) explanation I could find for understanding the basic mechanics of this process, at least when I started this journey. However, there’s a mistake in the explanation that left me confused for a little while, and I’m at a loss to contact the author (doesn’t anyone post a simple email address anymore ?).
Per the best of my understanding, Emscripten allocates a large JS array and calls that the memory space that the compiled C/C++ code is allowed to operate in. A pointer in C/C++ code will just be an index into that mighty array. Really, that’s not too far off from how a low-level program process is supposed to view memory– as a flat array.
Eventually, I just learned to cargo-cult my way through the memory allocation process. Here’s the JS code for allocating an Emscripten-compatible byte buffer, taken from my test harness (more on that later) :
var musicBuffer = fs.readFileSync(testSpec[’filename’]) ; var musicBufferBytes = new Uint8Array(musicBuffer) ; var bytesMalloc = player._malloc(musicBufferBytes.length) ; var bytes = new Uint8Array(player.HEAPU8.buffer, bytesMalloc, musicBufferBytes.length) ; bytes.set(new Uint8Array(musicBufferBytes.buffer)) ;
So, read the array of bytes from some input source, create a Uint8Array from the bytes, use the Emscripten _malloc() function to allocate enough bytes from the Emscripten memory array for the input bytes, then create a new array… then copy the bytes…
You know what ? It’s late and I can’t remember how it works exactly, but it does. It has been a few months since I touched that code (been fighting with front-end website tech since then). You write that memory allocation code enough times and it begins to make sense, and then you hope you don’t have to write it too many more times.
Multithreading
You can’t port multithreaded code to JS via Emscripten. JavaScript has no notion of threads ! If you don’t understand the computer science behind this limitation, a more thorough explanation is beyond the scope of this post. But trust me, I’ve thought about it a lot. In fact, the official Emscripten literature states that you should be able to port most any C/C++ code as long as 1) none of the code is proprietary (i.e., all the raw source is available) ; and 2) there are no threads.Yes, I read about the experimental pthreads support added to Emscripten recently. Don’t get too excited ; that won’t be ready and widespread for a long time to come as it relies on a new browser API. In the meantime, figure out how to make your multithreaded C/C++ code run in a single thread if you want it to run in a browser.
Printing Facility
Eventually, getting software to work boils down to debugging, and the most primitive tool in many a programmer’s toolbox is the humble print statement. A print statement allows you to inspect a piece of a program’s state at key junctures. Eventually, when you try to cross-compile C/C++ code to JS using Emscripten, something is not going to work correctly in the generated JS “object code” and you need to understand what. You’ll be pleading for a method of just inspecting one variable deep in the original C/C++ code.I came up with this simple printf-workalike called emprintf() :
#ifndef EMPRINTF_H #define EMPRINTF_H
#include <stdio .h>
#include <stdarg .h>
#include <emscripten .h>#define MAX_MSG_LEN 1000
/* NOTE : Don’t pass format strings that contain single quote (’) or newline
* characters. */
static void emprintf(const char *format, ...)
char msg[MAX_MSG_LEN] ;
char consoleMsg[MAX_MSG_LEN + 16] ;
va_list args ;/* create the string */
va_start(args, format) ;
vsnprintf(msg, MAX_MSG_LEN, format, args) ;
va_end(args) ;/* wrap the string in a console.log(’’) statement */
snprintf(consoleMsg, MAX_MSG_LEN + 16, "console.log(’%s’)", msg) ;/* send the final string to the JavaScript console */
emscripten_run_script(consoleMsg) ;
#endif /* EMPRINTF_H */
Put it in a file called “emprint.h”. Include it into any C/C++ file where you need debugging visibility, use emprintf() as a replacement for printf() and the output will magically show up on the browser’s JavaScript debug console. Heed the comments and don’t put any single quotes or newlines in strings, and keep it under 1000 characters. I didn’t say it was perfect, but it has helped me a lot in my Emscripten adventures.
Optimization Levels
Remember to turn on optimization when compiling. I have empirically found that optimizing for size (-Os) leads to the best performance all around, in addition to having the smallest size. Just be sure to specify some optimization level. If you don’t, the default is -O0 which offers horrible performance when running in JS.Static Compression For HTTP Delivery
JavaScript code compresses pretty efficiently, even after it has been optimized for size using -Os. I routinely see compression ratios between 3.5:1 and 5:1 using gzip.Web servers in this day and age are supposed to be smart enough to detect when a requesting web browser can accept gzip-compressed data and do the compression on the fly. They’re even supposed to be smart enough to cache compressed output so the same content is not recompressed for each request. I would have to set up a series of tests to establish whether either of the foregoing assertions are correct and I can’t be bothered. Instead, I took it into my own hands. The trick is to pre-compress the JS files and then instruct the webserver to serve these files with a ‘Content-Type’ of ‘application/javascript’ and a ‘Content-Encoding’ of ‘gzip’.
- Compress your large Emscripten-build JS files with ‘gzip’ : ‘gzip compiled-code.js’
- Rename them from extension .js.gz to .jsgz
- Tell the webserver to deliver .jsgz files with the correct Content-Type and Content-Encoding headers
To do that last step with Apache, specify these lines :
AddType application/javascript jsgz AddEncoding gzip jsgz
They belong in either a directory’s .htaccess file or in the sitewide configuration (/etc/apache2/mods-available/mime.conf works on my setup).
Build System and Build Time Optimization
Oh goodie, build systems ! I had a very specific manner in which I wanted to build my JS modules using Emscripten. Can I possibly coerce any of the many popular build systems to do this ? It has been a few months since I worked on this problem specifically but I seem to recall that the build systems I tried to used would freak out at the prospect of compiling stuff to a final binary target of .js.I had high hopes for Bazel, which Google released while I was developing Cirrus Retro. Surely, this is software that has been battle-tested in the harshest conditions of one of the most prominent software-developing companies in the world, needing to take into account the most bizarre corner cases and still build efficiently and correctly every time. And I have little doubt that it fulfills the order. Similarly, I’m confident that Google also has a team of no fewer than 100 or so people dedicated to developing and supporting the project within the organization. When you only have, at best, 1-2 hours per night to work on projects like this, you prefer not to fight with such cutting edge technology and after losing 2 or 3 nights trying to make a go of Bazel, I eventually put it aside.
I also tried to use Autotools. It failed horribly for me, mostly for my own carelessness and lack of early-project source control.
After that, it was strictly vanilla makefiles with no real dependency management. But you know what helps in these cases ? ccache ! Or at least, it would if it didn’t fail with Emscripten.
Quick tip : ccache has trouble with LLVM unless you set the CCACHE_CPP2 environment variable (e.g. : “export CCACHE_CPP2=1”). I don’t remember the specifics, but it magically fixes things. Then, the lazy build process becomes “make clean && make”.
Testing
If you have never used Node.js, testing Emscripten-compiled JS code might be a good opportunity to start. I was able to use Node.js to great effect for testing the individually-compiled music player modules, wiring up a series of invocations using Python for a broader test suite (wouldn’t want to go too deep down the JS rabbit hole, after all).Be advised that Node.js doesn’t enjoy the same kind of JIT optimizations that the browser engines leverage. Thus, in the case of time critical code like, say, an audio synthesis library, the code might not run in real time. But as long as it produces the correct bitwise waveform, that’s good enough for continuous integration.
Also, if you have largely been a low-level programmer for your whole career and are generally unfamiliar with the world of single-threaded, event-driven, callback-oriented programming, you might be in for a bit of a shock. When I wanted to learn how to read the contents of a file in Node.js, this is the first tutorial I found on the matter. I thought the code presented was a parody of bad coding style :
var fs = require("fs") ; var fileName = "foo.txt" ;
fs.exists(fileName, function(exists)
if (exists)
fs.stat(fileName, function(error, stats)
fs.open(fileName, "r", function(error, fd)
var buffer = new Buffer(stats.size) ;fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer)
var data = buffer.toString("utf8", 0, buffer.length) ;console.log(data) ;
fs.close(fd) ;
) ;
) ;
) ;
) ;Apparently, this kind of thing doesn’t raise an eyebrow in the JS world.
Now, I understand and respect the JS programming model. But this was seriously frustrating when I first encountered it because a simple script like the one I was trying to write just has an ordered list of tasks to complete. When it asks for bytes from a file, it really has nothing better to do than to wait for the answer.
Thankfully, it turns out that Node’s fs module includes synchronous versions of the various file access functions. So it’s all good.
Conclusion
I’m sure I missed or underexplained some things. But if other brave souls are interested in dipping their toes in the waters of Emscripten, I hope these tips will come in handy. -
Python : Extracting device and lens information from video metadata
14 mai 2023, par cat_got_my_tongueI am interested in extracting device and lens information from videos. Specifically, make and model of the device and the focal length. I was able to do this successfully for still images using the
exifread
module and extract a whole bunch of very useful information :

image type : MPO
Image ImageDescription: Shot with DxO ONE
Image Make: DxO
Image Model: DxO ONE
Image Orientation: Horizontal (normal)
Image XResolution: 300
Image YResolution: 300
Image ResolutionUnit: Pixels/Inch
Image Software: V3.0.0 (2b448a1aee) APP:1.0
Image DateTime: 2022:04:05 14:53:45
Image YCbCrCoefficients: [299/1000, 587/1000, 57/500]
Image YCbCrPositioning: Centered
Image ExifOffset: 158
Thumbnail Compression: JPEG (old-style)
Thumbnail XResolution: 300
Thumbnail YResolution: 300
Thumbnail ResolutionUnit: Pixels/Inch
Thumbnail JPEGInterchangeFormat: 7156
Thumbnail JPEGInterchangeFormatLength: 24886
EXIF ExposureTime: 1/3
EXIF FNumber: 8
EXIF ExposureProgram: Aperture Priority
EXIF ISOSpeedRatings: 100
EXIF SensitivityType: ISO Speed
EXIF ISOSpeed: 100
EXIF ExifVersion: 0221
EXIF DateTimeOriginal: 2022:04:05 14:53:45
EXIF DateTimeDigitized: 2022:04:05 14:53:45
EXIF ComponentsConfiguration: CrCbY
EXIF CompressedBitsPerPixel: 3249571/608175
EXIF ExposureBiasValue: 0
EXIF MaxApertureValue: 212/125
EXIF SubjectDistance: 39/125
EXIF MeteringMode: MultiSpot
EXIF LightSource: Unknown
EXIF Flash: Flash did not fire
EXIF FocalLength: 1187/100
EXIF SubjectArea: [2703, 1802, 675, 450]
EXIF MakerNote: [68, 88, 79, 32, 79, 78, 69, 0, 12, 0, 0, 0, 21, 0, 3, 0, 5, 0, 2, 0, ... ]
EXIF SubSecTime: 046
EXIF SubSecTimeOriginal: 046
EXIF SubSecTimeDigitized: 046
EXIF FlashPixVersion: 0100
EXIF ColorSpace: sRGB
EXIF ExifImageWidth: 5406
EXIF ExifImageLength: 3604
Interoperability InteroperabilityIndex: R98
Interoperability InteroperabilityVersion: [48, 49, 48, 48]
EXIF InteroperabilityOffset: 596
EXIF FileSource: Digital Camera
EXIF ExposureMode: Auto Exposure
EXIF WhiteBalance: Auto
EXIF DigitalZoomRatio: 1
EXIF FocalLengthIn35mmFilm: 32
EXIF SceneCaptureType: Standard
EXIF ImageUniqueID: C01A1709306530020220405185345046
EXIF BodySerialNumber: C01A1709306530



Unfortunately, I have been unable to extract this kind of info from videos so far.


This is what I have tried so far, with the
ffmpeg
module :

import ffmpeg
from pprint import pprint

test_video = "my_video.mp4"
pprint(ffmpeg.probe(test_video)["streams"])



And the output I get contains a lot of info but nothing related to the device or lens, which is what I am looking for :


[{'avg_frame_rate': '30/1',
 'bit_rate': '1736871',
 'bits_per_raw_sample': '8',
 'chroma_location': 'left',
 'codec_long_name': 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10',
 'codec_name': 'h264',
 'codec_tag': '0x31637661',
 'codec_tag_string': 'avc1',
 'codec_time_base': '1/60',
 'codec_type': 'video',
 'coded_height': 1088,
 'coded_width': 1920,
 'display_aspect_ratio': '16:9',
 'disposition': {'attached_pic': 0,
 'clean_effects': 0,
 'comment': 0,
 'default': 1,
 'dub': 0,
 'forced': 0,
 'hearing_impaired': 0,
 'karaoke': 0,
 'lyrics': 0,
 'original': 0,
 'timed_thumbnails': 0,
 'visual_impaired': 0},
 'duration': '20.800000',
 'duration_ts': 624000,
 'has_b_frames': 0,
 'height': 1080,
 'index': 0,
 'is_avc': 'true',
 'level': 40,
 'nal_length_size': '4',
 'nb_frames': '624',
 'pix_fmt': 'yuv420p',
 'profile': 'Constrained Baseline',
 'r_frame_rate': '30/1',
 'refs': 1,
 'sample_aspect_ratio': '1:1',
 'start_pts': 0,
 'start_time': '0.000000',
 'tags': {'creation_time': '2021-05-08T13:23:20.000000Z',
 'encoder': 'AVC Coding',
 'handler_name': 'VideoHandler',
 'language': 'und'},
 'time_base': '1/30000',
 'width': 1920},
 {'avg_frame_rate': '0/0',
 'bit_rate': '79858',
 'bits_per_sample': 0,
 'channel_layout': 'stereo',
 'channels': 2,
 'codec_long_name': 'AAC (Advanced Audio Coding)',
 'codec_name': 'aac',
 'codec_tag': '0x6134706d',
 'codec_tag_string': 'mp4a',
 'codec_time_base': '1/48000',
 'codec_type': 'audio',
 'disposition': {'attached_pic': 0,
 'clean_effects': 0,
 'comment': 0,
 'default': 1,
 'dub': 0,
 'forced': 0,
 'hearing_impaired': 0,
 'karaoke': 0,
 'lyrics': 0,
 'original': 0,
 'timed_thumbnails': 0,
 'visual_impaired': 0},
 'duration': '20.864000',
 'duration_ts': 1001472,
 'index': 1,
 'max_bit_rate': '128000',
 'nb_frames': '978',
 'profile': 'LC',
 'r_frame_rate': '0/0',
 'sample_fmt': 'fltp',
 'sample_rate': '48000',
 'start_pts': 0,
 'start_time': '0.000000',
 'tags': {'creation_time': '2021-05-08T13:23:20.000000Z',
 'handler_name': 'SoundHandler',
 'language': 'und'},
 'time_base': '1/48000'}]



Are these pieces of info available for videos ? Should I be using a different package ?


Thanks.


Edit :


pprint(ffmpeg.probe(test_video)["format"])
gives

{'bit_rate': '1815244',
 'duration': '20.864000',
 'filename': 'my_video.mp4',
 'format_long_name': 'QuickTime / MOV',
 'format_name': 'mov,mp4,m4a,3gp,3g2,mj2',
 'nb_programs': 0,
 'nb_streams': 2,
 'probe_score': 100,
 'size': '4734158',
 'start_time': '0.000000',
 'tags': {'artist': 'Microsoft Game DVR',
 'compatible_brands': 'mp41isom',
 'creation_time': '2021-05-08T12:12:33.000000Z',
 'major_brand': 'mp42',
 'minor_version': '0',
 'title': 'Snipping Tool'}}



-
Discord.py - IndexError : list index out of range
23 novembre 2020, par itsnexnHello i start to learn python and i make bot for practie but i got this error


Ignoring exception in command play:
Traceback (most recent call last):
 File "C:\Users\sinad\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
 ret = await coro(*args, **kwargs)
 File "d:\Projects\discord\musicbot.py", line 147, in play
 player = await YTDLSource.from_url(queue[0], loop=client.loop)
IndexError: list index out of range



and i use ffmpeg to convert audio
and i write this bot in youtube and discord.py documentation
itswork well without music commend but if i use that i got error and isnt working idk why ...
this is my first python project so this is happening and its normal
and this is my code :


import discord
from discord.ext import commands, tasks
from discord.voice_client import VoiceClient

import youtube_dl

from random import choice

from youtube_dl.utils import lowercase_escape

youtube_dl.utils.bug_reports_message = lambda: ''

ytdl_format_options = {
 'format': 'bestaudio/best',
 'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
 'restrictfilenames': True,
 'noplaylist': True,
 'nocheckcertificate': True,
 'ignoreerrors': False,
 'logtostderr': False,
 'quiet': True,
 'no_warnings': True,
 'default_search': 'auto',
 'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
}

ffmpeg_options = {
 'options': '-vn'
}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)

class YTDLSource(discord.PCMVolumeTransformer):
 def __init__(self, source, *, data, volume=0.5):
 super().__init__(source, volume)

 self.data = data

 self.title = data.get('title')
 self.url = data.get('url')

 @classmethod
 async def from_url(cls, url, *, loop=None, stream=False):
 loop = loop or asyncio.get_event_loop()
 data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

 if 'entries' in data:
 # take first item from a playlist
 data = data['entries'][0]

 filename = data['url'] if stream else ytdl.prepare_filename(data)
 return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)


client = commands.Bot(command_prefix='.')

status = ['']
queue = []

#print on terminal when is bot ready
@client.event
async def on_ready():
 change_status.start()
 print('Bot is online!')

#Welcome message
@client.event
async def on_member_join(member):
 channel = discord.utils.get(member.guild.channels, name='general')
 await channel.send(f'Welcome {member.mention}! Ready to jam out? See `.help` command for details!')

#ping
@client.command(name='ping', help='This command returns the latency')
async def ping(ctx):
 await ctx.send(f'**Ping!** Latency: {round(client.latency * 1000)}ms')

@client.event
async def on_message(message):

 if message.content in ['hello', 'Hello']:
 await message.channel.send("**wasaaaaaap**")

 await client.process_commands(message)


#join
@client.command(name='join', help='This command makes the bot join the voice channel')
async def join(ctx):
 if not ctx.message.author.voice:
 await ctx.send("You are not connected to a voice channel")
 return

 else:
 channel = ctx.message.author.voice.channel

 await channel.connect()

#queue
@client.command(name='queue', help='This command adds a song to the queue')
async def queue_(ctx, url):
 global queue

 queue.append(url)
 await ctx.send(f'`{url}` added to queue!')

#remove
@client.command(name='remove', help='This command removes an item from the list')
async def remove(ctx, number):
 global queue

 try:
 del(queue[int(number)])
 await ctx.send(f'Your queue is now `{queue}!`')

 except:
 await ctx.send('Your queue is either **empty** or the index is **out of range**')

#play
@client.command(name='play', help='This command plays songs')
async def play(ctx):
 global queue

 server = ctx.message.guild
 voice_channel = server.voice_client

 async with ctx.typing():
 player = await YTDLSource.from_url(queue[0], loop=client.loop)
 voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)

 await ctx.send('**Now playing:** {}'.format(player.title))
 del(queue[0])

#pause
@client.command(name='pause', help='This command pauses the song')
async def pause(ctx):
 server = ctx.message.guild
 voice_channel = server.voice_client

 voice_channel.pause()

#resune
@client.command(name='resume', help='This command resumes the song!')
async def resume(ctx):
 server = ctx.message.guild
 voice_channel = server.voice_client

 voice_channel.resume()

#viow
@client.command(name='view', help='This command shows the queue')
async def view(ctx):
 await ctx.send(f'Your queue is now `{queue}!`')

#leave
@client.command(name='leave', help='This command stops makes the bot leave the voice channel')
async def leave(ctx):
 voice_client = ctx.message.guild.voice_client
 await voice_client.disconnect()

#stop
@client.command(name='stop', help='This command stops the song!')
async def stop(ctx):
 server = ctx.message.guild
 voice_channel = server.voice_client

 voice_channel.stop()

@tasks.loop(seconds=20)
async def change_status():
 await client.change_presence(activity=discord.Game(choice(status)))

client.run("my_secret")