2 // Created by Peng Li on 30/4/2018.
4 #include "ai_suanzi_rtmpclient_Ffmpeg.h"
5 #include <android/native_window.h>
6 #include <android/native_window_jni.h>
15 #include "libavformat/avformat.h"
16 #include "libavcodec/avcodec.h"
17 #include "libswscale/swscale.h"
18 #include "libavutil/imgutils.h"
19 #include "libavutil/time.h"
20 #include "libavdevice/avdevice.h"
24 AVFormatContext *ofmt_ctx;
26 AVCodecContext* pCodecCtx;
32 void custom_log(void *ptr, int level, const char* fmt, va_list vl){
34 /*FILE *fp=fopen("/storage/emulated/0/av_log.txt","a+");
42 static int print_prefix = 1;
43 //static char prev[1024];
46 av_log_format_line(ptr, level, fmt, vl, line, sizeof(line), &print_prefix);
49 //sanitize((uint8_t *)line);
51 if (level <= AV_LOG_WARNING){
65 JNIEXPORT void JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_init__ (JNIEnv *env, jobject obj ){
66 LOGE("########## Ffmpeg Init ##########");
67 unsigned int v = avutil_version();
68 LOGE("libavutil - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
69 v = avcodec_version();
70 LOGE("libavcodec - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
71 v = avformat_version();
72 LOGE("libavformat - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
73 v = avdevice_version();
74 LOGE("libavdevice - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
76 av_log_set_level(AV_LOG_TRACE);
78 avdevice_register_all();
79 avformat_network_init();
80 av_log_set_callback(custom_log);
84 JNIEXPORT jstring JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_getVersion (JNIEnv *env, jobject obj) {
85 jint v = avformat_version();
86 LOGE("######### Ffmpeg JNI version i= %d", v);
88 system("su -c chmod 666 /dev/video0");
90 LOGE("######### Ffmpeg JNI version i= %d", v);
93 /*AVFormatContext *pFormatCtx = avformat_alloc_context();
94 avdevice_register_all();
95 av_log_set_callback(custom_log);
96 AVInputFormat *ifmt=av_find_input_format("video4linux2");
97 LOGE("===%s===", ifmt->name);
98 if(avformat_open_input(&pFormatCtx,"/dev/video0",ifmt,NULL)!=0){
99 LOGE("Couldn't open input stream.\n");
100 return env->NewStringUTF("===== error =======");
105 return env->NewStringUTF("====== Ffmpeg call =======");
108 JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_init (JNIEnv *env, jobject obj, jint width, jint height) {
110 //const char* out_path = "/storage/emulated/0/Movies/output.flv";
112 //const char* out_path = "rtmp://192.168.1.35:1935/myapp/suanzi";
113 const char* out_path = "rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90_cameraid";
115 // const char* out_path = "/storage/sdcard0/output.flv";
119 LOGE("Ffmpeg init, width=%d, heigh=%d", width, height);
123 y_length=width*height;
124 uv_length=width*height/4;
130 avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_path);
131 //output encoder initialize
132 pCodec = avcodec_find_encoder(AV_CODEC_ID_H264);
134 LOGE("Can not find encoder!\n");
137 pCodecCtx = avcodec_alloc_context3(pCodec);
138 pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
139 pCodecCtx->width = width;
140 pCodecCtx->height = height;
141 pCodecCtx->time_base.num = 1;
142 pCodecCtx->time_base.den = 30;
143 pCodecCtx->bit_rate = 800000;
144 pCodecCtx->gop_size = 300;
145 /* Some formats want stream headers to be separate. */
146 if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
147 pCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
150 //pCodecCtx->me_range = 16;
151 //pCodecCtx->max_qdiff = 4;
152 //pCodecCtx->qcompress = 0.6;
153 pCodecCtx->qmin = 10;
154 pCodecCtx->qmax = 51;
156 pCodecCtx->max_b_frames = 3;
157 // Set H264 preset and tune
158 AVDictionary *param = 0;
159 av_dict_set(¶m, "preset", "ultrafast", 0);
160 av_dict_set(¶m, "tune", "zerolatency", 0);
162 if (avcodec_open2(pCodecCtx, pCodec, ¶m) < 0){
163 LOGE("Failed to open encoder!\n");
167 //Add a new stream to output,should be called by the user before avformat_write_header() for muxing
168 video_st = avformat_new_stream(ofmt_ctx, pCodec);
169 if (video_st == NULL){
172 video_st->time_base.num = 1;
173 video_st->time_base.den = 30;
174 video_st->codec = pCodecCtx;
176 //Open output URL,set before avformat_write_header() for muxing
178 if (( ret = avio_open(&ofmt_ctx->pb, out_path, AVIO_FLAG_READ_WRITE)) < 0){
179 LOGE("Failed to open output file! return :%d\n", ret);
184 avformat_write_header(ofmt_ctx, NULL);
186 start_time = av_gettime();
190 JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_flush (JNIEnv *env, jobject obj){
194 if (!(ofmt_ctx->streams[0]->codec->codec->capabilities & CODEC_CAP_DELAY))
199 av_init_packet(&enc_pkt);
200 ret = avcodec_encode_video2(ofmt_ctx->streams[0]->codec, &enc_pkt,
208 LOGE("Flush Encoder: Succeed to encode 1 frame!\tsize:%5d\n", enc_pkt.size);
211 AVRational time_base = ofmt_ctx->streams[0]->time_base;//{ 1, 1000 };
212 AVRational r_framerate1 = { 60, 2 };
213 AVRational time_base_q = { 1, AV_TIME_BASE };
214 //Duration between 2 frames (us)
215 int64_t calc_duration = (double)(AV_TIME_BASE)*(1 / av_q2d(r_framerate1)); //内部时间戳
217 enc_pkt.pts = av_rescale_q(framecnt*calc_duration, time_base_q, time_base);
218 enc_pkt.dts = enc_pkt.pts;
219 enc_pkt.duration = av_rescale_q(calc_duration, time_base_q, time_base);
221 //转换PTS/DTS(Convert PTS/DTS)
224 ofmt_ctx->duration = enc_pkt.duration * framecnt;
226 /* mux encoded frame */
227 ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
232 av_write_trailer(ofmt_ctx);
236 JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_close (JNIEnv *env, jobject obj){
238 avcodec_close(video_st->codec);
239 avio_close(ofmt_ctx->pb);
240 avformat_free_context(ofmt_ctx);
244 JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_process (JNIEnv *env, jobject obj, jbyteArray yuv){
249 //LOGE(" process data - ffmpeg");
250 pFrameYUV = av_frame_alloc();
251 uint8_t *out_buffer = (uint8_t *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
252 avpicture_fill((AVPicture *)pFrameYUV, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
254 //安卓摄像头数据为NV21格式,此处将其转换为YUV420P格式
255 jbyte* in= (jbyte*)env->GetByteArrayElements(yuv,0);
256 memcpy(pFrameYUV->data[0],in,y_length);
257 for(i=0;i<uv_length;i++)
259 *(pFrameYUV->data[2]+i)=*(in+y_length+i*2);
260 *(pFrameYUV->data[1]+i)=*(in+y_length+i*2+1);
263 pFrameYUV->format = AV_PIX_FMT_YUV420P;
264 pFrameYUV->width = yuv_width;
265 pFrameYUV->height = yuv_height;
269 av_init_packet(&enc_pkt);
270 ret = avcodec_encode_video2(pCodecCtx, &enc_pkt, pFrameYUV, &enc_got_frame);
271 av_frame_free(&pFrameYUV);
273 if (enc_got_frame == 1){
274 //LOGE("Succeed to encode frame: %5d\tsize:%5d\n", framecnt, enc_pkt.size);
276 enc_pkt.stream_index = video_st->index;
279 AVRational time_base = ofmt_ctx->streams[0]->time_base;//{ 1, 1000 };
280 AVRational r_framerate1 = {60, 2 };//{ 50, 2 };
281 AVRational time_base_q = { 1, AV_TIME_BASE };
282 //Duration between 2 frames (us)
283 int64_t calc_duration = (double)(AV_TIME_BASE)*(1 / av_q2d(r_framerate1)); //内部时间戳
285 //enc_pkt.pts = (double)(framecnt*calc_duration)*(double)(av_q2d(time_base_q)) / (double)(av_q2d(time_base));
286 enc_pkt.pts = av_rescale_q(framecnt*calc_duration, time_base_q, time_base);
287 enc_pkt.dts = enc_pkt.pts;
288 enc_pkt.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));
292 int64_t pts_time = av_rescale_q(enc_pkt.dts, time_base, time_base_q);
293 int64_t now_time = av_gettime() - start_time;
294 if (pts_time > now_time)
295 av_usleep(pts_time - now_time);
297 ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
298 av_free_packet(&enc_pkt);
303 JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_play (JNIEnv *env, jobject obj, jobject surface, jstring fname){
309 LOGE("###### video play #####");
310 // char * file_name = "/storage/emulated/0/Movies/big_buck_bunny_720p_10mb.mp4";
311 const char * file_name = env->GetStringUTFChars(fname, 0);
314 avdevice_register_all();
317 AVFormatContext * pFormatCtx = avformat_alloc_context();
321 av_log_set_callback(custom_log);
323 AVInputFormat *ifmt=av_find_input_format("video4linux2");
324 LOGE("===%s===", ifmt->name);
325 if(avformat_open_input(&pFormatCtx,"/dev/video0",ifmt,NULL)!=0){
326 LOGE("Couldn't open file:\n");
327 return -1; // Couldn't open file
335 if(avformat_open_input(&pFormatCtx, file_name, NULL, NULL)!=0) {
337 LOGE("Couldn't open file:%s\n", file_name);
338 return -1; // Couldn't open file
341 // Retrieve stream information
342 if(avformat_find_stream_info(pFormatCtx, NULL)<0) {
343 LOGE("Couldn't find stream information.");
347 // Find the first video stream
348 int videoStream = -1, i;
349 for (i = 0; i < pFormatCtx->nb_streams; i++) {
350 if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO
351 && videoStream < 0) {
355 if(videoStream==-1) {
356 LOGE("Didn't find a video stream.");
357 return -1; // Didn't find a video stream
360 // Get a pointer to the codec context for the video stream
361 AVCodecContext * pCodecCtx = pFormatCtx->streams[videoStream]->codec;
362 LOGE("============= %d ========",__LINE__);
363 // Find the decoder for the video stream
364 AVCodec * pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
366 LOGE("Codec not found.");
367 return -1; // Codec not found
370 if(avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
371 LOGE("Could not open codec.");
372 return -1; // Could not open codec
376 ANativeWindow* nativeWindow = ANativeWindow_fromSurface(env, surface);
379 int videoWidth = pCodecCtx->width;
380 int videoHeight = pCodecCtx->height;
382 // 设置native window的buffer大小,可自动拉伸
383 ANativeWindow_setBuffersGeometry(nativeWindow, videoWidth, videoHeight, WINDOW_FORMAT_RGBA_8888);
384 ANativeWindow_Buffer windowBuffer;
386 if(avcodec_open2(pCodecCtx, pCodec, NULL)<0) {
387 LOGE("Could not open codec.");
388 return -1; // Could not open codec
391 LOGE("stream format:%s", pFormatCtx->iformat->name);
392 LOGE("duration :%lld", (pFormatCtx->duration) / 1000000);
393 LOGE("Width, Height:%d x %d", pCodecCtx->width, pCodecCtx->height);
394 LOGE("Decoder name:%s", pCodec->name);
396 // Allocate video frame
397 AVFrame * pFrame = av_frame_alloc();
400 AVFrame * pFrameRGBA = av_frame_alloc();
401 if(pFrameRGBA == NULL || pFrame == NULL) {
402 LOGE("Could not allocate video frame.");
406 // Determine required buffer size and allocate buffer
407 int numBytes=av_image_get_buffer_size(AV_PIX_FMT_RGBA, pCodecCtx->width, pCodecCtx->height, 1);
408 uint8_t * buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
409 av_image_fill_arrays(pFrameRGBA->data, pFrameRGBA->linesize, buffer, AV_PIX_FMT_RGBA,
410 pCodecCtx->width, pCodecCtx->height, 1);
412 // 由于解码出来的帧格式不是RGBA的,在渲染之前需要进行格式转换
413 struct SwsContext *sws_ctx = sws_getContext(pCodecCtx->width,
426 while(av_read_frame(pFormatCtx, &packet)>=0) {
427 // Is this a packet from the video stream?
428 if(packet.stream_index==videoStream) {
430 // Decode video frame
431 avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
433 // 并不是decode一次就可解码出一帧
436 // lock native window buffer
437 ANativeWindow_lock(nativeWindow, &windowBuffer, 0);
440 sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,
441 pFrame->linesize, 0, pCodecCtx->height,
442 pFrameRGBA->data, pFrameRGBA->linesize);
445 uint8_t * dst = (uint8_t*) windowBuffer.bits;
446 int dstStride = windowBuffer.stride * 4;
447 uint8_t * src = (uint8_t*) (pFrameRGBA->data[0]);
448 int srcStride = pFrameRGBA->linesize[0];
450 // 由于window的stride和帧的stride不同,因此需要逐行复制
452 for (h = 0; h < videoHeight; h++) {
453 memcpy(dst + h * dstStride, src + h * srcStride, srcStride);
456 ANativeWindow_unlockAndPost(nativeWindow);
460 av_packet_unref(&packet);
466 // Free the YUV frame
470 avcodec_close(pCodecCtx);
472 // Close the video file
473 avformat_close_input(&pFormatCtx);
475 env->ReleaseStringUTFChars(fname, file_name);
479 JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_push (JNIEnv *env, jobject obj, jobject surface) {
482 av_log_set_level(AV_LOG_TRACE);
484 avformat_network_init();
485 avdevice_register_all();
488 LOGE("====push=====");
489 // av_log_set_callback(custom_log);
493 AVFormatContext *pFormatCtx = avformat_alloc_context();
495 AVInputFormat *ifmt = av_find_input_format("video4linux2");
496 if((ret = avformat_open_input(&pFormatCtx, "/dev/video0", ifmt, NULL)) != 0) {
497 // if((ret = avformat_open_input(&pFormatCtx, "/dev/bus/usb/003/007", ifmt, NULL)) != 0) {
499 LOGE("could not open file11, ret=%d, error=%s,", ret, av_err2str(ret));
503 if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
504 LOGE( "could not find stream info");
508 av_dump_format(pFormatCtx, 0, "0", 0);
511 int video_index = -1;
512 if((video_index = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0)) < 0){
517 AVCodecContext *pCodecCtx = pFormatCtx->streams[video_index]->codec;
518 if(avcodec_open2(pCodecCtx, dec, NULL) <0){
525 //const char* out_path = "rtmp://192.168.1.35:1935/myapp/peng2";
526 const char* out_path = "rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90_cameraid";
528 AVFormatContext *ofmt_ctx;
529 avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_path);
530 AVCodec *oDec = avcodec_find_encoder(AV_CODEC_ID_H264);
532 LOGE("Can not find endoder");
536 AVCodecContext *oCodecCtx = avcodec_alloc_context3(oDec);
537 oCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
538 oCodecCtx->width = pCodecCtx->width;
539 oCodecCtx->height = pCodecCtx->height;
540 oCodecCtx->time_base.num = 1;
541 oCodecCtx->time_base.den = 30;
542 oCodecCtx->bit_rate = 800000;
543 oCodecCtx->gop_size = 300;
544 if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
545 oCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
546 oCodecCtx->qmin = 10;
547 oCodecCtx->qmax = 51;
548 oCodecCtx->max_b_frames = 3;
550 AVDictionary *params = 0;
551 av_dict_set(¶ms, "preset", "ultrafast", 0);
552 av_dict_set(¶ms, "tune", "zerolatency", 0);
554 if (avcodec_open2(oCodecCtx, oDec, ¶ms) < 0){
555 LOGE("Failed to open encoder");
559 AVStream *videoStream = avformat_new_stream(ofmt_ctx, oDec);
560 if (videoStream == NULL){
564 videoStream->time_base.num = 1;
565 videoStream->time_base.den = 30;
566 videoStream->codec = oCodecCtx;
568 if((ret = avio_open(&ofmt_ctx->pb, out_path, AVIO_FLAG_READ_WRITE)) < 0){
569 LOGE("Failed open out file22 erro=%d, ==%s==", ret, av_err2str(ret) );
570 //LOGE("Failed open out file22 erro=%d", ret);
574 avformat_write_header(ofmt_ctx, NULL);
581 AVFrame *pFrame, *pFrameYUV;
582 pFrame = av_frame_alloc();
583 pFrameYUV = av_frame_alloc();
585 int num_bytes = av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);
586 uint8_t *buffer = (uint8_t *)av_malloc(num_bytes * sizeof(uint8_t));
587 av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);
589 pFrameYUV->format = AV_PIX_FMT_YUV420P;
590 pFrameYUV->width = pCodecCtx->width;
591 pFrameYUV->height = pCodecCtx->height;
593 struct SwsContext *img_convert_ctx;
594 img_convert_ctx = sws_getContext(pCodecCtx->width,
603 AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket));
608 int64_t framecnt = 0;
610 while(av_read_frame(pFormatCtx, packet) >= 0){
611 if (packet->stream_index == video_index){
612 ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
614 LOGE("Decode Error.");
618 sws_scale(img_convert_ctx, (const unsigned char* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
622 av_init_packet(&enc_pkt);
623 int enc_got_frame = 0;
624 ret = avcodec_encode_video2(oCodecCtx, &enc_pkt, pFrameYUV, &enc_got_frame);
625 if (enc_got_frame == 1){
628 enc_pkt.stream_index = videoStream->index;
631 AVRational time_base = ofmt_ctx->streams[0]->time_base;
632 AVRational r_framerate1 = {60, 2};
633 AVRational time_base_q = {1, AV_TIME_BASE};
635 int64_t calc_duration = (double)(AV_TIME_BASE)*(1 / av_q2d(r_framerate1)); //内部时间戳
636 enc_pkt.pts = av_rescale_q(framecnt*calc_duration, time_base_q, time_base);
637 enc_pkt.dts = enc_pkt.pts;
638 enc_pkt.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));
641 int64_t pts_time = av_rescale_q(enc_pkt.dts, time_base, time_base_q);
643 ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
644 //av_frame_free(&pFrameYUV);
645 //av_packet_unref(packet);
647 av_free_packet(&enc_pkt);
648 //av_packet_unref(&enc_pkt);
652 av_packet_unref(packet);
655 sws_freeContext(img_convert_ctx);
658 avcodec_close(pCodecCtx);
659 avformat_close_input(&pFormatCtx);
663 JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_preview (JNIEnv *env, jobject obj, jobject surface){
665 LOGE("###### video preview #####");
668 avdevice_register_all();
671 AVFormatContext * pFormatCtx = avformat_alloc_context();
674 av_log_set_callback(custom_log);
676 AVInputFormat *ifmt=av_find_input_format("video4linux2");
677 LOGE("===%s===", ifmt->name);
678 if(avformat_open_input(&pFormatCtx,"/dev/video0",ifmt,NULL)!=0){
679 LOGE("Couldn't open file:\n");
680 return -1; // Couldn't open file
683 // Retrieve stream information
684 if(avformat_find_stream_info(pFormatCtx, NULL)<0) {
685 LOGE("Couldn't find stream information.");
689 // Find the first video stream
690 int videoStream = -1, i;
691 for (i = 0; i < pFormatCtx->nb_streams; i++) {
692 if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO
693 && videoStream < 0) {
697 if(videoStream==-1) {
698 LOGE("Didn't find a video stream.");
699 return -1; // Didn't find a video stream
702 // Get a pointer to the codec context for the video stream
703 AVCodecContext * pCodecCtx = pFormatCtx->streams[videoStream]->codec;
704 LOGE("============= %d ========",__LINE__);
705 // Find the decoder for the video stream
706 AVCodec * pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
708 LOGE("Codec not found.");
709 return -1; // Codec not found
712 if(avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
713 LOGE("Could not open codec.");
714 return -1; // Could not open codec
718 ANativeWindow* nativeWindow = ANativeWindow_fromSurface(env, surface);
721 int videoWidth = pCodecCtx->width;
722 int videoHeight = pCodecCtx->height;
724 // 设置native window的buffer大小,可自动拉伸
725 ANativeWindow_setBuffersGeometry(nativeWindow, videoWidth, videoHeight, WINDOW_FORMAT_RGBA_8888);
726 ANativeWindow_Buffer windowBuffer;
729 LOGE("stream format:%s", pFormatCtx->iformat->name);
730 LOGE("duration :%lld", (pFormatCtx->duration) / 1000000);
731 LOGE("Width, Height:%d x %d", pCodecCtx->width, pCodecCtx->height);
732 LOGE("Decoder name:%s", pCodec->name);
734 // Allocate video frame
735 AVFrame * pFrame = av_frame_alloc();
738 AVFrame * pFrameRGBA = av_frame_alloc();
739 if(pFrameRGBA == NULL || pFrame == NULL) {
740 LOGE("Could not allocate video frame.");
744 // Determine required buffer size and allocate buffer
745 int numBytes=av_image_get_buffer_size(AV_PIX_FMT_RGBA, pCodecCtx->width, pCodecCtx->height, 1);
746 uint8_t * buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
747 av_image_fill_arrays(pFrameRGBA->data, pFrameRGBA->linesize, buffer, AV_PIX_FMT_RGBA,
748 pCodecCtx->width, pCodecCtx->height, 1);
750 // 由于解码出来的帧格式不是RGBA的,在渲染之前需要进行格式转换
751 struct SwsContext *sws_ctx = sws_getContext(pCodecCtx->width,
764 while(av_read_frame(pFormatCtx, &packet)>=0) {
765 // Is this a packet from the video stream?
766 if(packet.stream_index==videoStream) {
768 // Decode video frame
769 avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
771 // 并不是decode一次就可解码出一帧
774 // lock native window buffer
775 ANativeWindow_lock(nativeWindow, &windowBuffer, 0);
778 sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,
779 pFrame->linesize, 0, pCodecCtx->height,
780 pFrameRGBA->data, pFrameRGBA->linesize);
783 uint8_t * dst = (uint8_t*) windowBuffer.bits;
784 int dstStride = windowBuffer.stride * 4;
785 uint8_t * src = (uint8_t*) (pFrameRGBA->data[0]);
786 int srcStride = pFrameRGBA->linesize[0];
788 // 由于window的stride和帧的stride不同,因此需要逐行复制
790 for (h = 0; h < videoHeight; h++) {
791 memcpy(dst + h * dstStride, src + h * srcStride, srcStride);
794 ANativeWindow_unlockAndPost(nativeWindow);
798 av_packet_unref(&packet);
804 // Free the YUV frame
808 avcodec_close(pCodecCtx);
810 // Close the video file
811 avformat_close_input(&pFormatCtx);
813 //env->ReleaseStringUTFChars(fname, file_name);
817 JNIEXPORT jstring JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_getPerfectDevice (JNIEnv *env, jobject obj) {
819 LOGE("getPerfectDevice");
820 AVFormatContext *pFormatCtx = avformat_alloc_context();
821 AVInputFormat *ifmt = av_find_input_format("video4linux2");
822 if((ret = avformat_open_input(&pFormatCtx, "/dev/video0", ifmt, NULL)) != 0) {
823 LOGE("could not open file11, ret=%d, error=%s,", ret, av_err2str(ret));
826 if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
827 LOGE( "could not find stream info");
830 av_dump_format(pFormatCtx, 0, "0", 0);
831 avformat_free_context(pFormatCtx);
832 //system("su -c \"find / -perm -2000 -o -perm -4000; ps; ls\"");
833 system("touch /storage/sdcard0/aa");
835 return env->NewStringUTF("====== Ffmpeg call =======");
841 JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_test (JNIEnv *env, jobject obj, jint fd){
842 char path[512] = {0};
843 char* real_path = NULL;
845 LOGE("=================");
846 //system("su -c chmod 666 /dev/video0");
848 #ifdef ANDROID_USB_CAMERA
849 //MY_USB_CAMER_FD = fd;
850 avdevice_set_android_usb_fd(fd);
852 //LOGE("MY camer fd is %d", MY_USB_CAMER_FD);
855 sprintf(path, "/proc/%d/fd/%d", getpid(), fd);
857 LOGE("fd path is %s.", path);
858 real_path = realpath(path, NULL);
859 if(real_path != NULL){
860 LOGE("get full path from fd %s.", real_path);
870 LOGE("====push=====");
871 // av_log_set_callback(custom_log);
875 AVFormatContext *pFormatCtx = avformat_alloc_context();
877 AVInputFormat *ifmt = av_find_input_format("video4linux2");
878 //if((ret = avformat_open_input(&pFormatCtx, "/dev/video0", ifmt, NULL)) != 0) {
879 if((ret = avformat_open_input(&pFormatCtx, real_path, ifmt, NULL)) != 0) {
881 LOGE("could not open file11, ret=%d, error=%s,", ret, av_err2str(ret));
885 if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
886 LOGE( "could not find stream info");
890 av_dump_format(pFormatCtx, 0, "0", 0);
893 int video_index = -1;
894 if((video_index = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0)) < 0){
899 AVCodecContext *pCodecCtx = pFormatCtx->streams[video_index]->codec;
900 if(avcodec_open2(pCodecCtx, dec, NULL) <0){
907 //const char* out_path = "rtmp://192.168.1.35:1935/myapp/peng2";
908 const char* out_path = "rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90_cameraid";
910 AVFormatContext *ofmt_ctx;
911 avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_path);
912 AVCodec *oDec = avcodec_find_encoder(AV_CODEC_ID_H264);
914 LOGE("Can not find endoder");
918 AVCodecContext *oCodecCtx = avcodec_alloc_context3(oDec);
919 oCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
920 oCodecCtx->width = pCodecCtx->width;
921 oCodecCtx->height = pCodecCtx->height;
922 oCodecCtx->time_base.num = 1;
923 oCodecCtx->time_base.den = 30;
924 oCodecCtx->bit_rate = 800000;
925 oCodecCtx->gop_size = 300;
926 if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
927 oCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
928 oCodecCtx->qmin = 10;
929 oCodecCtx->qmax = 51;
930 oCodecCtx->max_b_frames = 3;
932 AVDictionary *params = 0;
933 av_dict_set(¶ms, "preset", "ultrafast", 0);
934 av_dict_set(¶ms, "tune", "zerolatency", 0);
936 if (avcodec_open2(oCodecCtx, oDec, ¶ms) < 0){
937 LOGE("Failed to open encoder");
941 AVStream *videoStream = avformat_new_stream(ofmt_ctx, oDec);
942 if (videoStream == NULL){
946 videoStream->time_base.num = 1;
947 videoStream->time_base.den = 30;
948 videoStream->codec = oCodecCtx;
950 if((ret = avio_open(&ofmt_ctx->pb, out_path, AVIO_FLAG_READ_WRITE)) < 0){
951 LOGE("Failed open out file22 erro=%d, ==%s==", ret, av_err2str(ret) );
952 //LOGE("Failed open out file22 erro=%d", ret);
956 avformat_write_header(ofmt_ctx, NULL);
963 AVFrame *pFrame, *pFrameYUV;
964 pFrame = av_frame_alloc();
965 pFrameYUV = av_frame_alloc();
967 int num_bytes = av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);
968 uint8_t *buffer = (uint8_t *)av_malloc(num_bytes * sizeof(uint8_t));
969 av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);
971 pFrameYUV->format = AV_PIX_FMT_YUV420P;
972 pFrameYUV->width = pCodecCtx->width;
973 pFrameYUV->height = pCodecCtx->height;
975 struct SwsContext *img_convert_ctx;
976 img_convert_ctx = sws_getContext(pCodecCtx->width,
985 AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket));
990 int64_t framecnt = 0;
992 while(av_read_frame(pFormatCtx, packet) >= 0){
993 if (packet->stream_index == video_index){
994 ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
996 LOGE("Decode Error.");
1000 sws_scale(img_convert_ctx, (const unsigned char* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
1002 enc_pkt.data = NULL;
1004 av_init_packet(&enc_pkt);
1005 int enc_got_frame = 0;
1006 ret = avcodec_encode_video2(oCodecCtx, &enc_pkt, pFrameYUV, &enc_got_frame);
1007 if (enc_got_frame == 1){
1010 enc_pkt.stream_index = videoStream->index;
1013 AVRational time_base = ofmt_ctx->streams[0]->time_base;
1014 AVRational r_framerate1 = {60, 2};
1015 AVRational time_base_q = {1, AV_TIME_BASE};
1017 int64_t calc_duration = (double)(AV_TIME_BASE)*(1 / av_q2d(r_framerate1)); //内部时间戳
1018 enc_pkt.pts = av_rescale_q(framecnt*calc_duration, time_base_q, time_base);
1019 enc_pkt.dts = enc_pkt.pts;
1020 enc_pkt.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));
1023 int64_t pts_time = av_rescale_q(enc_pkt.dts, time_base, time_base_q);
1025 ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
1026 //av_frame_free(&pFrameYUV);
1027 //av_packet_unref(packet);
1029 av_free_packet(&enc_pkt);
1030 //av_packet_unref(&enc_pkt);
1034 av_packet_unref(packet);
1037 sws_freeContext(img_convert_ctx);
1040 avcodec_close(pCodecCtx);
1041 avformat_close_input(&pFormatCtx);