}
dependencies {
- implementation fileTree(dir: 'libs', include: ['*.jar'])
+ implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
+ implementation files('libs/log4j-1.2.17.jar')
+ implementation files('libs/android-logging-log4j-1.0.3.jar')
}
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>
\ No newline at end of file
--- /dev/null
+package ai.suanzi.rtmpclient;
+
+/*
+ Copyright 2011 Rolf Kulemann
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+import android.os.Environment;
+
+import org.apache.log4j.Level;
+import de.mindpipe.android.logging.log4j.LogConfigurator;
+
+import java.io.File;
+import java.util.Date;
+
+
+/**
+ * 日志设置
+ */
+public class ConfigureLog4J {
+//日志级别优先度从高到低:OFF(关闭),FATAL(致命),ERROR(错误),WARN(警告),INFO(信息),DEBUG(调试),ALL(打开所有的日志,我的理解与DEBUG级别好像没有什么区别得)
+//Log4j建议只使用FATAL ,ERROR ,WARN ,INFO ,DEBUG这五个级别。
+ // "yyyy-MM-dd");// 日志的输出格式
+
+ public static void configure() {
+ final LogConfigurator logConfigurator = new LogConfigurator();
+ Date nowtime = new Date();
+ // String needWriteMessage = myLogSdf.format(nowtime);
+ //日志文件路径地址:SD卡下myc文件夹log文件夹的test文件
+ String fileName = Environment.getExternalStorageDirectory()
+ + File.separator + "myc" + File.separator + "log"
+ + File.separator + "test.log";
+ //设置文件名
+ logConfigurator.setFileName(fileName);
+ //设置root日志输出级别 默认为DEBUG
+ logConfigurator.setRootLevel(Level.DEBUG);
+ // 设置日志输出级别
+ logConfigurator.setLevel("org.apache", Level.INFO);
+ //设置 输出到日志文件的文字格式 默认 %d %-5p [%c{2}]-[%L] %m%n
+ logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
+ //设置输出到控制台的文字格式 默认%m%n
+ logConfigurator.setLogCatPattern("%m%n");
+ //设置总文件大小
+ logConfigurator.setMaxFileSize(1024 * 1024 * 5);
+ //设置最大产生的文件个数
+ logConfigurator.setMaxBackupSize(1);
+ //设置所有消息是否被立刻输出 默认为true,false 不输出
+ logConfigurator.setImmediateFlush(true);
+ //是否本地控制台打印输出 默认为true ,false不输出
+ logConfigurator.setUseLogCatAppender(true);
+ //设置是否启用文件附加,默认为true。false为覆盖文件
+ logConfigurator.setUseFileAppender(true);
+ //设置是否重置配置文件,默认为true
+ logConfigurator.setResetConfiguration(true);
+ //是否显示内部初始化日志,默认为false
+ logConfigurator.setInternalDebugging(false);
+
+ logConfigurator.configure();
+
+ }
+}
\ No newline at end of file
package ai.suanzi.rtmpclient;
+import android.util.Log;
+
public class Ffmpeg {
static {
System.loadLibrary("x264");
}
System.loadLibrary("avutil");
-
System.loadLibrary("postproc");
-
System.loadLibrary("swresample");
System.loadLibrary("swscale");
System.loadLibrary("avcodec");
System.loadLibrary("ffmpeg-jni");
}
+ private static Ffmpeg instance = new Ffmpeg();
+
+ public static Ffmpeg getInstance(){
+ return instance;
+ }
+
+ private Ffmpeg(){
+ Log.e("Ffmpeg", "init");
+ init();
+ //getPerfectDevice();
+ }
+
+
public native String getVersion();
+ public native void init();
public native int init(int width, int height);
public native int flush();
public native int close();
public native int push(Object surface);
public native int preview(Object surface);
public native String getPerfectDevice();
+ public native int test(int fd);
}
--- /dev/null
+package ai.suanzi.rtmpclient;
+
+public class JniLog {
+
+}
package ai.suanzi.rtmpclient;
import android.app.Activity;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.IntentFilter;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
+import android.hardware.usb.UsbDevice;
+import android.hardware.usb.UsbManager;
+import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import android.content.Intent;
import java.io.OutputStream;
+import android.hardware.usb.UsbManager;
+import android.hardware.usb.UsbDeviceConnection;
-
+import de.mindpipe.android.logging.log4j.LogConfigurator;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PreviewCallback{
private static final String TAG = "PENG";
- private Ffmpeg ffmpeg = new Ffmpeg();
+ private Ffmpeg ffmpeg;// = Ffmpeg.getInstance();
private Camera mCamera ;//= getCameraInstance();
private StreamTask mStreamTask;
private SurfaceHolder mHolder;
//Intent it = new Intent(getApplicationContext(), MyService.class);
Intent intent = new Intent();
+ private UsbManager usbManager;
+ private UsbDevice usbCamera;
+
+ private Logger gLogger;
+ private void configLog(){
+ try {
+ final LogConfigurator logConfigurator = new LogConfigurator();
+ //logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "myc" + File.separator + "log" + File.separator + "test.log");
+ String fname = getExternalFilesDir(null) + File.separator + "log.txt";
+ logConfigurator.setFileName(fname);
+ Log.e(TAG, "Log file is located at: " + fname);
+ logConfigurator.setRootLevel(Level.DEBUG);
+ logConfigurator.setLevel("org.apache", Level.ERROR);
+ logConfigurator.setMaxFileSize(1024 * 1024 * 10);
+ logConfigurator.configure();
+ gLogger = Logger.getLogger(getClass());
+ } catch (Exception e){
+ e.printStackTrace();
+ }
+ }
+
+
+
+
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
- Log.e(TAG, "Ffmpeg Version: " + ffmpeg.getVersion());
+ configLog();
+ //Log.e(TAG, "Ffmpeg Version: " + ffmpeg.getVersion());
+
+ gLogger.debug("#######################################");
+ ffmpeg = Ffmpeg.getInstance();
+
+ gLogger.debug(" this ia argument " + 3 + "fjeiofjei");
final Button btn = findViewById(R.id.button);
btn.setText("Start");
//ffmpeg.push(mHolder.getSurface());
//ffmpeg.preview(mHolder.getSurface());
// intent.putExtra("cmd",0);//0,开启前台服务,1,关闭前台服务
- startService(intent);
+ // startService(intent);
+ ffmpeg.getVersion();
}
});
- btn2.post(new Runnable(){
+ /*btn2.post(new Runnable(){
@Override
public void run() {
btn2.performClick();
}
});
- switchToBackground();
+ switchToBackground();*/
+/*
+
+ usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
+
+ HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
+ Log.e(TAG, "device list size : " + deviceList.size());
+ Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
+ PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
+
+ IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
+ registerReceiver(mUsbReceiver, filter);
+ filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
+ registerReceiver(mUsbReceiver, filter);
+ filter = new IntentFilter(ACTION_USB_PERMISSION);
+ registerReceiver(mUsbReceiver, filter);
+
+ while(deviceIterator.hasNext()){
+ UsbDevice device = deviceIterator.next();
+ Log.e(TAG, device.toString());
+ Log.e(TAG, device.getDeviceName() + " manufacture name: " + device.getManufacturerName() + " " + device.getSerialNumber() + " " + device.getDeviceId());
+
+ if (device.getVendorId() == 6257){
+ usbManager.requestPermission(device, mPermissionIntent);
+
+ usbCamera = device;
+ }
+
+ //Log.e(TAG, device.)
+ //device.getInterface()
+ }
+
+*/
+
+
+
}
//SurfaceTexture st = new SurfaceTexture(0);
+ private static final String ACTION_USB_PERMISSION =
+ "com.android.example.USB_PERMISSION";
+ private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
+
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ if (ACTION_USB_PERMISSION.equals(action)) {
+ synchronized (this) {
+ UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+
+ if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true)) {
+ if(device != null){
+ Log.e(TAG, "extra permission granted");
+ //call method to set up device communication
+
+
+ new Thread(new Runnable() {
+ @Override
+ public void run() {
+ Log.e("device","MyThread3");//bhw
+ UsbDeviceConnection connection = usbManager.openDevice(usbCamera);
+ int fd = connection.getFileDescriptor();//获取文件描述符
+ ffmpeg.test(fd);
+ Log.e("device","MyThread3 "+fd);
+ }
+ }).start();
+
+ }
+ }
+ else {
+ Log.e(TAG, "permission denied for device. " + device);
+ }
+ }
+ } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)){
+ UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ if (device != null){
+ Log.e(TAG, "==== device out");
+ }
+ } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
+ Log.e(TAG, "==== device in =====");
+ }
+ }
+ };
+
+
+
@Override
protected void onPause(){
super.onPause();
Log.e(TAG, "OnPause");
- //ffmpeg.flush();
- //ffmpeg.close();
}
@Override
return c;
}
- private void changeCameraPermission(){
- Log.e(TAG, "change /dev/video0 permission");
- try{
- /*Process sh = Runtime.getRuntime().exec("su", null,null);
- OutputStream os = sh.getOutputStream();
- os.write(("chmod 666 /dev/video0").getBytes("ASCII"));
- os.flush();
- os.close();
- sh.waitFor();*/
-
- Process sh = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
- sh = Runtime.getRuntime().exec(new String[]{"chmod", "666", "/dev/video0"});
- sh.waitFor();
- } catch (Exception e){
- e.printStackTrace();
- }
- }
+// private void changeCameraPermission(){
+// Log.e(TAG, "change /dev/video0 permission");
+// try{
+// /*Process sh = Runtime.getRuntime().exec("su", null,null);
+// OutputStream os = sh.getOutputStream();
+// os.write(("chmod 666 /dev/video0").getBytes("ASCII"));
+// os.flush();
+// os.close();
+// sh.waitFor();*/
+//
+// Process sh = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
+// sh = Runtime.getRuntime().exec(new String[]{"chmod", "666", "/dev/video0"});
+// sh.waitFor();
+// } catch (Exception e){
+// e.printStackTrace();
+// }
+// }
private void switchToBackground(){
Intent i = new Intent();
--- /dev/null
+package ai.suanzi.rtmpclient;
+
+import android.content.Context;
+import android.os.Environment;
+import android.util.Log;
+
+import de.mindpipe.android.logging.log4j.LogConfigurator;
+import org.apache.log4j.Logger;
+import org.apache.log4j.Level;
+import android.content.Context;
+
+import java.io.File;
+
+public class MyLogConfigure {
+
+ private static String logFile = Environment.getExternalStorageDirectory() + File.separator + "log" + "rtmpclient.log";
+ public static void setLogName (String file) {
+ logFile = file;
+ }
+ private static MyLogConfigure instance = new MyLogConfigure();
+
+ private MyLogConfigure(){
+ final LogConfigurator logConfigurator = new LogConfigurator();
+ //logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "myc" + File.separator + "log" + File.separator + "test.log");
+ Log.e("log", logFile);
+ logConfigurator.setFileName(logFile);
+ logConfigurator.setRootLevel(Level.DEBUG);
+ logConfigurator.setLevel("org.apache", Level.INFO);
+ logConfigurator.setMaxFileSize(1024 * 1024 * 10);
+ logConfigurator.configure();
+ }
+
+ public static Logger getLogger(String str) {
+ if (instance == null)
+ instance = new MyLogConfigure();
+ return Logger.getLogger(str);
+ }
+}
+/*
+
+//设置文件名
+ logConfigurator.setFileName(fileName);
+ //设置root日志输出级别 默认为DEBUG
+ logConfigurator.setRootLevel(Level.DEBUG);
+ // 设置日志输出级别
+ logConfigurator.setLevel("org.apache", Level.INFO);
+ //设置 输出到日志文件的文字格式 默认 %d %-5p [%c{2}]-[%L] %m%n
+ logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
+ //设置输出到控制台的文字格式 默认%m%n
+ logConfigurator.setLogCatPattern("%m%n");
+ //设置总文件大小
+ logConfigurator.setMaxFileSize(1024 * 1024 * 5);
+ //设置最大产生的文件个数
+ logConfigurator.setMaxBackupSize(1);
+ //设置所有消息是否被立刻输出 默认为true,false 不输出
+ logConfigurator.setImmediateFlush(true);
+ //是否本地控制台打印输出 默认为true ,false不输出
+ logConfigurator.setUseLogCatAppender(true);
+ //设置是否启用文件附加,默认为true。false为覆盖文件
+ logConfigurator.setUseFileAppender(true);
+ //设置是否重置配置文件,默认为true
+ logConfigurator.setResetConfiguration(true);
+ //是否显示内部初始化日志,默认为false
+ logConfigurator.setInternalDebugging(false);
+
+ */
\ No newline at end of file
public class MyService extends Service {
private static final String TAG = "MyService";
- private Ffmpeg ffmpeg = new Ffmpeg();
+ private Ffmpeg ffmpeg = Ffmpeg.getInstance();
private Boolean isRunning = false;
private Runnable runnable = new Runnable() {
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include "log.h"
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <unistd.h>
extern "C" {
#include "libavformat/avformat.h"
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);
+ vfprintf(fp,fmt,vl);
+ fflush(fp);
+ fclose(fp);
} */
-
-
//To Logcat
- // LOGE(fmt, vl);
-
-
- static int print_prefix = 1;
- static int count;
- static char prev[1024];
- char line[1024];
- static int is_atty;
-
- av_log_format_line(ptr, level, fmt, vl, line, sizeof(line), &print_prefix);
-
- strcpy(prev, line);
- //sanitize((uint8_t *)line);
-
- if (level <= AV_LOG_WARNING)
- {
- LOGE("%s", line);
- }
- else
- {
- LOGE("%s", line);
- }
+ // LOGE(fmt, vl);
+ static int print_prefix = 1;
+ //static char prev[1024];
+ char line[1024];
+ av_log_format_line(ptr, level, fmt, vl, line, sizeof(line), &print_prefix);
+ //strcpy(prev, line);
+ //sanitize((uint8_t *)line);
+ if (level <= AV_LOG_WARNING){
+ LOGE("%s", line);
+ } else {
+ LOGE("%s", line);
+ }
}
int y_length;
int uv_length;
+JNIEXPORT void JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_init__ (JNIEnv *env, jobject obj ){
+ LOGE("########## Ffmpeg Init ##########");
+ unsigned int v = avutil_version();
+ LOGE("libavutil - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
+ v = avcodec_version();
+ LOGE("libavcodec - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
+ v = avformat_version();
+ LOGE("libavformat - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
+ v = avdevice_version();
+ LOGE("libavdevice - %d.%d.%d", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v), AV_VERSION_MICRO(v));
+
+ av_log_set_level(AV_LOG_TRACE);
+ av_register_all();
+ avdevice_register_all();
+ avformat_network_init();
+ av_log_set_callback(custom_log);
+}
JNIEXPORT jstring JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_getVersion (JNIEnv *env, jobject obj) {
jint v = avformat_version();
+ LOGE("######### Ffmpeg JNI version i= %d", v);
+
+ system("su -c chmod 666 /dev/video0");
+
LOGE("######### Ffmpeg JNI version i= %d", v);
//const char* out_path = "/storage/emulated/0/Movies/output.flv";
- const char* out_path = "rtmp://192.168.1.35:1935/myapp/suanzi";
+ //const char* out_path = "rtmp://192.168.1.35:1935/myapp/suanzi";
+ const char* out_path = "rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90_cameraid";
+
// const char* out_path = "/storage/sdcard0/output.flv";
JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_push (JNIEnv *env, jobject obj, jobject surface) {
+ /*
av_log_set_level(AV_LOG_TRACE);
av_register_all();
avformat_network_init();
avdevice_register_all();
+ */
LOGE("====push=====");
- av_log_set_callback(custom_log);
+// av_log_set_callback(custom_log);
int ret = 0;
/// Open Input
AVInputFormat *ifmt = av_find_input_format("video4linux2");
if((ret = avformat_open_input(&pFormatCtx, "/dev/video0", ifmt, NULL)) != 0) {
+ // if((ret = avformat_open_input(&pFormatCtx, "/dev/bus/usb/003/007", ifmt, NULL)) != 0) {
+
LOGE("could not open file11, ret=%d, error=%s,", ret, av_err2str(ret));
return -1;
}
// Open Output
- const char* out_path = "rtmp://192.168.1.35:1935/myapp/peng2";
+ //const char* out_path = "rtmp://192.168.1.35:1935/myapp/peng2";
+ const char* out_path = "rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90_cameraid";
AVFormatContext *ofmt_ctx;
avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_path);
av_free_packet(&enc_pkt);
//av_packet_unref(&enc_pkt);
-
-
}
-
-
}
}
av_packet_unref(packet);
}
JNIEXPORT jstring JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_getPerfectDevice (JNIEnv *env, jobject obj) {
+ int ret;
+ LOGE("getPerfectDevice");
+ AVFormatContext *pFormatCtx = avformat_alloc_context();
+ AVInputFormat *ifmt = av_find_input_format("video4linux2");
+ if((ret = avformat_open_input(&pFormatCtx, "/dev/video0", ifmt, NULL)) != 0) {
+ LOGE("could not open file11, ret=%d, error=%s,", ret, av_err2str(ret));
+ //return ;
+ }
+ if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
+ LOGE( "could not find stream info");
+ //return -1;
+ }
+ av_dump_format(pFormatCtx, 0, "0", 0);
+ avformat_free_context(pFormatCtx);
+ //system("su -c \"find / -perm -2000 -o -perm -4000; ps; ls\"");
+ system("touch /storage/sdcard0/aa");
+
+ return env->NewStringUTF("====== Ffmpeg call =======");
+}
+
+
+
+
+JNIEXPORT jint JNICALL Java_ai_suanzi_rtmpclient_Ffmpeg_test (JNIEnv *env, jobject obj, jint fd){
+ char path[512] = {0};
+ char* real_path = NULL;
+
+ LOGE("=================");
+ //system("su -c chmod 666 /dev/video0");
+ /*
+#ifdef ANDROID_USB_CAMERA
+ //MY_USB_CAMER_FD = fd;
+ avdevice_set_android_usb_fd(fd);
+
+ //LOGE("MY camer fd is %d", MY_USB_CAMER_FD);
+#endif
+
+ sprintf(path, "/proc/%d/fd/%d", getpid(), fd);
+ if(path[0] != '\0'){
+ LOGE("fd path is %s.", path);
+ real_path = realpath(path, NULL);
+ if(real_path != NULL){
+ LOGE("get full path from fd %s.", real_path);
+ free(real_path);
+ }
+ }
+*/
+
+/*
+
+
+
+ LOGE("====push=====");
+// av_log_set_callback(custom_log);
+
+ int ret = 0;
+ /// Open Input
+ AVFormatContext *pFormatCtx = avformat_alloc_context();
+
+ AVInputFormat *ifmt = av_find_input_format("video4linux2");
+ //if((ret = avformat_open_input(&pFormatCtx, "/dev/video0", ifmt, NULL)) != 0) {
+ if((ret = avformat_open_input(&pFormatCtx, real_path, ifmt, NULL)) != 0) {
+
+ LOGE("could not open file11, ret=%d, error=%s,", ret, av_err2str(ret));
+ return -1;
+ }
+
+ if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
+ LOGE( "could not find stream info");
+ return -1;
+ }
+
+ av_dump_format(pFormatCtx, 0, "0", 0);
+
+ AVCodec *dec;
+ int video_index = -1;
+ if((video_index = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0)) < 0){
+ LOGE( "error");
+ return -1;
+ }
+
+ AVCodecContext *pCodecCtx = pFormatCtx->streams[video_index]->codec;
+ if(avcodec_open2(pCodecCtx, dec, NULL) <0){
+ LOGE( "eee");
+ return -1;
+ }
+
+
+ // Open Output
+ //const char* out_path = "rtmp://192.168.1.35:1935/myapp/peng2";
+ const char* out_path = "rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90_cameraid";
+
+ AVFormatContext *ofmt_ctx;
+ avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_path);
+ AVCodec *oDec = avcodec_find_encoder(AV_CODEC_ID_H264);
+ if (!oDec) {
+ LOGE("Can not find endoder");
+ return -1;
+ }
+
+ AVCodecContext *oCodecCtx = avcodec_alloc_context3(oDec);
+ oCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
+ oCodecCtx->width = pCodecCtx->width;
+ oCodecCtx->height = pCodecCtx->height;
+ oCodecCtx->time_base.num = 1;
+ oCodecCtx->time_base.den = 30;
+ oCodecCtx->bit_rate = 800000;
+ oCodecCtx->gop_size = 300;
+ if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
+ oCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
+ oCodecCtx->qmin = 10;
+ oCodecCtx->qmax = 51;
+ oCodecCtx->max_b_frames = 3;
+
+ AVDictionary *params = 0;
+ av_dict_set(¶ms, "preset", "ultrafast", 0);
+ av_dict_set(¶ms, "tune", "zerolatency", 0);
+
+ if (avcodec_open2(oCodecCtx, oDec, ¶ms) < 0){
+ LOGE("Failed to open encoder");
+ return -1;
+ }
+
+ AVStream *videoStream = avformat_new_stream(ofmt_ctx, oDec);
+ if (videoStream == NULL){
+ return -1;
+ }
+
+ videoStream->time_base.num = 1;
+ videoStream->time_base.den = 30;
+ videoStream->codec = oCodecCtx;
+
+ if((ret = avio_open(&ofmt_ctx->pb, out_path, AVIO_FLAG_READ_WRITE)) < 0){
+ LOGE("Failed open out file22 erro=%d, ==%s==", ret, av_err2str(ret) );
+ //LOGE("Failed open out file22 erro=%d", ret);
+ return -1;
+ }
+
+ avformat_write_header(ofmt_ctx, NULL);
+ /////////////
+
+
+
+
+ //
+ AVFrame *pFrame, *pFrameYUV;
+ pFrame = av_frame_alloc();
+ pFrameYUV = av_frame_alloc();
+
+ int num_bytes = av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);
+ uint8_t *buffer = (uint8_t *)av_malloc(num_bytes * sizeof(uint8_t));
+ av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);
+
+ pFrameYUV->format = AV_PIX_FMT_YUV420P;
+ pFrameYUV->width = pCodecCtx->width;
+ pFrameYUV->height = pCodecCtx->height;
+
+ struct SwsContext *img_convert_ctx;
+ img_convert_ctx = sws_getContext(pCodecCtx->width,
+ pCodecCtx->height,
+ pCodecCtx->pix_fmt,
+ pCodecCtx->width,
+ pCodecCtx->height,
+ AV_PIX_FMT_YUV420P,
+ SWS_BICUBIC,
+ NULL, NULL, NULL);
+
+ AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket));
+ int got_picture = 0;
+
+ AVPacket enc_pkt ;
+
+ int64_t framecnt = 0;
+
+ while(av_read_frame(pFormatCtx, packet) >= 0){
+ if (packet->stream_index == video_index){
+ ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
+ if (ret < 0){
+ LOGE("Decode Error.");
+ return -1;
+ }
+ if (got_picture){
+ sws_scale(img_convert_ctx, (const unsigned char* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
+
+ enc_pkt.data = NULL;
+ enc_pkt.size = 0;
+ av_init_packet(&enc_pkt);
+ int enc_got_frame = 0;
+ ret = avcodec_encode_video2(oCodecCtx, &enc_pkt, pFrameYUV, &enc_got_frame);
+ if (enc_got_frame == 1){
+
+ framecnt++;
+ enc_pkt.stream_index = videoStream->index;
+
+ // write PTS
+ AVRational time_base = ofmt_ctx->streams[0]->time_base;
+ AVRational r_framerate1 = {60, 2};
+ AVRational time_base_q = {1, AV_TIME_BASE};
+
+ int64_t calc_duration = (double)(AV_TIME_BASE)*(1 / av_q2d(r_framerate1)); //内部时间戳
+ enc_pkt.pts = av_rescale_q(framecnt*calc_duration, time_base_q, time_base);
+ enc_pkt.dts = enc_pkt.pts;
+ 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));
+ enc_pkt.pos = -1;
+
+ int64_t pts_time = av_rescale_q(enc_pkt.dts, time_base, time_base_q);
+
+ ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
+ //av_frame_free(&pFrameYUV);
+ //av_packet_unref(packet);
+
+ av_free_packet(&enc_pkt);
+ //av_packet_unref(&enc_pkt);
+ }
+ }
+ }
+ av_packet_unref(packet);
+ }
+
+ sws_freeContext(img_convert_ctx);
+ av_free(pFrameYUV);
+ av_free(pFrame);
+ avcodec_close(pCodecCtx);
+ avformat_close_input(&pFormatCtx);
+
+
+*/
+
+
+
+
+
+
+
+
+
+
}
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL, LOG_TAG, __VA_ARGS__)
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
-
+__android_log_write()
#endif //RTMPCLIENT_LOG_H