FFmpeg筆記(四)--編碼過程

編碼過程可以看做解碼的逆過程粱锐,語法、思路基本一致扛邑。

1.導(dǎo)入頭文件,比解碼多用到個image工具類怜浅。
#import <libavformat/avformat.h>
#import <libswscale/swscale.h>
#import <libswresample/swresample.h>
#import <libavutil/pixdesc.h>
#import <libavutil/imgutils.h>
2.注冊協(xié)議、格式鹿榜、編解碼器海雪。
av_register_all();
3.初始化上下文锦爵,獲取輸出文件格式。
AVFormatContext *avformat_context = avformat_alloc_context();
const char *coutFilePath = [outFilePath UTF8String];
AVOutputFormat *avoutput_format = av_guess_format(NULL,coutFilePath,NULL);
avformat_context->oformat = avoutput_format;
4.打開輸出文件奥裸。
if (avio_open(&avformat_context->pb,coutFilePath,AVIO_FLAG_WRITE) < 0) {
   NSLog(@"打開輸出文件失敗");
   return;
}
5.獲取編碼器上下文并設(shè)置音視頻編碼器险掀。

視頻編碼器:

AVStream *av_video_stream = avformat_new_stream(avformat_context,NULL);
AVCodecContext *avcodec_context = avcodec_alloc_context3(NULL);
if (avcodec_context == NULL)  {
  NSLog(@"Could not allocate AVCodecContext\n");
  return;
}

int avcodec_parameters_to_context_result = avcodec_parameters_to_context(avcodec_context, av_video_stream->codecpar);
if (avcodec_parameters_to_context_result != 0) {
  // 0 成功 
  NSLog(@"獲取解碼器上下文失敗");
  return;
}

avcodec_context->codec_id = avoutput_format->video_codec;
avcodec_context->codec_type = AVMEDIA_TYPE_VIDEO;
avcodec_context->pix_fmt = AV_PIX_FMT_YUV420P;
avcodec_context->width = 640;
avcodec_context->height = 352;
//每1秒25幀
avcodec_context->time_base.num = 1;
avcodec_context->time_base.den = 25;

//碼率->單位時間傳送的數(shù)據(jù)位數(shù)
avcodec_context->bit_rate = 468000;
avcodec_context->gop_size = 250;

//量化系數(shù)越小,視頻越是清晰
//一般情況下都是默認(rèn)值湾宙,最小量化系數(shù)默認(rèn)值是10樟氢,最大量化系數(shù)默認(rèn)值是51
avcodec_context->qmin = 10;
avcodec_context->qmax = 51;

//設(shè)置b幀最大值->設(shè)置不需要B幀
avcodec_context->max_b_frames = 0;
// 查找編碼器h264 (默認(rèn)情況下FFmpeg沒有編譯進(jìn)行h264庫 需下載x264編譯)
AVCodec *avcodec = avcodec_find_encoder(avcodec_context->codec_id);
if (avcodec == NULL) {
   NSLog(@"找不到編碼器");
   return;
}

音頻編碼器:

    AVStream *av_video_stream = avformat_new_stream(avformat_context,NULL);
    AVCodecContext *avcodec_context = avcodec_alloc_context3(NULL);;
    avcodec_parameters_to_context(avcodec_context, av_video_stream->codecpar);
    //設(shè)置編解碼器上下文->目標(biāo):設(shè)置為是一個音頻編碼器上下文->指定的是音頻編碼器
    avcodec_context->codec_id = avcodec_alloc_context3(NULL);

    //設(shè)置編碼器類型->音頻編碼器
    //視頻編碼器->AVMEDIA_TYPE_VIDEO
    //音頻編碼器->AVMEDIA_TYPE_AUDIO
    avcodec_context->codec_type = AVMEDIA_TYPE_AUDIO;

    // 設(shè)置讀取音頻采樣數(shù)據(jù)格式->編碼的是音頻采樣數(shù)據(jù)格式->音頻采樣數(shù)據(jù)格式->pcm格式
    //注意:這個類型是根據(jù)你解碼的時候指定的解碼的音頻采樣數(shù)據(jù)格式類型
    avcodec_context->sample_fmt = AV_SAMPLE_FMT_S16;

    //設(shè)置采樣率
    avcodec_context->sample_rate = 44100;
    //立體聲
    avcodec_context->channel_layout = AV_CH_LAYOUT_STEREO;
    //聲道數(shù)量
    int channels = av_get_channel_layout_nb_channels(avcodec_context->channel_layout);
    avcodec_context->channels = channels;
    //設(shè)置碼率 基本的算法是:【碼率】(kbps)=【視頻大小 - 音頻大小】(bit位) /【時間】(秒)
    avcodec_context->bit_rate = 128000;

6.打開編碼器。

視頻編碼器:

    AVDictionary *param = 0;
    if (avcodec_context->codec_id == AV_CODEC_ID_H264) {
        //需要查看x264源碼->x264.c文件
        //第一個值:預(yù)備參數(shù)
        //key: preset
        //value: slow->慢
        //value: superfast->超快
        av_dict_set(&param, "preset", "slow", 0);
        //第二個值:調(diào)優(yōu)
        //key: tune->調(diào)優(yōu)
        //value: zerolatency->零延遲
        av_dict_set(&param, "tune", "zerolatency", 0);
    }
    if (avcodec_open2(avcodec_context, avcodec, &param) < 0) {
        
        NSLog(@"打開編碼器失敗");
        return;
    }

音頻編碼器:

    //查找音頻編碼器->aac libfdk_aac ffmpeg ./configre help 查看
    AVCodec *avcodec = avcodec_find_encoder_by_name("libfdk_aac");
    if (avcodec == NULL) {
        NSLog(@"找不到音頻編碼器");
        return;
    }
    if (avcodec_open2(avcodec_context,avcodec,NULL)<0) {
        NSLog(@"打開音頻編碼器失敗");
        return;
    }
7.寫入文件頭信息侠鳄。
  int avformat_write_header_result = avformat_write_header(avformat_context, NULL);
  if (avformat_write_header_result != 0) {
      NSLog(@"寫入頭部信息失敗");
      return;
  }
8.設(shè)置緩沖區(qū)埠啃。

視頻緩沖區(qū):

    // 獲取緩沖區(qū)大小
    int buffer_size = av_image_get_buffer_size(avcodec_context->pix_fmt,
                                               avcodec_context->width,
                                               avcodec_context->height,
                                               1);
    //創(chuàng)建一個緩沖區(qū)
    int y_size = avcodec_context->width * avcodec_context->height;
    uint8_t *out_buffer = (uint8_t *) av_malloc(buffer_size);

    //打開輸入文件
    const char *cinFilePath = [inFilePath cStringUsingEncoding:NSUTF8StringEncoding];
    FILE *in_file = fopen(cinFilePath, "rb");
    if (in_file == NULL) {
        NSLog(@"文件不存在");
        return;
    }

    //開辟一塊內(nèi)存空間->av_frame_alloc
    AVFrame *av_frame = av_frame_alloc();
    //設(shè)置緩沖區(qū)和AVFrame類型保持一致->填充數(shù)據(jù) linesize:yuv/rgb這些值
    av_image_fill_arrays(av_frame->data,
                         av_frame->linesize,
                         out_buffer,
                         avcodec_context->pix_fmt,
                         avcodec_context->width,
                         avcodec_context->height,
                         1);

音頻緩沖區(qū):

    AVFrame *av_frame = av_frame_alloc();
    av_frame->nb_samples = avcodec_context->frame_size;
    av_frame->format = avcodec_context->sample_fmt;

    //得到音頻采樣數(shù)據(jù)緩沖區(qū)大小
    int buffer_size = av_samples_get_buffer_size(NULL,
                                                 avcodec_context->channels,
                                                 avcodec_context->frame_size,
                                                 avcodec_context->sample_fmt,
                                                 1);
    //創(chuàng)建緩沖區(qū)
    uint8_t *out_buffer = (uint8_t *) av_malloc(buffer_size);
    avcodec_fill_audio_frame(av_frame,
                             avcodec_context->channels,
                             avcodec_context->sample_fmt,
                             (const uint8_t *)out_buffer,
                             buffer_size,
                             1);
9.開始編碼。

視頻編碼:

    AVPacket *av_packet = (AVPacket *) av_malloc(buffer_size);
    int i = 0;
    int result = 0;
    int current_frame_index = 1;

    while (true) {
        //從yuv文件里面讀取緩沖區(qū) 讀取大形岸瘛:y_size * 3 / 2
        if (fread(out_buffer, 1, y_size * 3 / 2, in_file) <= 0) {
            NSLog(@"讀取完畢...");
            break;
        } else if (feof(in_file)) {
            break;
        }

        // 將緩沖區(qū)數(shù)據(jù)->轉(zhuǎn)成AVFrame類型
        //給AVFrame填充數(shù)據(jù) void * restrict->->轉(zhuǎn)成->AVFrame->ffmpeg數(shù)據(jù)類型
        //Y值 4
        av_frame->data[0] = out_buffer;
        //U值
        av_frame->data[1] = out_buffer + y_size;
        //V值 1
        av_frame->data[2] = out_buffer + y_size * 5 / 4;
        av_frame->pts = i;
        //注意時間戳
        i++;
        //總結(jié):這樣一來我們的AVFrame就有數(shù)據(jù)了

        //發(fā)送一幀視頻像素數(shù)據(jù)
        int send_result = avcodec_send_frame(avcodec_context, av_frame);
        int receive_result = 0;
        if (send_result == AVERROR(EAGAIN)) {
            while (receive_result != AVERROR(EAGAIN)) {
                receive_result = avcodec_receive_packet(avcodec_context, av_packet);
            }
        } else {
            receive_result = avcodec_receive_packet(avcodec_context, av_packet);
            if (receive_result == AVERROR(EAGAIN)) {
                continue;
            }
        }

        //編碼成功
        //將視頻壓縮數(shù)據(jù)->寫入到輸出文件中->outFilePath
        av_packet->stream_index = av_video_stream->index;
        result = av_write_frame(avformat_context, av_packet);
        NSLog(@"當(dāng)前是第%d幀", current_frame_index);
        current_frame_index++;
        //是否輸出成功
        if (result < 0) {
             NSLog(@"輸出一幀數(shù)據(jù)失敗");
             return;
        }
    }
    //寫入剩余幀數(shù)據(jù)->可能沒有
    flush_encoder(avformat_context, 0);

    //寫入文件尾部信息
    av_write_trailer(avformat_context);

音頻編碼:

    AVPacket *av_packet = (AVPacket *) av_malloc(buffer_size);

   //循環(huán)讀取音頻幀
    int frame_current = 1;
    int i = 0, ret = 0;

    //即將AVFrame(存儲pcm采樣數(shù)據(jù))編碼為AVPacket (acc)
    while (true) {

        // 讀取一幀音頻采樣數(shù)據(jù)
        if (fread(out_buffer, 1, buffer_size, in_file) <=0) {
            NSLog(@"讀取數(shù)據(jù)失敗");
            break;
        } else if (feof(in_file)) {
            break;
        }

        //設(shè)置音頻采樣數(shù)據(jù)格式
        av_frame->data[0] = out_buffer;
        av_frame->pts = i;
        i++;

        // 編碼一幀音頻采樣數(shù)據(jù)->得到音頻壓縮數(shù)據(jù)->aac

        // 發(fā)送一幀音頻采樣數(shù)據(jù)
        ret = avcodec_send_frame(avcodec_context, av_frame);
        if (ret != 0) {
            NSLog(@"發(fā)送數(shù)據(jù)失敗");
        }

        // 編碼一幀音頻采樣數(shù)據(jù)
        ret = avcodec_receive_packet(avcodec_context, av_packet);
        if (ret == 0) {
            /**第十一步:將編碼后的音頻碼流寫入文件*/
            NSLog(@"當(dāng)前編碼到了第%d幀", frame_current);
            frame_current++;
            av_packet->stream_index = audio_st->index;
            ret = av_write_frame(avformat_context, av_packet);
            if (ret < 0) {
                NSLog(@"main","寫入失敗");
                return;
            }
        } else {
            NSLog(@"無采樣數(shù)據(jù)編碼");
            return;
        }
    }

    //輸入的像素數(shù)據(jù)讀取完成后調(diào)用此函數(shù)碴开。用于輸出編碼器中剩余的AVPacket。
    ret = flush_encoder(avformat_context, 0);
    if (ret < 0) {
        NSLog(@"無剩余壓縮包");
        return;
    }

    // 寫文件尾(對于某些沒有文件頭的封裝格式博秫,不需要此函數(shù)潦牛。比如說MPEG2TS)
    av_write_trailer(avformat_context);
10.釋放內(nèi)存。
    avcodec_close(avcodec_context);
    av_free(av_frame);
    av_free(out_buffer);
    av_free_packet(av_packet);
    avio_close(avformat_context->pb);
    avformat_free_context(avformat_context);
    fclose(in_file);

注釋來自這里

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末挡育,一起剝皮案震驚了整個濱河市巴碗,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌即寒,老刑警劉巖橡淆,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異母赵,居然都是意外死亡逸爵,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門市咽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來痊银,“玉大人抵蚊,你說我怎么就攤上這事施绎。” “怎么了贞绳?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵谷醉,是天一觀的道長。 經(jīng)常有香客問我冈闭,道長俱尼,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任萎攒,我火速辦了婚禮遇八,結(jié)果婚禮上矛绘,老公的妹妹穿的比我還像新娘。我一直安慰自己刃永,他們只是感情好货矮,可當(dāng)我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著斯够,像睡著了一般囚玫。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上读规,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天抓督,我揣著相機與錄音,去河邊找鬼束亏。 笑死铃在,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的碍遍。 我是一名探鬼主播涌穆,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼雀久!你這毒婦竟也來了宿稀?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤赖捌,失蹤者是張志新(化名)和其女友劉穎祝沸,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體越庇,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡罩锐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了卤唉。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片涩惑。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖桑驱,靈堂內(nèi)的尸體忽然破棺而出竭恬,到底是詐尸還是另有隱情,我是刑警寧澤熬的,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布痊硕,位于F島的核電站,受9級特大地震影響押框,放射性物質(zhì)發(fā)生泄漏岔绸。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望盒揉。 院中可真熱鬧晋被,春花似錦、人聲如沸刚盈。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽扁掸。三九已至翘县,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間谴分,已是汗流浹背锈麸。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留牺蹄,地道東北人忘伞。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像沙兰,于是被迫代替她去往敵國和親氓奈。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,871評論 2 354