X264とRTPでlibavformat / ffmpegを同期するトラブル
-
12-12-2019 - |
質問
私はライブフィードを取るいくつかのストリーミングソフトウェアに取り組んでいました ネットワーク上のさまざまな種類のカメラやストリームから H.264。これを達成するために、私はX264エンコーダーを直接使用しています 「潜在性」プリセット)およびそれらが利用可能なときの給餌NALS RTP(最終的にRTSP)にパックするLibavFormat。理想的には、これです アプリケーションはできるだけリアルタイムであるべきです。ほとんどの場合、 これはうまく機能しています。
残念ながら、いくつかの同期の問題があります。 クライアント上でのビデオ再生では、いくつかの滑らかなフレームを表示するようです。 その後、短い一時停止、その後、より多くのフレーム。繰り返す。さらに、 約4秒の遅延があるようです。これが起こります 私が試したすべてのビデオプレーヤー:TOTEM、VLC、および基本的なGStreamerパイプ。
私はそれをすべてやや小さなテストケースに煮詰めました:
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <x264.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#define WIDTH 640
#define HEIGHT 480
#define FPS 30
#define BITRATE 400000
#define RTP_ADDRESS "127.0.0.1"
#define RTP_PORT 49990
struct AVFormatContext* avctx;
struct x264_t* encoder;
struct SwsContext* imgctx;
uint8_t test = 0x80;
void create_sample_picture(x264_picture_t* picture)
{
// create a frame to store in
x264_picture_alloc(picture, X264_CSP_I420, WIDTH, HEIGHT);
// fake image generation
// disregard how wrong this is; just writing a quick test
int strides = WIDTH / 8;
uint8_t* data = malloc(WIDTH * HEIGHT * 3);
memset(data, test, WIDTH * HEIGHT * 3);
test = (test << 1) | (test >> (8 - 1));
// scale the image
sws_scale(imgctx, (const uint8_t* const*) &data, &strides, 0, HEIGHT,
picture->img.plane, picture->img.i_stride);
}
int encode_frame(x264_picture_t* picture, x264_nal_t** nals)
{
// encode a frame
x264_picture_t pic_out;
int num_nals;
int frame_size = x264_encoder_encode(encoder, nals, &num_nals, picture, &pic_out);
// ignore bad frames
if (frame_size < 0)
{
return frame_size;
}
return num_nals;
}
void stream_frame(uint8_t* payload, int size)
{
// initalize a packet
AVPacket p;
av_init_packet(&p);
p.data = payload;
p.size = size;
p.stream_index = 0;
p.flags = AV_PKT_FLAG_KEY;
p.pts = AV_NOPTS_VALUE;
p.dts = AV_NOPTS_VALUE;
// send it out
av_interleaved_write_frame(avctx, &p);
}
int main(int argc, char* argv[])
{
// initalize ffmpeg
av_register_all();
// set up image scaler
// (in-width, in-height, in-format, out-width, out-height, out-format, scaling-method, 0, 0, 0)
imgctx = sws_getContext(WIDTH, HEIGHT, PIX_FMT_MONOWHITE,
WIDTH, HEIGHT, PIX_FMT_YUV420P,
SWS_FAST_BILINEAR, NULL, NULL, NULL);
// set up encoder presets
x264_param_t param;
x264_param_default_preset(¶m, "ultrafast", "zerolatency");
param.i_threads = 3;
param.i_width = WIDTH;
param.i_height = HEIGHT;
param.i_fps_num = FPS;
param.i_fps_den = 1;
param.i_keyint_max = FPS;
param.b_intra_refresh = 0;
param.rc.i_bitrate = BITRATE;
param.b_repeat_headers = 1; // whether to repeat headers or write just once
param.b_annexb = 1; // place start codes (1) or sizes (0)
// initalize
x264_param_apply_profile(¶m, "high");
encoder = x264_encoder_open(¶m);
// at this point, x264_encoder_headers can be used, but it has had no effect
// set up streaming context. a lot of error handling has been ommitted
// for brevity, but this should be pretty standard.
avctx = avformat_alloc_context();
struct AVOutputFormat* fmt = av_guess_format("rtp", NULL, NULL);
avctx->oformat = fmt;
snprintf(avctx->filename, sizeof(avctx->filename), "rtp://%s:%d", RTP_ADDRESS, RTP_PORT);
if (url_fopen(&avctx->pb, avctx->filename, URL_WRONLY) < 0)
{
perror("url_fopen failed");
return 1;
}
struct AVStream* stream = av_new_stream(avctx, 1);
// initalize codec
AVCodecContext* c = stream->codec;
c->codec_id = CODEC_ID_H264;
c->codec_type = AVMEDIA_TYPE_VIDEO;
c->flags = CODEC_FLAG_GLOBAL_HEADER;
c->width = WIDTH;
c->height = HEIGHT;
c->time_base.den = FPS;
c->time_base.num = 1;
c->gop_size = FPS;
c->bit_rate = BITRATE;
avctx->flags = AVFMT_FLAG_RTP_HINT;
// write the header
av_write_header(avctx);
// make some frames
for (int frame = 0; frame < 10000; frame++)
{
// create a sample moving frame
x264_picture_t* pic = (x264_picture_t*) malloc(sizeof(x264_picture_t));
create_sample_picture(pic);
// encode the frame
x264_nal_t* nals;
int num_nals = encode_frame(pic, &nals);
if (num_nals < 0)
printf("invalid frame size: %d\n", num_nals);
// send out NALs
for (int i = 0; i < num_nals; i++)
{
stream_frame(nals[i].p_payload, nals[i].i_payload);
}
// free up resources
x264_picture_clean(pic);
free(pic);
// stream at approx 30 fps
printf("frame %d\n", frame);
usleep(33333);
}
return 0;
}
.
このテストは白い背景の上の黒い線を示しています 左に円滑に動くべきです。 FFMPEG 0.6.5のために書かれています しかし、問題は 0.8 と 0.10 で再現することができます(私がこれまでにテストしたものから)この問題は(私がテストしたものから)。この例を短くするために、エラー処理にいくつかのショートカットを取った。 それでも問題を示しながら可能なので、 厄介なコード。また、SDPはここでは使用されていない間にも注意してください。 同様の結果を込めてすでに使用してみました。テストはできます
でコンパイルされましたgcc -g -std=gnu99 streamtest.c -lswscale -lavformat -lx264 -lm -lpthread -o streamtest
.
直接Gtremerで再生することができます:
gst-launch udpsrc port=49990 ! application/x-rtp,payload=96,clock-rate=90000 ! rtph264depay ! decodebin ! xvimagesink
.
すぐに吃音に気付くべきです。 1つの一般的な「修正」 インターネット全体に見られることは、パイプラインにSync= falseを追加することです:
gst-launch udpsrc port=49990 ! application/x-rtp,payload=96,clock-rate=90000 ! rtph264depay ! decodebin ! xvimagesink sync=false
.
これにより、再生が滑らかで(そしてリアルタイム)の原因となりますが、 非解決策とGStreamerでのみ機能します。修正したいのですが ソースの問題私はほぼ同一で流れていました RAW FFMPEGを使用したパラメータと問題がありませんでした:
ffmpeg -re -i sample.mp4 -vcodec libx264 -vpre ultrafast -vpre baseline -b 400000 -an -f rtp rtp://127.0.0.1:49990 -an
.
とても明らかに何か悪いことをしています。しかし、それは何ですか?
解決
1)あなたがlibx264に送るフレームのためにPTSを設定しませんでした(あなたはおそらく非厳密な単調なPTS "の警告を見るべきです) 2)LibavFormatのRTPマルチュアに送信するパケットにPTS / DTSを設定しませんでした(私はそれが設定される必要があると思いますが、それがより良いと思います。ソースコードからRTP使用PTSのように見えます)。 3)IMHO USLEEP(33333)は悪いです。この時間も(待ち時間の増加)中にエンコーダがストールを起こす(待ち時間の増加)。
p.S。BTW param.rc.i_rc_methodをx264_rc_abrに設定しませんので、libx264は代わりにCRF 23を使用し、 "param.rc.i_bitrate= bitrate"を無視します。ネットワーク送信用のエンコード時にVBVを使用することをお勧めします。