1 #include "FfmpegHelper.h"
5 #define FLOGE(...) av_log(NULL, AV_LOG_ERROR, __VA_ARGS__)
6 #define FLOGD(...) av_log(NULL, AV_LOG_INFO, __VA_ARGS__)
8 FfmpegHelper* FfmpegHelper::singleton = NULL;
9 bool FfmpegHelper::isInit = false;
12 FfmpegHelper::FfmpegHelper(JavaVM *vm, jclass cls)
14 , ai_suanzi_rtmpclient_FfmpegHelper(cls)
19 jint FfmpegHelper::nativeOnLoad(JavaVM * vm, void* reserved)
22 if(vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK){
27 if (env) local_ref = env->FindClass ("ai/suanzi/rtmpclient/FfmpegHelper");
28 jclass global_ref = reinterpret_cast<jclass> (env->NewGlobalRef (local_ref));
29 singleton = new FfmpegHelper(vm, global_ref);
30 return JNI_VERSION_1_6;
33 void FfmpegHelper::av_log_cb (void *ptr, int level, const char* fmt, va_list vl)
35 static int print_prefix = 1;
37 av_log_format_line(ptr, level, fmt, vl, line, sizeof(line), &print_prefix);
39 if (level <= AV_LOG_WARNING){
40 if (singleton) singleton->javaPrint(line, 1);
41 } else if(level <= AV_LOG_INFO){
42 if (singleton) singleton->javaPrint(line, 0);
49 void FfmpegHelper::javaPrint(const char* str, int level)
52 if(this->jvm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK){
55 jmethodID mid = env->GetStaticMethodID(ai_suanzi_rtmpclient_FfmpegHelper, "javaPrint", "(Ljava/lang/String;I)V");
56 jstring jstr = env->NewStringUTF(str);
57 env->CallStaticVoidMethod(ai_suanzi_rtmpclient_FfmpegHelper, mid, jstr, level);
58 env->DeleteLocalRef(jstr);
61 void FfmpegHelper::init()
63 av_log_set_callback(av_log_cb);
64 av_log_set_level(AV_LOG_DEBUG);
65 FLOGD("########## Ffmpeg Init ##########");
66 unsigned int v = avutil_version();
67 FLOGD("libavutil - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
68 v = avcodec_version();
69 FLOGD("libavcodec - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
70 v = avformat_version();
71 FLOGD("libavformat - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
72 v = avdevice_version();
73 FLOGD("libavdevice - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
76 //avdevice_register_all();
78 if((ret = avformat_network_init()) != 0){
79 FLOGE("avformat_network_init, error:%s(%d)", av_err2str(ret), ret);
84 int FfmpegHelper::initEncoder(int width, int height, const char* outpath)
87 FLOGE("-----------> FfmpegHelper::initEncoder");
88 FLOGD("initEncoder - width=%d, height=%d, url=%s", width, height, outpath);
94 avformat_alloc_output_context2(&formatCtx, NULL, "flv", outpath);
97 if((codec = avcodec_find_encoder(AV_CODEC_ID_H264)) == NULL){
98 FLOGE("Can not find encoder!\n");
101 codecCtx = avcodec_alloc_context3(codec);
102 codecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
103 codecCtx->width = width;
104 codecCtx->height = height;
105 codecCtx->time_base.num = 1;
106 codecCtx->time_base.den = 30;
107 codecCtx->bit_rate = 800000;
108 codecCtx->gop_size = 300;
109 if (formatCtx->oformat->flags & AVFMT_GLOBALHEADER) /* Some formats want stream headers to be separate. */
110 codecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
112 //pCodecCtx->me_range = 16;
113 //pCodecCtx->max_qdiff = 4;
114 //pCodecCtx->qcompress = 0.6;
118 codecCtx->max_b_frames = 3;
119 // Set H264 preset and tune
120 AVDictionary *param = 0;
121 av_dict_set(¶m, "preset", "ultrafast", 0);
122 av_dict_set(¶m, "tune", "zerolatency", 0);
123 if ((ret = avcodec_open2(codecCtx, codec, ¶m)) < 0){
124 LOGE("Failed to open encoder!, error:%s(%d)\n", av_err2str(ret), ret);
128 //Add a new stream to output,should be called by the user before avformat_write_header() for muxing
129 if ((vStream = avformat_new_stream(formatCtx, codec)) == NULL){
130 FLOGE("avformat_new_stream - error");
133 vStream->time_base.num = 1;
134 vStream->time_base.den = 30;
135 vStream->codec = codecCtx;
137 //Open output URL,set before avformat_write_header() for muxing
138 if (( ret = avio_open(&formatCtx->pb, outpath, AVIO_FLAG_READ_WRITE)) < 0){
139 LOGE("Failed to open output file! error :%s(%d)\n", av_err2str(ret), ret);
143 if((ret = avformat_write_header(formatCtx, NULL)) != 0){ //Write File Header
144 LOGE("avformat_write_header error :%s(%d)\n", av_err2str(ret), ret);
147 startTime = av_gettime();
153 int FfmpegHelper::processFrame(uint8_t* data)
156 int y_length = pWidth * pHeight;
157 pFrameYUV = av_frame_alloc();
158 uint8_t *outBuf = (uint8_t *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P, codecCtx->width, codecCtx->height, 1));
160 FLOGE("av_malloc, error");
161 av_frame_free(&pFrameYUV);
164 if((ret = av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, outBuf, AV_PIX_FMT_YUV420P, codecCtx->width, codecCtx->height, 1)) < 0){
165 FLOGE("av_image_fill_arrays - error: %s(%d).", av_err2str(ret), ret);
166 av_frame_free(&pFrameYUV);
171 memcpy(pFrameYUV->data[0], data, y_length);
172 for (int i = 0; i < y_length / 4; i++){
173 *(pFrameYUV->data[2] + i) = *(data + y_length + i * 2);
174 *(pFrameYUV->data[1] + i) = *(data + y_length + i * 2 + 1);
177 pFrameYUV->format = AV_PIX_FMT_YUV420P;
178 pFrameYUV->width = pWidth;
179 pFrameYUV->height = pHeight;
184 av_init_packet(&encPkt);
187 if((ret = avcodec_encode_video2(codecCtx, &encPkt, pFrameYUV, &got_frame)) < 0){
188 FLOGE("avcodec_encode_video2 - error: %s(%d).", av_err2str(ret), ret);
189 av_frame_free(&pFrameYUV);
192 av_frame_free(&pFrameYUV);
195 if (frameCnt % (15 * 60) == 0){
196 FLOGD("Succeed to encode frame: %5d\tsize:%5d\n", frameCnt, encPkt.size);
199 encPkt.stream_index = vStream->index;
202 AVRational time_base = formatCtx->streams[0]->time_base;//{ 1, 1000 };
203 AVRational r_framerate = {60, 2 };//{ 50, 2 };
204 AVRational time_base_q = { 1, AV_TIME_BASE };
205 //Duration between 2 frames (us)
206 int64_t calc_duration = (double)(AV_TIME_BASE)*(1 / av_q2d(r_framerate)); //内部时间戳
208 //enc_pkt.pts = (double)(framecnt*calc_duration)*(double)(av_q2d(time_base_q)) / (double)(av_q2d(time_base));
209 encPkt.pts = av_rescale_q(frameCnt*calc_duration, time_base_q, time_base);
210 encPkt.dts = encPkt.pts;
211 encPkt.duration = av_rescale_q(calc_duration, time_base_q, time_base); //(double)(calc_duration)*(double)(av_q2d(time_base_q)) / (double)(av_q2d(time_base));
215 int64_t pts_time = av_rescale_q(encPkt.dts, time_base, time_base_q);
216 int64_t now_time = av_gettime() - startTime;
217 if (pts_time > now_time)
218 av_usleep(pts_time - now_time);
220 if((ret = av_interleaved_write_frame(formatCtx, &encPkt)) < 0){
221 FLOGE("av_interleaved_write_frame - error: %s(%d)", av_err2str(ret), ret);
224 av_packet_unref(&encPkt);
230 int FfmpegHelper::close()
233 avcodec_close(vStream->codec);
235 avio_close(formatCtx->pb);
236 avformat_free_context(formatCtx);
238 FLOGE("<----------- FfmpegHelper::close ");
243 jint FfmpegHelper::nativeInitEncoder(JNIEnv *env, jclass cls, jint width, jint height, jstring url)
245 const char* output = env->GetStringUTFChars(url, 0);
247 if (singleton) ret = singleton->initEncoder(width, height, output);
248 env->ReleaseStringUTFChars(url, output);
252 jint FfmpegHelper::nativeProcessFrame(JNIEnv *env, jclass cls, jbyteArray data)
254 jbyte* buf = (jbyte*)env->GetByteArrayElements(data, 0);
256 if(singleton) ret = singleton->processFrame((uint8_t *)buf);
260 jint FfmpegHelper::nativeClose()
262 if(singleton) return singleton->close();