FFmpeg4Android:視頻文件推流

8 FFmpeg4Android:視頻文件推流

8.1 推流原理

RTMP推流器(Streamer)的在流媒體系統(tǒng)中的作用可以用下圖表示。首先將視頻數(shù)據(jù)以RTMP的形式發(fā)送到流媒體服務(wù)器端(Server,比如FMS,Red5,Wowza等),然后客戶端(一般為Flash Player)通過訪問流媒體服務(wù)器就可以收看實時流了。

<center>
推流原理

運行本程序之前需要先運行RTMP流媒體服務(wù)器,并在流媒體服務(wù)器上建立相應(yīng)的Application。有關(guān)流媒體服務(wù)器的操作不在本文的論述范圍內(nèi),在此不再詳述。本程序運行后,即可通過RTMP客戶端(例如 Flash Player, FFplay等等)收看推送的直播流。

需要要注意的地方:
1)封裝格式
RTMP采用的封裝格式是FLV。因此在指定輸出流媒體的時候需要指定其封裝格式為“flv”。同理,其他流媒體協(xié)議也需要指定其封裝格式。例如采用UDP推送流媒體的時候,可以指定其封裝格式為“mpegts”。

2)延時
發(fā)送流媒體的數(shù)據(jù)的時候需要延時。不然的話,F(xiàn)Fmpeg處理數(shù)據(jù)速度很快,瞬間就能把所有的數(shù)據(jù)發(fā)送出去,流媒體服務(wù)器是接受不了的。因此需要按照視頻實際的幀率發(fā)送數(shù)據(jù)。本文記錄的推流器在視頻幀與幀之間采用了av_usleep()函數(shù)休眠的方式來延遲發(fā)送。這樣就可以按照視頻的幀率發(fā)送數(shù)據(jù)了,參考代碼如下。

8.2 nginx服務(wù)器搭建

  1. 先下載安裝 nginx 和 nginx-rtmp 編譯依賴工具
    sudo apt-get install build-essential libpcre3 libpcre3-dev libssl-dev

  2. 創(chuàng)建一個工作目錄,并切換到工作目錄
    mkdir /usr/jason/nginx
    cd /usr/jason/nginx

  3. 下載 nginx 和 nginx-rtmp源碼(wget是一個從網(wǎng)絡(luò)上自動下載文件的自由工具)
    wget http://nginx.org/download/nginx-1.7.5.tar.gz(或wget http://nginx.org/download/nginx-1.8.1.tar.gz
    wget https://github.com/arut/nginx-rtmp-module/archive/master.zip

  4. 安裝unzip工具,解壓下載的安裝包
    sudo apt-get install unzip

  5. 解壓 nginx 和 nginx-rtmp安裝包
    tar -zxvf nginx-1.7.5.tar.gz
    -zxvf分別是四個參數(shù)
    x : 從 tar 包中把文件提取出來
    z : 表示 tar 包是被 gzip 壓縮過的,所以解壓時需要用 gunzip 解壓
    v : 顯示詳細(xì)信息
    f xxx.tar.gz : 指定被處理的文件是 xxx.tar.gz

unzip master.zip

  1. 切換到 nginx-目錄
    cd nginx-1.7.5

  2. 添加 nginx-rtmp 模板編譯到 nginx
    ./configure --with-http_ssl_module --add-module=../nginx-rtmp-module-master

  3. 編譯安裝
    make
    sudo make install

  4. 安裝nginx init 腳本
    (/etc/init.d/下:)
    sudo wget https://raw.github.com/JasonGiedymin/nginx-init-ubuntu/master/nginx -O /etc/init.d/nginx
    sudo chmod +x /etc/init.d/nginx
    sudo update-rc.d nginx defaults

  5. 啟動和停止nginx 服務(wù),生成配置文件
    sudo service nginx start
    sudo service nginx stop
    (tip : /usr/local/nginx/conf下的nginx.conf文件,在server:listen中可以改端口)

  1. 安裝 FFmpeg
    ./configure --disable-yasm(末尾會有fail字樣的WARNING,為正常情況)
    make
    make install

  2. 配置 nginx-rtmp 服務(wù)器
    打開 /usr/local/nginx/conf/nginx.conf
    在末尾添加如下 配置

rtmp {
    server {
            listen 1935;
            chunk_size 4096;

            application live {
                    live on;
                    record off;
                    exec ffmpeg -i rtmp://localhost/live/$name -threads 1 -c:v libx264 -profile:v baseline -b:v 350K -s 640x360 -f flv -c:a aac -ac 1 -strict -2 -b:a 56k rtmp://localhost/live360p/$name;
            }
            application live360p {
                    live on;
                    record off;
        }
    }
}
  1. 保存上面配置文件,然后重新啟動nginx服務(wù)
    sudo service nginx restart

  2. 如果你使用了防火墻,請允許端口 tcp 1935
    如:阿里云需要在安全組中設(shè)置好1935端口

  1. 服務(wù)器配置測試播放器:
    將播放器復(fù)制到目錄:/usr/local/nginx/html/,然后修改播放地址

附:推流與播放命令
推流:ffmpeg -re -i "D:\sintel.mp4" -vcodec libx264 -vprofile baseline -acodec aac -ar 44100 -strict -2 -ac 1 -f flv -s 1280x720 -q 10 rtmp://180.76.117.119:1935/live/walker
播放:ffplay rtmp://180.76.117.119:1935/live/walker

8.3 視頻推流

java端代碼,主要是轉(zhuǎn)入rtmp地址和聲明jni函數(shù):

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

    // rtmp url
    private static final String rtmpURL = "rtmp://118.190.211.61:1935/live/walker";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button startButton = findViewById(R.id.button_start);
        final EditText urlEdittext_input = findViewById(R.id.input_url);
        final EditText urlEdittext_output = findViewById(R.id.output_url);
        urlEdittext_output.setText(rtmpURL);

        startButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {

                String folderurl = Environment.getExternalStorageDirectory().getPath();

                String urltext_input = urlEdittext_input.getText().toString();
                String inputurl = folderurl + "/" + urltext_input;

                String outputurl = urlEdittext_output.getText().toString();

                Log.e("inputurl", inputurl);
                Log.e("outputurl", outputurl);
                String info = "";

                stream(inputurl, outputurl);

                Log.e("Info", info);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    // JNI
    public native int stream(String inputurl, String outputurl);

    static {
        System.loadLibrary("avutil-54");
        System.loadLibrary("swresample-1");
        System.loadLibrary("avcodec-56");
        System.loadLibrary("avformat-56");
        System.loadLibrary("swscale-3");
        System.loadLibrary("postproc-53");
        System.loadLibrary("avfilter-5");
        System.loadLibrary("avdevice-56");
        System.loadLibrary("sffstreamer");
    }
}

c端代碼,實現(xiàn)視頻的解封裝與推流:

#include <stdio.h>
#include <time.h> 

#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/log.h"

#ifdef ANDROID
#include <jni.h>
#include <android/log.h>
#define LOGE(format, ...)  __android_log_print(ANDROID_LOG_ERROR, "walker", format, ##__VA_ARGS__)
#define LOGI(format, ...)  __android_log_print(ANDROID_LOG_INFO,  "walker", format, ##__VA_ARGS__)
#else
#define LOGE(format, ...)  LOGE("(>_<) " format "\n", ##__VA_ARGS__)
#define LOGI(format, ...)  LOGE("(^_^) " format "\n", ##__VA_ARGS__)
#endif

//Output FFmpeg's av_log()
void custom_log(void *ptr, int level, const char* fmt, va_list vl){

    //To TXT file
    FILE *fp=fopen("/storage/emulated/0/av_log.txt","a+");
    if(fp){
        vfprintf(fp,fmt,vl);
        fflush(fp);
        fclose(fp);
    }

    //To Logcat
    //LOGE(fmt, vl);
}

JNIEXPORT jint JNICALL Java_com_ffmpeg_push_MainActivity_stream
  (JNIEnv *env, jobject obj, jstring input_jstr, jstring output_jstr)
{
    AVOutputFormat *ofmt = NULL;
    AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
    AVPacket pkt;

    int ret, i;
    char input_str[500]={0};
    char output_str[500]={0};

    char info[1000]={0};
    sprintf(input_str,"%s",(*env)->GetStringUTFChars(env,input_jstr, NULL));
    sprintf(output_str,"%s",(*env)->GetStringUTFChars(env,output_jstr, NULL));

    //FFmpeg av_log() callback
    av_log_set_callback(custom_log);

    av_register_all();
    //Network
    avformat_network_init();

    //Input
    if ((ret = avformat_open_input(&ifmt_ctx, input_str, 0, 0)) < 0) {
        LOGE( "Could not open input file.");
        goto end;
    }
    if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
        LOGE( "Failed to retrieve input stream information");
        goto end;
    }

    int videoindex=-1;
    for(i=0; i<ifmt_ctx->nb_streams; i++) 
        if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){
            videoindex=i;
            break;
        }
    //Output
    avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv",output_str); //RTMP
    //avformat_alloc_output_context2(&ofmt_ctx, NULL, "mpegts", output_str);//UDP

    if (!ofmt_ctx) {
        LOGE( "Could not create output context\n");
        ret = AVERROR_UNKNOWN;
        goto end;
    }
    ofmt = ofmt_ctx->oformat;
    for (i = 0; i < ifmt_ctx->nb_streams; i++) {
        //Create output AVStream according to input AVStream
        AVStream *in_stream = ifmt_ctx->streams[i];
        AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);
        if (!out_stream) {
            LOGE( "Failed allocating output stream\n");
            ret = AVERROR_UNKNOWN;
            goto end;
        }
        //Copy the settings of AVCodecContext
        ret = avcodec_copy_context(out_stream->codec, in_stream->codec);
        if (ret < 0) {
            LOGE( "Failed to copy context from input to output stream codec context\n");
            goto end;
        }
        out_stream->codec->codec_tag = 0;
        if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
            out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }

    //Open output URL
    if (!(ofmt->flags & AVFMT_NOFILE)) {
        ret = avio_open(&ofmt_ctx->pb, output_str, AVIO_FLAG_WRITE);
        if (ret < 0) {
            LOGE( "Could not open output URL '%s'\n 'ret':%d", output_str, ret);
            goto end;
        }
    }
    //Write file header
    ret = avformat_write_header(ofmt_ctx, NULL);
    if (ret < 0) {
        LOGE( "Error occurred when opening output URL\n 'ret: %d'", ret);
        goto end;
    }

    int frame_index=0;

    int64_t start_time=av_gettime();
    while (1) {
        AVStream *in_stream, *out_stream;
        //Get an AVPacket
        ret = av_read_frame(ifmt_ctx, &pkt);
        if (ret < 0)
            break;
        //FIX??No PTS (Example: Raw H.264)
        //Simple Write PTS
        if(pkt.pts==AV_NOPTS_VALUE) {
            //Write PTS
            AVRational time_base1=ifmt_ctx->streams[videoindex]->time_base;
            //Duration between 2 frames (us)
            int64_t calc_duration=(double)AV_TIME_BASE/av_q2d(ifmt_ctx->streams[videoindex]->r_frame_rate);
            //Parameters
            pkt.pts=(double)(frame_index*calc_duration)/(double)(av_q2d(time_base1)*AV_TIME_BASE);
            pkt.dts=pkt.pts;
            pkt.duration=(double)calc_duration/(double)(av_q2d(time_base1)*AV_TIME_BASE);
        }
        //Important:Delay
        if(pkt.stream_index==videoindex){
            AVRational time_base=ifmt_ctx->streams[videoindex]->time_base;
            AVRational time_base_q={1,AV_TIME_BASE};
            int64_t pts_time = av_rescale_q(pkt.dts, time_base, time_base_q);
            int64_t now_time = av_gettime() - start_time;
            if (pts_time > now_time)
                av_usleep(pts_time - now_time);

        }

        in_stream  = ifmt_ctx->streams[pkt.stream_index];
        out_stream = ofmt_ctx->streams[pkt.stream_index];
        /* copy packet */
        //Convert PTS/DTS
        pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
        pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
        pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
        pkt.pos = -1;
        //Print to Screen
        if(pkt.stream_index==videoindex){
            LOGE("Send %8d video frames to output URL\n",frame_index);
            frame_index++;
        }
        //ret = av_write_frame(ofmt_ctx, &pkt);
        ret = av_interleaved_write_frame(ofmt_ctx, &pkt);

        if (ret < 0) {
            LOGE( "Error muxing packet\n");
            break;
        }
        av_free_packet(&pkt);
        
    }
    //Write file trailer
    av_write_trailer(ofmt_ctx);
    end:
        avformat_close_input(&ifmt_ctx);
        /* close output */
        if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
            avio_close(ofmt_ctx->pb);
        avformat_free_context(ofmt_ctx);
        if (ret < 0 && ret != AVERROR_EOF) {
            LOGE( "Error occurred.\n");
            return -1;
        }
        return 0;
}





源碼下載:https://download.csdn.net/download/itismelzp/10317555

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容