
Recherche avancée
Médias (1)
-
The Great Big Beautiful Tomorrow
28 octobre 2011, par
Mis à jour : Octobre 2011
Langue : English
Type : Texte
Autres articles (86)
-
Amélioration de la version de base
13 septembre 2013Jolie sélection multiple
Le plugin Chosen permet d’améliorer l’ergonomie des champs de sélection multiple. Voir les deux images suivantes pour comparer.
Il suffit pour cela d’activer le plugin Chosen (Configuration générale du site > Gestion des plugins), puis de configurer le plugin (Les squelettes > Chosen) en activant l’utilisation de Chosen dans le site public et en spécifiant les éléments de formulaires à améliorer, par exemple select[multiple] pour les listes à sélection multiple (...) -
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 ; (...) -
Configuration spécifique pour PHP5
4 février 2011, parPHP5 est obligatoire, vous pouvez l’installer en suivant ce tutoriel spécifique.
Il est recommandé dans un premier temps de désactiver le safe_mode, cependant, s’il est correctement configuré et que les binaires nécessaires sont accessibles, MediaSPIP devrait fonctionner correctement avec le safe_mode activé.
Modules spécifiques
Il est nécessaire d’installer certains modules PHP spécifiques, via le gestionnaire de paquet de votre distribution ou manuellement : php5-mysql pour la connectivité avec la (...)
Sur d’autres sites (6830)
-
Anatomy of an optimization : H.264 deblocking
As mentioned in the previous post, H.264 has an adaptive deblocking filter. But what exactly does that mean — and more importantly, what does it mean for performance ? And how can we make it as fast as possible ? In this post I’ll try to answer these questions, particularly in relation to my recent deblocking optimizations in x264.
H.264′s deblocking filter has two steps : strength calculation and the actual filter. The first step calculates the parameters for the second step. The filter runs on all the edges in each macroblock. That’s 4 vertical edges of length 16 pixels and 4 horizontal edges of length 16 pixels. The vertical edges are filtered first, from left to right, then the horizontal edges, from top to bottom (order matters !). The leftmost edge is the one between the current macroblock and the left macroblock, while the topmost edge is the one between the current macroblock and the top macroblock.
Here’s the formula for the strength calculation in progressive mode. The highest strength that applies is always selected.
If we’re on the edge between an intra macroblock and any other macroblock : Strength 4
If we’re on an internal edge of an intra macroblock : Strength 3
If either side of a 4-pixel-long edge has residual data : Strength 2
If the motion vectors on opposite sides of a 4-pixel-long edge are at least a pixel apart (in either x or y direction) or the reference frames aren’t the same : Strength 1
Otherwise : Strength 0 (no deblocking)These values are then thrown into a lookup table depending on the quantizer : higher quantizers have stronger deblocking. Then the actual filter is run with the appropriate parameters. Note that Strength 4 is actually a special deblocking mode that performs a much stronger filter and affects more pixels.
One can see somewhat intuitively why these strengths are chosen. The deblocker exists to get rid of sharp edges caused by the block-based nature of H.264, and so the strength depends on what exists that might cause such sharp edges. The strength calculation is a way to use existing data from the video stream to make better decisions during the deblocking process, improving compression and quality.
Both the strength calculation and the actual filter (not described here) are very complex if naively implemented. The latter can be SIMD’d with not too much difficulty ; no H.264 decoder can get away with reasonable performance without such a thing. But what about optimizing the strength calculation ? A quick analysis shows that this can be beneficial as well.
Since we have to check both horizontal and vertical edges, we have to check up to 32 pairs of coefficient counts (for residual), 16 pairs of reference frame indices, and 128 motion vector values (counting x and y as separate values). This is a lot of calculation ; a naive implementation can take 500-1000 clock cycles on a modern CPU. Of course, there’s a lot of shortcuts we can take. Here’s some examples :
- If the macroblock uses the 8×8 transform, we only need to check 2 edges in each direction instead of 4, because we don’t deblock inside of the 8×8 blocks.
- If the macroblock is a P-skip, we only have to check the first edge in each direction, since there’s guaranteed to be no motion vector differences, reference frame differences, or residual inside of the macroblock.
- If the macroblock has no residual at all, we can skip that check.
- If we know the partition type of the macroblock, we can do motion vector checks only along the edges of the partitions.
- If the effective quantizer is so low that no deblocking would be performed no matter what, don’t bother calculating the strength.
But even all of this doesn’t save us from ourselves. We still have to iterate over a ton of edges, checking each one. Stuff like the partition-checking logic greatly complicates the code and adds overhead even as it reduces the number of checks. And in many cases decoupling the checks to add such logic will make it slower : if the checks are coupled, we can avoid doing a motion vector check if there’s residual, since Strength 2 overrides Strength 1.
But wait. What if we could do this in SIMD, just like the actual loopfilter itself ? Sure, it seems more of a problem for C code than assembly, but there aren’t any obvious things in the way. Many years ago, Loren Merritt (pengvado) wrote the first SIMD implementation that I know of (for ffmpeg’s decoder) ; it is quite fast, so I decided to work on porting the idea to x264 to see if we could eke out a bit more speed here as well.
Before I go over what I had to do to make this change, let me first describe how deblocking is implemented in x264. Since the filter is a loopfilter, it acts “in loop” and must be done in both the encoder and decoder — hence why x264 has it too, not just decoders. At the end of encoding one row of macroblocks, x264 goes back and deblocks the row, then performs half-pixel interpolation for use in encoding the next frame.
We do it per-row for reasons of cache coherency : deblocking accesses a lot of pixels and a lot of code that wouldn’t otherwise be used, so it’s more efficient to do it in a single pass as opposed to deblocking each macroblock immediately after encoding. Then half-pixel interpolation can immediately re-use the resulting data.
Now to the change. First, I modified deblocking to implement a subset of the macroblock_cache_load function : spend an extra bit of effort loading the necessary data into a data structure which is much simpler to address — as an assembly implementation would need (x264_macroblock_cache_load_deblock). Then I massively cleaned up deblocking to move all of the core strength-calculation logic into a single, small function that could be converted to assembly (deblock_strength_c). Finally, I wrote the assembly functions and worked with Loren to optimize them. Here’s the result.
And the timings for the resulting assembly function on my Core i7, in cycles :
deblock_strength_c : 309
deblock_strength_mmx : 79
deblock_strength_sse2 : 37
deblock_strength_ssse3 : 33Now that is a seriously nice improvement. 33 cycles on average to perform that many comparisons–that’s absurdly low, especially considering the SIMD takes no branchy shortcuts : it always checks every single edge ! I walked over to my performance chart and happily crossed off a box.
But I had a hunch that I could do better. Remember, as mentioned earlier, we’re reloading all that data back into our data structures in order to address it. This isn’t that slow, but takes enough time to significantly cut down on the gain of the assembly code. And worse, less than a row ago, all this data was in the correct place to be used (when we just finished encoding the macroblock) ! But if we did the deblocking right after encoding each macroblock, the cache issues would make it too slow to be worth it (yes, I tested this). So I went back to other things, a bit annoyed that I couldn’t get the full benefit of the changes.
Then, yesterday, I was talking with Pascal, a former Xvid dev and current video hacker over at Google, about various possible x264 optimizations. He had seen my deblocking changes and we discussed that a bit as well. Then two lines hit me like a pile of bricks :
<_skal_> tried computing the strength at least ?
<_skal_> while it’s freshWhy hadn’t I thought of that ? Do the strength calculation immediately after encoding each macroblock, save the result, and then go pick it up later for the main deblocking filter. Then we can use the data right there and then for strength calculation, but we don’t have to do the whole deblock process until later.
I went and implemented it and, after working my way through a horde of bugs, eventually got a working implementation. A big catch was that of slices : deblocking normally acts between slices even though normal encoding does not, so I had to perform extra munging to get that to work. By midday today I was able to go cross yet another box off on the performance chart. And now it’s committed.
Sometimes chatting for 10 minutes with another developer is enough to spot the idea that your brain somehow managed to miss for nearly a straight week.
NB : the performance chart is on a specific test clip at a specific set of settings (super fast settings) relevant to the company I work at, so it isn’t accurate nor complete for, say, default settings.
Update : Here’s a higher resolution version of the current chart, as requested in the comments.
-
Introducing WebM, an open web media project
20 mai 2010, par noreply@blogger.com (christosap)A key factor in the web’s success is that its core technologies such as HTML, HTTP, TCP/IP, etc. are open and freely implementable. Though video is also now core to the web experience, there is unfortunately no open and free video format that is on par with the leading commercial choices. To that end, we are excited to introduce WebM, a broadly-backed community effort to develop a world-class media format for the open web.
WebM includes :
- VP8, a high-quality video codec we are releasing today under a BSD-style, royalty-free license
- Vorbis, an already open source and broadly implemented audio codec
- a container format based on a subset of the Matroska media container
The team that created VP8 have been pioneers in video codec development for over a decade. VP8 delivers high quality video while efficiently adapting to the varying processing and bandwidth conditions found on today’s broad range of web-connected devices. VP8’s efficient bandwidth usage will mean lower serving costs for content publishers and high quality video for end-users. The codec’s relative simplicity makes it easy to integrate into existing environments and requires less manual tuning to produce high quality results. These existing attributes and the rapid innovation we expect through the open-development process make VP8 well suited for the unique requirements of video on the web.
A developer preview of WebM and VP8, including source code, specs, and encoding tools is available today at www.webmproject.org.
We want to thank the many industry leaders and web community members who are collaborating on the development of WebM and integrating it into their products. Check out what Mozilla, Opera, Google Chrome, Adobe, and many others below have to say about the importance of WebM to the future of web video.
-
H264 codec encode, decode and write to file
30 novembre 2020, par Алекс АникейI try to use ffmpeg and h264 codec to translate the video in realtime. But at the state of decoding encoded frame, I get some "bad" image.
Init encoder and decoder :


VCSession *vc_new_x264(Logger *log, ToxAV *av, uint32_t friend_number, toxav_video_receive_frame_cb *cb, void *cb_data,
 VCSession *vc)
{

// ------ ffmpeg encoder ------
 AVCodec *codec2 = NULL;
 vc->h264_encoder_ctx = NULL;//AVCodecContext type

 codec2 = NULL;
 avcodec_register_all();
 codec2 = avcodec_find_encoder(AV_CODEC_ID_H264);
 if (codec2 == NULL)
 {
 LOGGER_WARNING(log, "h264: not find encoder");
 }

 vc->h264_encoder_ctx = avcodec_alloc_context3(codec2);

 vc->h264_out_pic2 = av_packet_alloc();

 vc->h264_encoder_ctx->bit_rate = 10 *1000 * 1000;
 vc->h264_encoder_ctx->width = 800;
 vc->h264_encoder_ctx->height = 600;

 vc->h264_enc_width = vc->h264_encoder_ctx->width;
 vc->h264_enc_height = vc->h264_encoder_ctx->height;
 vc->h264_encoder_ctx->time_base = (AVRational) {
 1, 30
 };
 vc->h264_encoder_ctx->gop_size = 30;
 vc->h264_encoder_ctx->max_b_frames = 1;
 vc->h264_encoder_ctx->pix_fmt = AV_PIX_FMT_YUV420P;


 av_opt_set(vc->h264_encoder_ctx->priv_data, "preset", "veryfast", 0);


 av_opt_set(vc->h264_encoder_ctx->priv_data, "annex_b", "1", 0);
 av_opt_set(vc->h264_encoder_ctx->priv_data, "repeat_headers", "1", 0);
 av_opt_set(vc->h264_encoder_ctx->priv_data, "tune", "zerolatency", 0);
 av_opt_set_int(vc->h264_encoder_ctx->priv_data, "zerolatency", 1, 0);

 vc->h264_encoder_ctx->time_base.num = 1;
 vc->h264_encoder_ctx->time_base.den = 1000;

 vc->h264_encoder_ctx->framerate = (AVRational) {
 1000, 40
 };

 AVDictionary *opts = NULL;

 if (avcodec_open2(vc->h264_encoder_ctx, codec2, &opts) < 0) {
 LOGGER_ERROR(log, "could not open codec H264 on encoder");
 }

 av_dict_free(&opts);



 AVCodec *codec = NULL;
 vc->h264_decoder_ctx = NULL;// AVCodecContext - type
 codec = NULL;

 codec = avcodec_find_decoder(AV_CODEC_ID_H264);

 if (!codec) {
 LOGGER_WARNING(log, "codec not found H264 on decoder");
 }

 vc->h264_decoder_ctx = avcodec_alloc_context3(codec);

 if (codec->capabilities & AV_CODEC_CAP_TRUNCATED) {
 vc->h264_decoder_ctx->flags |= AV_CODEC_FLAG_TRUNCATED; /* we do not send complete frames */
 }

 if (codec->capabilities & AV_CODEC_FLAG_LOW_DELAY) {
 vc->h264_decoder_ctx->flags |= AV_CODEC_FLAG_LOW_DELAY;
 }

 vc->h264_decoder_ctx->flags |= AV_CODEC_FLAG2_SHOW_ALL;

 vc->h264_decoder_ctx->refcounted_frames = 0;

 vc->h264_decoder_ctx->delay = 0;
 vc->h264_decoder_ctx->sw_pix_fmt = AV_PIX_FMT_YUV420P;
 av_opt_set_int(vc->h264_decoder_ctx->priv_data, "delay", 0, AV_OPT_SEARCH_CHILDREN);
 vc->h264_decoder_ctx->time_base = (AVRational) {
 40, 1000
};
 vc->h264_decoder_ctx->framerate = (AVRational) {
 1000, 40
 };

 if (avcodec_open2(vc->h264_decoder_ctx, codec, NULL) < 0) {
 LOGGER_WARNING(log, "could not open codec H264 on decoder");
 }
 vc->h264_decoder_ctx->refcounted_frames = 0;

 return vc;
}



Encoding (in this function i encode frame and for debugging decode and save him in file) :


uint32_t encode_frame_h264_p(ToxAV *av, uint32_t friend_number, uint16_t width, uint16_t height,
 const uint8_t *y,
 const uint8_t *u, const uint8_t *v, ToxAVCall *call,
 uint64_t *video_frame_record_timestamp,
 int vpx_encode_flags,
 x264_nal_t **nal,
 int *i_frame_size)
{
 AVFrame *frame;
 int ret;
 uint32_t result = 1;

 frame = av_frame_alloc();

 frame->format = call->video->h264_encoder_ctx->pix_fmt;
 frame->width = width;
 frame->height = height;

 ret = av_frame_get_buffer(frame, 32);

 if (ret < 0) {
 LOGGER_ERROR(av->m->log, "av_frame_get_buffer:Could not allocate the video frame data");
 }

 /* make sure the frame data is writable */
 ret = av_frame_make_writable(frame);

 if (ret < 0) {
 LOGGER_ERROR(av->m->log, "av_frame_make_writable:ERROR");
 }

 frame->pts = (int64_t)(*video_frame_record_timestamp);


 // copy YUV frame data into buffers
 memcpy(frame->data[0], y, width * height);
 memcpy(frame->data[1], u, (width / 2) * (height / 2));
 memcpy(frame->data[2], v, (width / 2) * (height / 2));

 // encode the frame
 ret = avcodec_send_frame(call->video->h264_encoder_ctx, frame);

 if (ret < 0) {
 LOGGER_ERROR(av->m->log, "Error sending a frame for encoding:ERROR");
 }


 ret = avcodec_receive_packet(call->video->h264_encoder_ctx, call->video->h264_out_pic2);



 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
 *i_frame_size = 0;
 } else if (ret < 0) {
 *i_frame_size = 0;
 // fprintf(stderr, "Error during encoding\n");
 } else {

 // Decoded encoded frame and save him to file

 saveInFile(call->video->h264_decoder_ctx, frame, call->video->h264_out_pic2, "/home/user/testSave");

 // printf("Write packet %3"PRId64" (size=%5d)\n", call->video->h264_out_pic2->pts, call->video->h264_out_pic2->size);
 // fwrite(call->video->h264_out_pic2->data, 1, call->video->h264_out_pic2->size, outfile);

 global_encoder_delay_counter++;

 if (global_encoder_delay_counter > 60) {
 global_encoder_delay_counter = 0;
 LOGGER_DEBUG(av->m->log, "enc:delay=%ld",
 (long int)(frame->pts - (int64_t)call->video->h264_out_pic2->pts)
 );
 }


 *i_frame_size = call->video->h264_out_pic2->size;
 *video_frame_record_timestamp = (uint64_t)call->video->h264_out_pic2->pts;

 result = 0;
 }

 av_frame_free(&frame);

 return result;

}



Decode and save frame code :


void saveInFile(AVCodecContext *dec_ctx, AVFrame *frame, AVPacket *pkt, const char *filename)
{
 if (!pkt)
 return;
 char buf[1024];
 int ret;
 static int curNumber = 0;
 ret = avcodec_send_packet(dec_ctx, pkt);
 if (ret < 0 && ret != AVERROR_EOF)
 {
 fprintf(stderr, "Error sending a packet for decoding'\n");
 if ( ret == AVERROR(EAGAIN))
 return;
 if (ret == AVERROR(EINVAL))
 return;
 if (ret == AVERROR(ENOMEM))
 return;

 }

 ret = avcodec_receive_frame(dec_ctx, frame);
 if (ret == AVERROR(EAGAIN) )
 return;
 if (ret == AVERROR_EOF)
 {
 return;
 }
 else if (ret < 0)
 {
 fprintf(stderr, "Error during decoding\n");
 }
 printf("saving frame %3d\n", dec_ctx->frame_number);
 sprintf(buf, "%s%d", filename, curNumber);
 curNumber++;
 pgm_save(frame->data[0], frame->linesize[0], frame->width, frame->height, buf);

}

void pgm_save(unsigned char* buf, int wrap, int xsize, int ysize, char *filename)
{
 FILE *f;
 int i;
 f = fopen(filename, "w");
 fprintf(f, "P5\n%d %d\n%d\n", xsize, ysize, 255);
 for (i =0; i < ysize; i++)
 fwrite(buf + i* wrap, 1, xsize, f);
 fclose(f);
}



After this manipulation I have smth like that :