1df52e52f9dd0be6c34b1a3efe94bc80f9a548b5
[rtmpclient.git] / app / src / main / jni / FfmpegHelper.cpp
1 #include "FfmpegHelper.h"
2 #include "log.h"
3 #include <string>
4
5 #define FLOGE(...) av_log(NULL, AV_LOG_ERROR, __VA_ARGS__)
6 #define FLOGD(...) av_log(NULL, AV_LOG_INFO, __VA_ARGS__)
7
8 FfmpegHelper* FfmpegHelper::singleton = NULL;
9 bool FfmpegHelper::isInit = false;
10
11
12 FfmpegHelper::FfmpegHelper(JavaVM *vm, jclass cls)
13 : jvm(vm)
14 , ai_suanzi_rtmpclient_FfmpegHelper(cls)
15 {
16 }
17
18
19 jint FfmpegHelper::nativeOnLoad(JavaVM * vm, void* reserved)
20 {
21     JNIEnv* env;
22     if(vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK){
23         return -1;
24     }
25
26     jclass local_ref = 0;
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;
31 }
32
33 void FfmpegHelper::av_log_cb (void *ptr, int level, const char* fmt, va_list vl)
34
35     static int print_prefix = 1;
36     char line[1024];
37     av_log_format_line(ptr, level, fmt, vl, line, sizeof(line), &print_prefix);
38
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);
43         // LOGE("%s", line);
44     } else {
45
46     }
47 }
48
49 void FfmpegHelper::javaPrint(const char* str, int level)
50 {
51     JNIEnv* env = 0;
52     if(this->jvm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK){
53         return;
54     }
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);
59 }
60
61 void FfmpegHelper::init()
62 {    
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));
74
75     av_register_all();
76     //avdevice_register_all();
77     int ret = 0;
78     if((ret = avformat_network_init()) != 0){
79         FLOGE("avformat_network_init, error:%s(%d)", av_err2str(ret), ret);
80     }
81     isInit = true;
82 }
83
84 int FfmpegHelper::initEncoder(int width, int height, const char* outpath)
85 {
86     if(!isInit) init();
87     FLOGE("-----------> FfmpegHelper::initEncoder");
88     FLOGD("initEncoder - width=%d, height=%d, url=%s", width, height, outpath);
89
90     pWidth = width;
91     pHeight = height;
92     int ret = 0;
93
94         avformat_alloc_output_context2(&formatCtx, NULL, "flv", outpath);
95
96     // initial encoder
97         if((codec = avcodec_find_encoder(AV_CODEC_ID_H264)) == NULL){
98                 FLOGE("Can not find encoder!\n");
99                 return -1;
100         }
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;
111         //H264 codec param
112         //pCodecCtx->me_range = 16;
113         //pCodecCtx->max_qdiff = 4;
114         //pCodecCtx->qcompress = 0.6;
115         codecCtx->qmin = 10;
116         codecCtx->qmax = 51;
117         //Optional Param
118         codecCtx->max_b_frames = 3;
119         // Set H264 preset and tune
120         AVDictionary *param = 0;
121         av_dict_set(&param, "preset", "ultrafast", 0);
122         av_dict_set(&param, "tune", "zerolatency", 0);
123         if ((ret = avcodec_open2(codecCtx, codec, &param)) < 0){
124                 LOGE("Failed to open encoder!, error:%s(%d)\n", av_err2str(ret), ret);
125                 return -1;
126         }
127
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");
131         return -1;
132     }
133         vStream->time_base.num = 1;
134         vStream->time_base.den = 30;
135         vStream->codec = codecCtx;
136
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);
140                 return -1;
141         }
142
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);
145         return -1;
146     }
147     startTime = av_gettime();
148     frameCnt = 0;
149     return 0;
150 }
151
152
153 int FfmpegHelper::processFrame(uint8_t* data)
154 {
155     int ret = 0;
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));
159     if(outBuf == NULL) {
160         FLOGE("av_malloc, error");
161         av_frame_free(&pFrameYUV);
162         return -1;
163     }
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);
167         return -1;
168     }
169
170     // NV21 to YUV420P
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);
175     }
176
177         pFrameYUV->format = AV_PIX_FMT_YUV420P;
178         pFrameYUV->width = pWidth; 
179         pFrameYUV->height = pHeight;
180
181
182     encPkt.data = NULL;
183     encPkt.size = 0;
184     av_init_packet(&encPkt);
185     int got_frame = 0;
186
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);
190         return -1;
191     }
192     av_frame_free(&pFrameYUV);
193
194     if(got_frame == 1){
195         if (frameCnt % (15 * 60) == 0){
196                     FLOGD("Succeed to encode frame: %5d\tsize:%5d\n", frameCnt, encPkt.size);
197         }
198         frameCnt++;
199                 encPkt.stream_index = vStream->index;
200
201         // PTS
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));       //内部时间戳
207                 //Parameters
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));
212                 encPkt.pos = -1;
213
214                 //Delay
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);
219
220                 if((ret = av_interleaved_write_frame(formatCtx, &encPkt)) < 0){
221             FLOGE("av_interleaved_write_frame - error: %s(%d)", av_err2str(ret), ret);
222             return -1;
223         }
224                 av_packet_unref(&encPkt);
225     }
226     av_free(outBuf);
227     return 0;
228 }
229
230 int FfmpegHelper::close()
231 {
232     if(vStream)
233         avcodec_close(vStream->codec);
234     if (formatCtx){
235         avio_close(formatCtx->pb);
236         avformat_free_context(formatCtx);
237     }
238     FLOGE("<----------- FfmpegHelper::close ");
239     return 0;
240 }
241
242
243 jint FfmpegHelper::nativeInitEncoder(JNIEnv *env, jclass cls, jint width, jint height, jstring url)
244 {
245     const char* output = env->GetStringUTFChars(url, 0);
246     int ret = 0;
247     if (singleton)  ret = singleton->initEncoder(width, height, output);
248     env->ReleaseStringUTFChars(url, output);
249     return ret;
250 }
251
252 jint FfmpegHelper::nativeProcessFrame(JNIEnv *env, jclass cls, jbyteArray data)
253 {
254         jbyte* buf = (jbyte*)env->GetByteArrayElements(data, 0);
255     int ret = 0;
256     if(singleton)  ret = singleton->processFrame((uint8_t *)buf);
257     return ret;
258 }
259
260 jint FfmpegHelper::nativeClose()
261 {
262     if(singleton) return singleton->close();
263     return 0;
264 }