├── .gitignore
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── renhui
│ │ └── androidrecorder
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── renhui
│ │ │ └── androidrecorder
│ │ │ ├── muxer
│ │ │ ├── AudioEncoderThread.java
│ │ │ ├── FileUtils.java
│ │ │ ├── MediaMuxerActivity.java
│ │ │ ├── MediaMuxerThread.java
│ │ │ └── VideoEncoderThread.java
│ │ │ └── onlyh264
│ │ │ ├── H264Encoder.java
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ └── activity_media_muxer.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── renhui
│ └── androidrecorder
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AndroidRecorder
2 |
3 | ### 结合博客:[Android 音视频开发(七): 音视频录制流程总结](http://www.cnblogs.com/renhui/p/7520690.html) 生成Demo:
4 |
5 | #### 1.1 需求说明
6 | 我们需要做的事情就是:串联整个音视频录制流程,完成音视频的采集、编码、封包成 mp4 输出。
7 |
8 | #### 1.2 实现方式
9 | Android音视频采集的方法:预览用SurfaceView,视频采集用Camera类,音频采集用AudioRecord。
10 |
11 | #### 1.3 数据处理思路
12 | 使用MediaCodec 类进行编码压缩,视频压缩为H.264,音频压缩为aac,使用MediaMuxer 将音视频合成为MP4。
13 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 26
5 | buildToolsVersion "26.0.1"
6 | defaultConfig {
7 | applicationId "com.renhui.androidrecorder"
8 | minSdkVersion 18
9 | targetSdkVersion 26
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile 'com.android.support:appcompat-v7:26.+'
28 | compile 'com.android.support.constraint:constraint-layout:1.0.2'
29 | testCompile 'junit:junit:4.12'
30 | }
31 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/renhui/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/renhui/androidrecorder/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.renhui.androidrecorder;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.renhui.androidrecorder", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
13 |
14 |
22 |
23 |
24 |
25 |
26 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/app/src/main/java/com/renhui/androidrecorder/muxer/AudioEncoderThread.java:
--------------------------------------------------------------------------------
1 | package com.renhui.androidrecorder.muxer;
2 |
3 | import android.media.AudioFormat;
4 | import android.media.AudioRecord;
5 | import android.media.MediaCodec;
6 | import android.media.MediaCodecInfo;
7 | import android.media.MediaCodecList;
8 | import android.media.MediaFormat;
9 | import android.media.MediaRecorder;
10 | import android.util.Log;
11 |
12 | import java.io.IOException;
13 | import java.lang.ref.WeakReference;
14 | import java.nio.ByteBuffer;
15 |
16 | /**
17 | * 音频编码线程
18 | * Created by renhui on 2017/9/25.
19 | */
20 | public class AudioEncoderThread extends Thread {
21 |
22 | public static final String TAG = "AudioEncoderThread";
23 |
24 | public static final int SAMPLES_PER_FRAME = 1024;
25 | public static final int FRAMES_PER_BUFFER = 25;
26 | private static final int TIMEOUT_USEC = 10000;
27 | private static final String MIME_TYPE = "audio/mp4a-latm";
28 | private static final int SAMPLE_RATE = 16000;
29 | private static final int BIT_RATE = 64000;
30 | private static final int[] AUDIO_SOURCES = new int[]{MediaRecorder.AudioSource.DEFAULT};
31 |
32 |
33 | private final Object lock = new Object();
34 | private MediaCodec mMediaCodec; // API >= 16(Android4.1.2)
35 | private volatile boolean isExit = false;
36 | private WeakReference mediaMuxerRunnable;
37 | private AudioRecord audioRecord;
38 | private MediaCodec.BufferInfo mBufferInfo; // API >= 16(Android4.1.2)
39 | private volatile boolean isStart = false;
40 | private volatile boolean isMuxerReady = false;
41 | private long prevOutputPTSUs = 0;
42 | private MediaFormat audioFormat;
43 |
44 | public AudioEncoderThread(WeakReference mediaMuxerRunnable) {
45 | this.mediaMuxerRunnable = mediaMuxerRunnable;
46 | mBufferInfo = new MediaCodec.BufferInfo();
47 | prepare();
48 | }
49 |
50 | private static final MediaCodecInfo selectAudioCodec(final String mimeType) {
51 | MediaCodecInfo result = null;
52 | // get the list of available codecs
53 | Log.e("111", "selectAudioCodec");
54 | final int numCodecs = MediaCodecList.getCodecCount();
55 | Log.e("111", "selectAudioCodec。。。" + numCodecs);
56 | for (int i = 0; i < numCodecs; i++) {
57 | final MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
58 | if (!codecInfo.isEncoder()) { // skipp decoder
59 | continue;
60 | }
61 | final String[] types = codecInfo.getSupportedTypes();
62 | for (int j = 0; j < types.length; j++) {
63 | Log.i(TAG, "supportedType:" + codecInfo.getName() + ",MIME=" + types[j]);
64 | if (types[j].equalsIgnoreCase(mimeType)) {
65 | if (result == null) {
66 | result = codecInfo;
67 | break;
68 | }
69 | }
70 | }
71 | }
72 | return result;
73 | }
74 |
75 | private void prepare() {
76 | MediaCodecInfo audioCodecInfo = selectAudioCodec(MIME_TYPE);
77 | if (audioCodecInfo == null) {
78 | Log.e(TAG, "Unable to find an appropriate codec for " + MIME_TYPE);
79 | return;
80 | }
81 | Log.e(TAG, "selected codec: " + audioCodecInfo.getName());
82 |
83 | audioFormat = MediaFormat.createAudioFormat(MIME_TYPE, SAMPLE_RATE, 1);
84 | audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
85 | audioFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
86 | audioFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, SAMPLE_RATE);
87 | Log.e(TAG, "format: " + audioFormat);
88 | }
89 |
90 | private void startMediaCodec() throws IOException {
91 | if (mMediaCodec != null) {
92 | return;
93 | }
94 | mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
95 | mMediaCodec.configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
96 | mMediaCodec.start();
97 | Log.i(TAG, "prepare finishing");
98 |
99 | prepareAudioRecord();
100 |
101 | isStart = true;
102 | }
103 |
104 | private void stopMediaCodec() {
105 | if (audioRecord != null) {
106 | audioRecord.stop();
107 | audioRecord.release();
108 | audioRecord = null;
109 | try {
110 | Thread.sleep(100);
111 | } catch (InterruptedException e) {
112 | }
113 | }
114 | if (mMediaCodec != null) {
115 | mMediaCodec.stop();
116 | mMediaCodec.release();
117 | mMediaCodec = null;
118 | }
119 | isStart = false;
120 | Log.e("angcyo-->", "stop audio 录制...");
121 | }
122 |
123 | public synchronized void restart() {
124 | isStart = false;
125 | isMuxerReady = false;
126 | }
127 |
128 | private void prepareAudioRecord() {
129 | if (audioRecord != null) {
130 | audioRecord.stop();
131 | audioRecord.release();
132 | audioRecord = null;
133 | }
134 | android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
135 | try {
136 | final int min_buffer_size = AudioRecord.getMinBufferSize(
137 | SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
138 | AudioFormat.ENCODING_PCM_16BIT);
139 | int buffer_size = SAMPLES_PER_FRAME * FRAMES_PER_BUFFER;
140 | if (buffer_size < min_buffer_size)
141 | buffer_size = ((min_buffer_size / SAMPLES_PER_FRAME) + 1) * SAMPLES_PER_FRAME * 2;
142 |
143 | audioRecord = null;
144 | for (final int source : AUDIO_SOURCES) {
145 | try {
146 | audioRecord = new AudioRecord(source, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, buffer_size);
147 | if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED)
148 | audioRecord = null;
149 | } catch (Exception e) {
150 | audioRecord = null;
151 | }
152 | if (audioRecord != null) break;
153 | }
154 | } catch (final Exception e) {
155 | Log.e(TAG, "AudioThread#run", e);
156 | }
157 |
158 | if (audioRecord != null) {
159 | audioRecord.startRecording();
160 | }
161 | }
162 |
163 | public void exit() {
164 | isExit = true;
165 | }
166 |
167 | public void setMuxerReady(boolean muxerReady) {
168 | synchronized (lock) {
169 | Log.e("angcyo-->", Thread.currentThread().getId() + " audio -- setMuxerReady..." + muxerReady);
170 | isMuxerReady = muxerReady;
171 | lock.notifyAll();
172 | }
173 | }
174 |
175 | @Override
176 | public void run() {
177 | final ByteBuffer buf = ByteBuffer.allocateDirect(SAMPLES_PER_FRAME);
178 | int readBytes;
179 | while (!isExit) {
180 |
181 | /*启动或者重启*/
182 | if (!isStart) {
183 | stopMediaCodec();
184 |
185 | Log.e(TAG, Thread.currentThread().getId() + " audio -- run..." + isMuxerReady);
186 |
187 | if (!isMuxerReady) {
188 | synchronized (lock) {
189 | try {
190 | Log.e(TAG, "audio -- 等待混合器准备...");
191 | lock.wait();
192 | } catch (InterruptedException e) {
193 | }
194 | }
195 | }
196 |
197 | if (isMuxerReady) {
198 | try {
199 | Log.e(TAG, "audio -- startMediaCodec...");
200 | startMediaCodec();
201 | } catch (IOException e) {
202 | e.printStackTrace();
203 | isStart = false;
204 | try {
205 | Thread.sleep(100);
206 | } catch (InterruptedException e1) {
207 | }
208 | }
209 | }
210 | } else if (audioRecord != null) {
211 | buf.clear();
212 | readBytes = audioRecord.read(buf, SAMPLES_PER_FRAME);
213 | if (readBytes > 0) {
214 | // set audio data to encoder
215 | buf.position(readBytes);
216 | buf.flip();
217 | Log.e("ang-->", "解码音频数据:" + readBytes);
218 | try {
219 | encode(buf, readBytes, getPTSUs());
220 | } catch (Exception e) {
221 | Log.e(TAG, "解码音频(Audio)数据 失败");
222 | e.printStackTrace();
223 | }
224 | }
225 | }
226 |
227 | }
228 | Log.e(TAG, "Audio 录制线程 退出...");
229 | }
230 |
231 | private void encode(final ByteBuffer buffer, final int length, final long presentationTimeUs) {
232 | if (isExit) return;
233 | final ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
234 | final int inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_USEC);
235 | /*向编码器输入数据*/
236 | if (inputBufferIndex >= 0) {
237 | final ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
238 | inputBuffer.clear();
239 | if (buffer != null) {
240 | inputBuffer.put(buffer);
241 | }
242 | if (length <= 0) {
243 | Log.i(TAG, "send BUFFER_FLAG_END_OF_STREAM");
244 | mMediaCodec.queueInputBuffer(inputBufferIndex, 0, 0, presentationTimeUs, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
245 | } else {
246 | mMediaCodec.queueInputBuffer(inputBufferIndex, 0, length, presentationTimeUs, 0);
247 | }
248 | } else if (inputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
249 | // wait for MediaCodec encoder is ready to encode
250 | // nothing to do here because MediaCodec#dequeueInputBuffer(TIMEOUT_USEC)
251 | // will wait for maximum TIMEOUT_USEC(10msec) on each call
252 | }
253 |
254 | /*获取解码后的数据*/
255 | final MediaMuxerThread muxer = mediaMuxerRunnable.get();
256 | if (muxer == null) {
257 | Log.w(TAG, "MediaMuxerRunnable is unexpectedly null");
258 | return;
259 | }
260 | ByteBuffer[] encoderOutputBuffers = mMediaCodec.getOutputBuffers();
261 | int encoderStatus;
262 |
263 | do {
264 | encoderStatus = mMediaCodec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
265 | if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
266 | } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
267 | encoderOutputBuffers = mMediaCodec.getOutputBuffers();
268 | } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
269 |
270 | final MediaFormat format = mMediaCodec.getOutputFormat(); // API >= 16
271 | MediaMuxerThread mediaMuxerRunnable = this.mediaMuxerRunnable.get();
272 | if (mediaMuxerRunnable != null) {
273 | Log.e(TAG, "添加音轨 INFO_OUTPUT_FORMAT_CHANGED " + format.toString());
274 | mediaMuxerRunnable.addTrackIndex(MediaMuxerThread.TRACK_AUDIO, format);
275 | }
276 |
277 | } else if (encoderStatus < 0) {
278 | Log.e(TAG, "encoderStatus < 0");
279 | } else {
280 | final ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
281 | if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
282 | mBufferInfo.size = 0;
283 | }
284 |
285 | if (mBufferInfo.size != 0 && muxer != null && muxer.isMuxerStart()) {
286 | mBufferInfo.presentationTimeUs = getPTSUs();
287 | Log.e(TAG, "发送音频数据 " + mBufferInfo.size);
288 | muxer.addMuxerData(new MediaMuxerThread.MuxerData(MediaMuxerThread.TRACK_AUDIO, encodedData, mBufferInfo));
289 | prevOutputPTSUs = mBufferInfo.presentationTimeUs;
290 | }
291 | mMediaCodec.releaseOutputBuffer(encoderStatus, false);
292 | }
293 | } while (encoderStatus >= 0);
294 | }
295 |
296 | /**
297 | * get next encoding presentationTimeUs
298 | *
299 | * @return
300 | */
301 | private long getPTSUs() {
302 | long result = System.nanoTime() / 1000L;
303 | // presentationTimeUs should be monotonic
304 | // otherwise muxer fail to write
305 | if (result < prevOutputPTSUs)
306 | result = (prevOutputPTSUs - result) + result;
307 | return result;
308 | }
309 | }
310 |
--------------------------------------------------------------------------------
/app/src/main/java/com/renhui/androidrecorder/muxer/FileUtils.java:
--------------------------------------------------------------------------------
1 | package com.renhui.androidrecorder.muxer;
2 |
3 | import android.os.Environment;
4 | import android.util.Log;
5 |
6 | import java.io.File;
7 | import java.text.SimpleDateFormat;
8 | import java.util.Arrays;
9 | import java.util.Collections;
10 | import java.util.List;
11 |
12 | /**
13 | * 文件处理工具类
14 | * Created by renhui on 2017/9/25.
15 | */
16 | public class FileUtils {
17 |
18 | private static final String MAIN_DIR_NAME = "/android_records";
19 | private static final String BASE_VIDEO = "/video/";
20 | private static final String BASE_EXT = ".mp4";
21 |
22 | private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
23 | private String currentFileName = "-";
24 | private String nextFileName;
25 |
26 | public FileUtils() {
27 | }
28 |
29 | public boolean requestSwapFile() {
30 | return requestSwapFile(false);
31 | }
32 |
33 | public boolean requestSwapFile(boolean force) {
34 | //SD 卡可读写
35 | String fileName = getFileName();
36 | boolean isChanged = false;
37 |
38 | if (!currentFileName.equalsIgnoreCase(fileName)) {
39 | isChanged = true;
40 | }
41 |
42 | if (isChanged || force) {
43 | nextFileName = getSaveFilePath(fileName);
44 | return true;
45 | }
46 |
47 | return false;
48 | }
49 |
50 | public String getNextFileName() {
51 | return nextFileName;
52 | }
53 |
54 | private String getFileName() {
55 | String format = simpleDateFormat.format(System.currentTimeMillis());
56 | return format;
57 | }
58 |
59 | private String getSaveFilePath(String fileName) {
60 | currentFileName = fileName;
61 | StringBuilder fullPath = new StringBuilder();
62 | fullPath.append(getExternalStorageDirectory());
63 | //检查内置卡剩余空间容量,并清理
64 | checkSpace();
65 | fullPath.append(MAIN_DIR_NAME);
66 | fullPath.append(BASE_VIDEO);
67 | fullPath.append(fileName);
68 | fullPath.append(BASE_EXT);
69 |
70 | String string = fullPath.toString();
71 | File file = new File(string);
72 | File parentFile = file.getParentFile();
73 | if (!parentFile.exists()) {
74 | parentFile.mkdirs();
75 | }
76 |
77 | return string;
78 | }
79 |
80 | /**
81 | * 检查剩余空间
82 | */
83 | private void checkSpace() {
84 | StringBuilder fullPath = new StringBuilder();
85 | String checkPath = getExternalStorageDirectory();
86 | fullPath.append(checkPath);
87 | fullPath.append(MAIN_DIR_NAME);
88 | fullPath.append(BASE_VIDEO);
89 |
90 | if (checkCardSpace(checkPath)) {
91 | File file = new File(fullPath.toString());
92 |
93 | if (!file.exists()) {
94 | file.mkdirs();
95 | }
96 |
97 | String[] fileNames = file.list();
98 | if (fileNames.length < 1) {
99 | return;
100 | }
101 |
102 | List fileNameLists = Arrays.asList(fileNames);
103 | Collections.sort(fileNameLists);
104 |
105 | for (int i = 0; i < fileNameLists.size() && checkCardSpace(checkPath); i++) {
106 | //清理视频
107 | String removeFileName = fileNameLists.get(i);
108 | File removeFile = new File(file, removeFileName);
109 | try {
110 | removeFile.delete();
111 | Log.e("angcyo-->", "删除文件 " + removeFile.getAbsolutePath());
112 | } catch (Exception e) {
113 | e.printStackTrace();
114 | Log.e("angcyo-->", "删除文件失败 " + removeFile.getAbsolutePath());
115 | }
116 | }
117 | }
118 | }
119 |
120 | private boolean checkCardSpace(String filePath) {
121 | File dir = new File(filePath);
122 | double totalSpace = dir.getTotalSpace();//总大小
123 | double freeSpace = dir.getFreeSpace();//剩余大小
124 | if (freeSpace < totalSpace * 0.2) {
125 | return true;
126 | }
127 | return false;
128 | }
129 |
130 | /**
131 | * 获取sdcard路径
132 | */
133 | public static String getExternalStorageDirectory() {
134 | return Environment.getExternalStorageDirectory().getPath();
135 | }
136 |
137 | }
138 |
--------------------------------------------------------------------------------
/app/src/main/java/com/renhui/androidrecorder/muxer/MediaMuxerActivity.java:
--------------------------------------------------------------------------------
1 | package com.renhui.androidrecorder.muxer;
2 |
3 | import android.Manifest;
4 | import android.content.pm.PackageManager;
5 | import android.graphics.ImageFormat;
6 | import android.hardware.Camera;
7 | import android.os.Bundle;
8 | import android.support.v4.app.ActivityCompat;
9 | import android.support.v4.content.ContextCompat;
10 | import android.support.v7.app.AppCompatActivity;
11 | import android.util.Log;
12 | import android.view.SurfaceHolder;
13 | import android.view.SurfaceView;
14 | import android.view.View;
15 | import android.widget.Button;
16 | import android.widget.TextView;
17 | import android.widget.Toast;
18 |
19 | import com.renhui.androidrecorder.R;
20 |
21 | import java.io.IOException;
22 |
23 | /**
24 | * 音视频混合界面
25 | */
26 | public class MediaMuxerActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PreviewCallback {
27 |
28 | SurfaceView surfaceView;
29 | Button startStopButton;
30 |
31 | Camera camera;
32 | SurfaceHolder surfaceHolder;
33 |
34 | @Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 | super.onCreate(savedInstanceState);
37 |
38 | setContentView(R.layout.activity_media_muxer);
39 |
40 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
41 | ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED ||
42 | ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
43 | ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
44 | Toast.makeText(this, "申请权限", Toast.LENGTH_SHORT).show();
45 | // 申请 相机 麦克风权限
46 | ActivityCompat.requestPermissions(this, new String[]{
47 | Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO,
48 | Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
49 | }
50 |
51 | surfaceView = (SurfaceView) findViewById(R.id.surface_view);
52 | startStopButton = (Button) findViewById(R.id.startStop);
53 |
54 | startStopButton.setOnClickListener(new View.OnClickListener() {
55 | @Override
56 | public void onClick(View view) {
57 | if (view.getTag().toString().equalsIgnoreCase("stop")) {
58 | view.setTag("start");
59 | ((TextView) view).setText("开始");
60 | MediaMuxerThread.stopMuxer();
61 | stopCamera();
62 | finish();
63 | } else {
64 | startCamera();
65 | view.setTag("stop");
66 | ((TextView) view).setText("停止");
67 | MediaMuxerThread.startMuxer();
68 | }
69 | }
70 | });
71 |
72 | surfaceHolder = surfaceView.getHolder();
73 | surfaceHolder.addCallback(this);
74 |
75 | }
76 |
77 | @Override
78 | public void surfaceCreated(SurfaceHolder surfaceHolder) {
79 | Log.w("MainActivity", "enter surfaceCreated method");
80 | this.surfaceHolder = surfaceHolder;
81 | }
82 |
83 | @Override
84 | public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
85 | Log.w("MainActivity", "enter surfaceChanged method");
86 | }
87 |
88 | @Override
89 | public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
90 | Log.w("MainActivity", "enter surfaceDestroyed method");
91 | MediaMuxerThread.stopMuxer();
92 | stopCamera();
93 |
94 | }
95 |
96 | @Override
97 | public void onPreviewFrame(byte[] bytes, Camera camera) {
98 | MediaMuxerThread.addVideoFrameData(bytes);
99 | }
100 |
101 | //----------------------- 摄像头操作相关 --------------------------------------
102 |
103 | /**
104 | * 打开摄像头
105 | */
106 | private void startCamera() {
107 | camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
108 | camera.setDisplayOrientation(90);
109 | Camera.Parameters parameters = camera.getParameters();
110 | parameters.setPreviewFormat(ImageFormat.NV21);
111 |
112 | // 这个宽高的设置必须和后面编解码的设置一样,否则不能正常处理
113 | parameters.setPreviewSize(1920, 1080);
114 |
115 | try {
116 | camera.setParameters(parameters);
117 | camera.setPreviewDisplay(surfaceHolder);
118 | camera.setPreviewCallback(MediaMuxerActivity.this);
119 | camera.startPreview();
120 | } catch (IOException e) {
121 | e.printStackTrace();
122 | }
123 | }
124 |
125 | /**
126 | * 关闭摄像头
127 | */
128 | private void stopCamera() {
129 | // 停止预览并释放资源
130 | if (camera != null) {
131 | camera.setPreviewCallback(null);
132 | camera.stopPreview();
133 | camera = null;
134 | }
135 | }
136 |
137 |
138 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/renhui/androidrecorder/muxer/MediaMuxerThread.java:
--------------------------------------------------------------------------------
1 | package com.renhui.androidrecorder.muxer;
2 |
3 |
4 | import android.media.MediaCodec;
5 | import android.media.MediaFormat;
6 | import android.media.MediaMuxer;
7 | import android.util.Log;
8 |
9 | import java.io.IOException;
10 | import java.lang.ref.WeakReference;
11 | import java.nio.ByteBuffer;
12 | import java.util.Vector;
13 |
14 | /**
15 | * 音视频混合线程
16 | */
17 | public class MediaMuxerThread extends Thread {
18 |
19 | private static final String TAG = "MediaMuxerThread";
20 |
21 | public static final int TRACK_VIDEO = 0;
22 | public static final int TRACK_AUDIO = 1;
23 |
24 | private final Object lock = new Object();
25 |
26 | private static MediaMuxerThread mediaMuxerThread;
27 |
28 | private AudioEncoderThread audioThread;
29 | private VideoEncoderThread videoThread;
30 |
31 | private MediaMuxer mediaMuxer;
32 | private Vector muxerDatas;
33 |
34 | private int videoTrackIndex = -1;
35 | private int audioTrackIndex = -1;
36 |
37 | private FileUtils fileSwapHelper;
38 |
39 | // 音轨添加状态
40 | private volatile boolean isVideoTrackAdd;
41 | private volatile boolean isAudioTrackAdd;
42 |
43 | private volatile boolean isExit = false;
44 |
45 | private MediaMuxerThread() {
46 | // 构造函数
47 | }
48 |
49 | // 开始音视频混合任务
50 | public static void startMuxer() {
51 | if (mediaMuxerThread == null) {
52 | synchronized (MediaMuxerThread.class) {
53 | if (mediaMuxerThread == null) {
54 | mediaMuxerThread = new MediaMuxerThread();
55 | Log.e("111", "mediaMuxerThread.start();");
56 | mediaMuxerThread.start();
57 | }
58 | }
59 | }
60 | }
61 |
62 | // 停止音视频混合任务
63 | public static void stopMuxer() {
64 | if (mediaMuxerThread != null) {
65 | mediaMuxerThread.exit();
66 | try {
67 | mediaMuxerThread.join();
68 | } catch (InterruptedException e) {
69 | e.printStackTrace();
70 | }
71 | mediaMuxerThread = null;
72 | }
73 | }
74 |
75 | private void readyStart() throws IOException {
76 | fileSwapHelper.requestSwapFile(true);
77 | readyStart(fileSwapHelper.getNextFileName());
78 | }
79 |
80 | private void readyStart(String filePath) throws IOException {
81 | isExit = false;
82 | isVideoTrackAdd = false;
83 | isAudioTrackAdd = false;
84 | muxerDatas.clear();
85 |
86 | mediaMuxer = new MediaMuxer(filePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
87 | if (audioThread != null) {
88 | audioThread.setMuxerReady(true);
89 | }
90 | if (videoThread != null) {
91 | videoThread.setMuxerReady(true);
92 | }
93 | Log.e(TAG, "readyStart(String filePath, boolean restart) 保存至:" + filePath);
94 | }
95 |
96 | // 添加视频帧数据
97 | public static void addVideoFrameData(byte[] data) {
98 | if (mediaMuxerThread != null) {
99 | mediaMuxerThread.addVideoData(data);
100 | }
101 | }
102 |
103 | public void addMuxerData(MuxerData data) {
104 | if (!isMuxerStart()) {
105 | return;
106 | }
107 |
108 | muxerDatas.add(data);
109 | synchronized (lock) {
110 | lock.notify();
111 | }
112 | }
113 |
114 | /**
115 | * 添加视频/音频轨
116 | *
117 | * @param index
118 | * @param mediaFormat
119 | */
120 | public synchronized void addTrackIndex(int index, MediaFormat mediaFormat) {
121 | if (isMuxerStart()) {
122 | return;
123 | }
124 |
125 | /* 如果已经添加了,就不做处理了 */
126 | if ((index == TRACK_AUDIO && isAudioTrackAdd()) || (index == TRACK_VIDEO && isVideoTrackAdd())) {
127 | return;
128 | }
129 |
130 | if (mediaMuxer != null) {
131 | int track = 0;
132 | try {
133 | track = mediaMuxer.addTrack(mediaFormat);
134 | } catch (Exception e) {
135 | Log.e(TAG, "addTrack 异常:" + e.toString());
136 | return;
137 | }
138 |
139 | if (index == TRACK_VIDEO) {
140 | videoTrackIndex = track;
141 | isVideoTrackAdd = true;
142 | Log.e(TAG, "添加视频轨完成");
143 | } else {
144 | audioTrackIndex = track;
145 | isAudioTrackAdd = true;
146 | Log.e(TAG, "添加音轨完成");
147 | }
148 | requestStart();
149 | }
150 | }
151 |
152 | /**
153 | * 请求混合器开始启动
154 | */
155 | private void requestStart() {
156 | synchronized (lock) {
157 | if (isMuxerStart()) {
158 | mediaMuxer.start();
159 | Log.e(TAG, "requestStart启动混合器..开始等待数据输入...");
160 | lock.notify();
161 | }
162 | }
163 | }
164 |
165 | /**
166 | * 当前是否添加了音轨
167 | *
168 | * @return
169 | */
170 | public boolean isAudioTrackAdd() {
171 | return isAudioTrackAdd;
172 | }
173 |
174 | /**
175 | * 当前是否添加了视频轨
176 | *
177 | * @return
178 | */
179 | public boolean isVideoTrackAdd() {
180 | return isVideoTrackAdd;
181 | }
182 |
183 | /**
184 | * 当前音视频合成器是否运行了
185 | *
186 | * @return
187 | */
188 | public boolean isMuxerStart() {
189 | return isAudioTrackAdd && isVideoTrackAdd;
190 | }
191 |
192 |
193 | // 添加视频数据
194 | private void addVideoData(byte[] data) {
195 | if (videoThread != null) {
196 | videoThread.add(data);
197 | }
198 | }
199 |
200 | private void initMuxer() {
201 | muxerDatas = new Vector<>();
202 | fileSwapHelper = new FileUtils();
203 | audioThread = new AudioEncoderThread((new WeakReference(this)));
204 | videoThread = new VideoEncoderThread(1920, 1080, new WeakReference(this));
205 | audioThread.start();
206 | videoThread.start();
207 | try {
208 | readyStart();
209 | } catch (IOException e) {
210 | Log.e(TAG, "initMuxer 异常:" + e.toString());
211 | }
212 | }
213 |
214 | @Override
215 | public void run() {
216 | super.run();
217 | // 初始化混合器
218 | initMuxer();
219 | while (!isExit) {
220 | if (isMuxerStart()) {
221 | if (muxerDatas.isEmpty()) {
222 | synchronized (lock) {
223 | try {
224 | Log.e(TAG, "等待混合数据...");
225 | lock.wait();
226 | } catch (InterruptedException e) {
227 | e.printStackTrace();
228 | }
229 | }
230 | } else {
231 | if (fileSwapHelper.requestSwapFile()) {
232 | //需要切换文件
233 | String nextFileName = fileSwapHelper.getNextFileName();
234 | Log.e(TAG, "正在重启混合器..." + nextFileName);
235 | restart(nextFileName);
236 | } else {
237 | MuxerData data = muxerDatas.remove(0);
238 | int track;
239 | if (data.trackIndex == TRACK_VIDEO) {
240 | track = videoTrackIndex;
241 | } else {
242 | track = audioTrackIndex;
243 | }
244 | Log.e(TAG, "写入混合数据 " + data.bufferInfo.size);
245 | try {
246 | mediaMuxer.writeSampleData(track, data.byteBuf, data.bufferInfo);
247 | } catch (Exception e) {
248 | Log.e(TAG, "写入混合数据失败!" + e.toString());
249 | }
250 | }
251 | }
252 | } else {
253 | synchronized (lock) {
254 | try {
255 | Log.e(TAG, "等待音视轨添加...");
256 | lock.wait();
257 | } catch (InterruptedException e) {
258 | e.printStackTrace();
259 | Log.e(TAG, "addTrack 异常:" + e.toString());
260 | }
261 | }
262 | }
263 | }
264 | readyStop();
265 | Log.e(TAG, "混合器退出...");
266 | }
267 |
268 | private void restart() {
269 | fileSwapHelper.requestSwapFile(true);
270 | String nextFileName = fileSwapHelper.getNextFileName();
271 | restart(nextFileName);
272 | }
273 |
274 | private void restart(String filePath) {
275 | restartAudioVideo();
276 | readyStop();
277 |
278 | try {
279 | readyStart(filePath);
280 | } catch (Exception e) {
281 | Log.e(TAG, "readyStart(filePath, true) " + "重启混合器失败 尝试再次重启!" + e.toString());
282 | restart();
283 | return;
284 | }
285 | Log.e(TAG, "重启混合器完成");
286 | }
287 |
288 |
289 | private void readyStop() {
290 | if (mediaMuxer != null) {
291 | try {
292 | mediaMuxer.stop();
293 | } catch (Exception e) {
294 | Log.e(TAG, "mediaMuxer.stop() 异常:" + e.toString());
295 | }
296 | try {
297 | mediaMuxer.release();
298 | } catch (Exception e) {
299 | Log.e(TAG, "mediaMuxer.release() 异常:" + e.toString());
300 |
301 | }
302 | mediaMuxer = null;
303 | }
304 | }
305 |
306 | private void restartAudioVideo() {
307 | if (audioThread != null) {
308 | audioTrackIndex = -1;
309 | isAudioTrackAdd = false;
310 | audioThread.restart();
311 | }
312 | if (videoThread != null) {
313 | videoTrackIndex = -1;
314 | isVideoTrackAdd = false;
315 | videoThread.restart();
316 | }
317 | }
318 |
319 | private void exit() {
320 | if (videoThread != null) {
321 | videoThread.exit();
322 | try {
323 | videoThread.join();
324 | } catch (InterruptedException e) {
325 | e.printStackTrace();
326 | }
327 | }
328 | if (audioThread != null) {
329 | audioThread.exit();
330 | try {
331 | audioThread.join();
332 | } catch (InterruptedException e) {
333 | e.printStackTrace();
334 | }
335 | }
336 |
337 | isExit = true;
338 | synchronized (lock) {
339 | lock.notify();
340 | }
341 | }
342 |
343 | /**
344 | * 封装需要传输的数据类型
345 | */
346 | public static class MuxerData {
347 |
348 | int trackIndex;
349 | ByteBuffer byteBuf;
350 | MediaCodec.BufferInfo bufferInfo;
351 |
352 | public MuxerData(int trackIndex, ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo) {
353 | this.trackIndex = trackIndex;
354 | this.byteBuf = byteBuf;
355 | this.bufferInfo = bufferInfo;
356 | }
357 | }
358 |
359 |
360 | }
361 |
--------------------------------------------------------------------------------
/app/src/main/java/com/renhui/androidrecorder/muxer/VideoEncoderThread.java:
--------------------------------------------------------------------------------
1 | package com.renhui.androidrecorder.muxer;
2 |
3 | import android.media.MediaCodec;
4 | import android.media.MediaCodecInfo;
5 | import android.media.MediaCodecList;
6 | import android.media.MediaFormat;
7 | import android.util.Log;
8 |
9 | import java.io.IOException;
10 | import java.lang.ref.WeakReference;
11 | import java.nio.ByteBuffer;
12 | import java.util.Vector;
13 |
14 | /**
15 | * 视频编码线程
16 | */
17 | public class VideoEncoderThread extends Thread {
18 |
19 | public static final int IMAGE_HEIGHT = 1080;
20 | public static final int IMAGE_WIDTH = 1920;
21 |
22 | private static final String TAG = "VideoEncoderThread";
23 |
24 | // 编码相关参数
25 | private static final String MIME_TYPE = "video/avc"; // H.264 Advanced Video
26 | private static final int FRAME_RATE = 25; // 帧率
27 | private static final int IFRAME_INTERVAL = 10; // I帧间隔(GOP)
28 | private static final int TIMEOUT_USEC = 10000; // 编码超时时间
29 |
30 | // 视频宽高参数
31 | private int mWidth;
32 | private int mHeight;
33 |
34 | // 存储每一帧的数据 Vector 自增数组
35 | private Vector frameBytes;
36 | private byte[] mFrameData;
37 |
38 | private static final int COMPRESS_RATIO = 256;
39 | private static final int BIT_RATE = IMAGE_HEIGHT * IMAGE_WIDTH * 3 * 8 * FRAME_RATE / COMPRESS_RATIO; // bit rate CameraWrapper.
40 |
41 | private final Object lock = new Object();
42 |
43 | private MediaCodecInfo mCodecInfo;
44 | private MediaCodec mMediaCodec; // Android硬编解码器
45 | private MediaCodec.BufferInfo mBufferInfo; // 编解码Buffer相关信息
46 |
47 | private WeakReference mediaMuxer; // 音视频混合器
48 | private MediaFormat mediaFormat; // 音视频格式
49 |
50 | private volatile boolean isStart = false;
51 | private volatile boolean isExit = false;
52 | private volatile boolean isMuxerReady = false;
53 |
54 |
55 | public VideoEncoderThread(int mWidth, int mHeight, WeakReference mediaMuxer) {
56 | // 初始化相关对象和参数
57 | this.mWidth = mWidth;
58 | this.mHeight = mHeight;
59 | this.mediaMuxer = mediaMuxer;
60 | frameBytes = new Vector();
61 | prepare();
62 | }
63 |
64 | // 执行相关准备工作
65 | private void prepare() {
66 | Log.i(TAG, "VideoEncoderThread().prepare");
67 | mFrameData = new byte[this.mWidth * this.mHeight * 3 / 2];
68 | mBufferInfo = new MediaCodec.BufferInfo();
69 | mCodecInfo = selectCodec(MIME_TYPE);
70 | if (mCodecInfo == null) {
71 | Log.e(TAG, "Unable to find an appropriate codec for " + MIME_TYPE);
72 | return;
73 | }
74 | mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, this.mWidth, this.mHeight);
75 | mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
76 | mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
77 | mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar);
78 | mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
79 | }
80 |
81 | private static MediaCodecInfo selectCodec(String mimeType) {
82 | int numCodecs = MediaCodecList.getCodecCount();
83 | for (int i = 0; i < numCodecs; i++) {
84 | MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
85 | if (!codecInfo.isEncoder()) {
86 | continue;
87 | }
88 | String[] types = codecInfo.getSupportedTypes();
89 | for (int j = 0; j < types.length; j++) {
90 | if (types[j].equalsIgnoreCase(mimeType)) {
91 | return codecInfo;
92 | }
93 | }
94 | }
95 | return null;
96 | }
97 |
98 |
99 | /**
100 | * 开始视频编码
101 | *
102 | * @throws IOException
103 | */
104 | private void startMediaCodec() throws IOException {
105 | mMediaCodec = MediaCodec.createByCodecName(mCodecInfo.getName());
106 | mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
107 | mMediaCodec.start();
108 | isStart = true;
109 | }
110 |
111 | public void setMuxerReady(boolean muxerReady) {
112 | synchronized (lock) {
113 | Log.e(TAG, Thread.currentThread().getId() + " video -- setMuxerReady..." + muxerReady);
114 | isMuxerReady = muxerReady;
115 | lock.notifyAll();
116 | }
117 | }
118 |
119 | public void add(byte[] data) {
120 | if (frameBytes != null && isMuxerReady) {
121 | frameBytes.add(data);
122 | }
123 | }
124 |
125 | public synchronized void restart() {
126 | isStart = false;
127 | isMuxerReady = false;
128 | frameBytes.clear();
129 | }
130 |
131 | @Override
132 | public void run() {
133 | super.run();
134 |
135 | while (!isExit) {
136 | if (!isStart) {
137 | stopMediaCodec();
138 |
139 | if (!isMuxerReady) {
140 | synchronized (lock) {
141 | try {
142 | Log.e(TAG, "video -- 等待混合器准备...");
143 | lock.wait();
144 | } catch (InterruptedException e) {
145 | }
146 | }
147 | }
148 |
149 | if (isMuxerReady) {
150 | try {
151 | Log.e(TAG, "video -- startMediaCodec...");
152 | startMediaCodec();
153 | } catch (IOException e) {
154 | isStart = false;
155 | try {
156 | Thread.sleep(100);
157 | } catch (InterruptedException e1) {
158 | }
159 | }
160 | }
161 |
162 | } else if (!frameBytes.isEmpty()) {
163 | byte[] bytes = this.frameBytes.remove(0);
164 | Log.e("ang-->", "解码视频数据:" + bytes.length);
165 | try {
166 | encodeFrame(bytes);
167 | } catch (Exception e) {
168 | Log.e(TAG, "解码视频(Video)数据 失败");
169 | e.printStackTrace();
170 | }
171 | }
172 | }
173 | Log.e(TAG, "Video 录制线程 退出...");
174 | }
175 |
176 | public void exit() {
177 | isExit = true;
178 | }
179 |
180 | /**
181 | * 编码每一帧的数据
182 | *
183 | * @param input 每一帧的数据
184 | */
185 | private void encodeFrame(byte[] input) {
186 | Log.w(TAG, "VideoEncoderThread.encodeFrame()");
187 |
188 | // 将原始的N21数据转为I420
189 | NV21toI420SemiPlanar(input, mFrameData, this.mWidth, this.mHeight);
190 |
191 | ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
192 | ByteBuffer[] outputBuffers = mMediaCodec.getOutputBuffers();
193 |
194 | int inputBufferIndex = mMediaCodec.dequeueInputBuffer(TIMEOUT_USEC);
195 | if (inputBufferIndex >= 0) {
196 | ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
197 | inputBuffer.clear();
198 | inputBuffer.put(mFrameData);
199 | mMediaCodec.queueInputBuffer(inputBufferIndex, 0, mFrameData.length, System.nanoTime() / 1000, 0);
200 | } else {
201 | Log.e(TAG, "input buffer not available");
202 | }
203 |
204 | int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
205 | Log.i(TAG, "outputBufferIndex-->" + outputBufferIndex);
206 | do {
207 | if (outputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
208 | } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
209 | outputBuffers = mMediaCodec.getOutputBuffers();
210 | } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
211 | MediaFormat newFormat = mMediaCodec.getOutputFormat();
212 | MediaMuxerThread mediaMuxerRunnable = this.mediaMuxer.get();
213 | if (mediaMuxerRunnable != null) {
214 | mediaMuxerRunnable.addTrackIndex(MediaMuxerThread.TRACK_VIDEO, newFormat);
215 | }
216 | } else if (outputBufferIndex < 0) {
217 | Log.e(TAG, "outputBufferIndex < 0");
218 | } else {
219 | Log.d(TAG, "perform encoding");
220 | ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];
221 | if (outputBuffer == null) {
222 | throw new RuntimeException("encoderOutputBuffer " + outputBufferIndex + " was null");
223 | }
224 | if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
225 | Log.d(TAG, "ignoring BUFFER_FLAG_CODEC_CONFIG");
226 | mBufferInfo.size = 0;
227 | }
228 | if (mBufferInfo.size != 0) {
229 | MediaMuxerThread mediaMuxer = this.mediaMuxer.get();
230 |
231 | if (mediaMuxer != null && !mediaMuxer.isVideoTrackAdd()) {
232 | MediaFormat newFormat = mMediaCodec.getOutputFormat();
233 | mediaMuxer.addTrackIndex(MediaMuxerThread.TRACK_VIDEO, newFormat);
234 | }
235 | // adjust the ByteBuffer values to match BufferInfo (not needed?)
236 | outputBuffer.position(mBufferInfo.offset);
237 | outputBuffer.limit(mBufferInfo.offset + mBufferInfo.size);
238 |
239 | if (mediaMuxer != null && mediaMuxer.isMuxerStart()) {
240 | mediaMuxer.addMuxerData(new MediaMuxerThread.MuxerData(MediaMuxerThread.TRACK_VIDEO, outputBuffer, mBufferInfo));
241 | }
242 |
243 | Log.d(TAG, "sent " + mBufferInfo.size + " frameBytes to muxer");
244 | }
245 | mMediaCodec.releaseOutputBuffer(outputBufferIndex, false);
246 | }
247 | outputBufferIndex = mMediaCodec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
248 | } while (outputBufferIndex >= 0);
249 | }
250 |
251 | /**
252 | * 停止视频编码
253 | */
254 | private void stopMediaCodec() {
255 | if (mMediaCodec != null) {
256 | mMediaCodec.stop();
257 | mMediaCodec.release();
258 | mMediaCodec = null;
259 | }
260 | isStart = false;
261 | Log.e(TAG, "stop video 录制...");
262 | }
263 |
264 |
265 | private static void NV21toI420SemiPlanar(byte[] nv21bytes, byte[] i420bytes, int width, int height) {
266 | System.arraycopy(nv21bytes, 0, i420bytes, 0, width * height);
267 | for (int i = width * height; i < nv21bytes.length; i += 2) {
268 | i420bytes[i] = nv21bytes[i + 1];
269 | i420bytes[i + 1] = nv21bytes[i];
270 | }
271 | }
272 |
273 | }
274 |
--------------------------------------------------------------------------------
/app/src/main/java/com/renhui/androidrecorder/onlyh264/H264Encoder.java:
--------------------------------------------------------------------------------
1 | package com.renhui.androidrecorder.onlyh264;
2 |
3 | import android.media.MediaCodec;
4 | import android.media.MediaCodecInfo;
5 | import android.media.MediaFormat;
6 | import android.os.Environment;
7 |
8 | import java.io.BufferedOutputStream;
9 | import java.io.File;
10 | import java.io.FileOutputStream;
11 | import java.io.IOException;
12 | import java.nio.ByteBuffer;
13 | import java.util.concurrent.ArrayBlockingQueue;
14 |
15 | /**
16 | * H264 编码类
17 | */
18 | public class H264Encoder {
19 |
20 | private final static int TIMEOUT_USEC = 12000;
21 |
22 | private MediaCodec mediaCodec;
23 |
24 | public boolean isRuning = false;
25 | private int width, height, framerate;
26 | public byte[] configbyte;
27 |
28 | private BufferedOutputStream outputStream;
29 |
30 | public ArrayBlockingQueue yuv420Queue = new ArrayBlockingQueue<>(10);
31 |
32 | /***
33 | * 构造函数
34 | * @param width
35 | * @param height
36 | * @param framerate
37 | */
38 | public H264Encoder(int width, int height, int framerate) {
39 | this.width = width;
40 | this.height = height;
41 | this.framerate = framerate;
42 |
43 | MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", width, height);
44 | mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar);
45 | mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, width * height * 5);
46 | mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
47 | mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
48 | try {
49 | mediaCodec = MediaCodec.createEncoderByType("video/avc");
50 | mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
51 | mediaCodec.start();
52 | createfile();
53 | } catch (IOException e) {
54 | e.printStackTrace();
55 | }
56 | }
57 |
58 | private void createfile() {
59 | String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.mp4";
60 | File file = new File(path);
61 | if (file.exists()) {
62 | file.delete();
63 | }
64 | try {
65 | outputStream = new BufferedOutputStream(new FileOutputStream(file));
66 | } catch (Exception e) {
67 | e.printStackTrace();
68 | }
69 | }
70 |
71 | public void putData(byte[] buffer) {
72 | if (yuv420Queue.size() >= 10) {
73 | yuv420Queue.poll();
74 | }
75 | yuv420Queue.add(buffer);
76 | }
77 |
78 | /***
79 | * 开始编码
80 | */
81 | public void startEncoder() {
82 | new Thread(new Runnable() {
83 |
84 | @Override
85 | public void run() {
86 | isRuning = true;
87 | byte[] input = null;
88 | long pts = 0;
89 | long generateIndex = 0;
90 |
91 | while (isRuning) {
92 | if (yuv420Queue.size() > 0) {
93 | input = yuv420Queue.poll();
94 | byte[] yuv420sp = new byte[width * height * 3 / 2];
95 | // 必须要转格式,否则录制的内容播放出来为绿屏
96 | NV21ToNV12(input, yuv420sp, width, height);
97 | input = yuv420sp;
98 | }
99 | if (input != null) {
100 | try {
101 | ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
102 | ByteBuffer[] outputBuffers = mediaCodec.getOutputBuffers();
103 | int inputBufferIndex = mediaCodec.dequeueInputBuffer(-1);
104 | if (inputBufferIndex >= 0) {
105 | pts = computePresentationTime(generateIndex);
106 | ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
107 | inputBuffer.clear();
108 | inputBuffer.put(input);
109 | mediaCodec.queueInputBuffer(inputBufferIndex, 0, input.length, System.currentTimeMillis(), 0);
110 | generateIndex += 1;
111 | }
112 |
113 | MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
114 | int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, TIMEOUT_USEC);
115 | while (outputBufferIndex >= 0) {
116 | ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];
117 | byte[] outData = new byte[bufferInfo.size];
118 | outputBuffer.get(outData);
119 | if (bufferInfo.flags == MediaCodec.BUFFER_FLAG_CODEC_CONFIG) {
120 | configbyte = new byte[bufferInfo.size];
121 | configbyte = outData;
122 | } else if (bufferInfo.flags == MediaCodec.BUFFER_FLAG_SYNC_FRAME) {
123 | byte[] keyframe = new byte[bufferInfo.size + configbyte.length];
124 | System.arraycopy(configbyte, 0, keyframe, 0, configbyte.length);
125 | System.arraycopy(outData, 0, keyframe, configbyte.length, outData.length);
126 | outputStream.write(keyframe, 0, keyframe.length);
127 | } else {
128 | outputStream.write(outData, 0, outData.length);
129 | }
130 |
131 | mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
132 | outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, TIMEOUT_USEC);
133 | }
134 |
135 | } catch (Throwable t) {
136 | t.printStackTrace();
137 | }
138 | } else {
139 | try {
140 | Thread.sleep(500);
141 | } catch (InterruptedException e) {
142 | e.printStackTrace();
143 | }
144 | }
145 | }
146 |
147 | // 停止编解码器并释放资源
148 | try {
149 | mediaCodec.stop();
150 | mediaCodec.release();
151 | } catch (Exception e) {
152 | e.printStackTrace();
153 | }
154 |
155 | // 关闭数据流
156 | try {
157 | outputStream.flush();
158 | outputStream.close();
159 | } catch (IOException e) {
160 | e.printStackTrace();
161 | }
162 | }
163 | }).start();
164 | }
165 |
166 | /**
167 | * 停止编码数据
168 | */
169 | public void stopEncoder() {
170 | isRuning = false;
171 | }
172 |
173 | private void NV21ToNV12(byte[] nv21, byte[] nv12, int width, int height) {
174 | if (nv21 == null || nv12 == null) return;
175 | int framesize = width * height;
176 | int i = 0, j = 0;
177 | System.arraycopy(nv21, 0, nv12, 0, framesize);
178 | for (i = 0; i < framesize; i++) {
179 | nv12[i] = nv21[i];
180 | }
181 | for (j = 0; j < framesize / 2; j += 2) {
182 | nv12[framesize + j - 1] = nv21[j + framesize];
183 | }
184 | for (j = 0; j < framesize / 2; j += 2) {
185 | nv12[framesize + j] = nv21[j + framesize - 1];
186 | }
187 | }
188 |
189 | /**
190 | * 根据帧数生成时间戳
191 | */
192 | private long computePresentationTime(long frameIndex) {
193 | return 132 + frameIndex * 1000000 / framerate;
194 | }
195 | }
196 |
--------------------------------------------------------------------------------
/app/src/main/java/com/renhui/androidrecorder/onlyh264/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.renhui.androidrecorder.onlyh264;
2 |
3 | import android.Manifest;
4 | import android.content.Intent;
5 | import android.content.pm.PackageManager;
6 | import android.graphics.ImageFormat;
7 | import android.hardware.Camera;
8 | import android.media.MediaCodecInfo;
9 | import android.media.MediaCodecList;
10 | import android.os.Build;
11 | import android.os.Bundle;
12 | import android.support.v4.app.ActivityCompat;
13 | import android.support.v4.content.ContextCompat;
14 | import android.support.v7.app.AppCompatActivity;
15 | import android.util.Log;
16 | import android.view.SurfaceHolder;
17 | import android.view.SurfaceView;
18 | import android.view.View;
19 | import android.widget.Button;
20 | import android.widget.Toast;
21 |
22 | import com.renhui.androidrecorder.muxer.MediaMuxerActivity;
23 | import com.renhui.androidrecorder.R;
24 |
25 | import java.io.IOException;
26 |
27 | public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PreviewCallback {
28 |
29 | Camera camera;
30 | SurfaceView surfaceView;
31 | SurfaceHolder surfaceHolder;
32 | Button muxerButton;
33 |
34 | int width = 1280;
35 | int height = 720;
36 | int framerate = 30;
37 | H264Encoder encoder;
38 |
39 | @Override
40 | protected void onCreate(Bundle savedInstanceState) {
41 | super.onCreate(savedInstanceState);
42 |
43 | setContentView(R.layout.activity_main);
44 |
45 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
46 | ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED ||
47 | ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
48 | ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
49 | Toast.makeText(this, "申请权限", Toast.LENGTH_SHORT).show();
50 | // 申请 相机 麦克风权限
51 | ActivityCompat.requestPermissions(this, new String[]{
52 | Manifest.permission.CAMERA,
53 | Manifest.permission.RECORD_AUDIO,
54 | Manifest.permission.WRITE_EXTERNAL_STORAGE,
55 | Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
56 | }
57 |
58 | surfaceView = (SurfaceView) findViewById(R.id.surface_view);
59 | surfaceHolder = surfaceView.getHolder();
60 | surfaceHolder.addCallback(this);
61 | muxerButton = (Button) findViewById(R.id.go_muxer);
62 | muxerButton.setOnClickListener(new View.OnClickListener() {
63 | @Override
64 | public void onClick(View view) {
65 | Intent intent = new Intent(MainActivity.this, MediaMuxerActivity.class);
66 | startActivity(intent);
67 | finish();
68 | }
69 | });
70 |
71 | if (supportH264Codec()) {
72 | Log.e("MainActivity", "support H264 hard codec");
73 | } else {
74 | Log.e("MainActivity", "not support H264 hard codec");
75 | }
76 | }
77 |
78 | private boolean supportH264Codec() {
79 | // 遍历支持的编码格式信息
80 | if (Build.VERSION.SDK_INT >= 18) {
81 | for (int j = MediaCodecList.getCodecCount() - 1; j >= 0; j--) {
82 | MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(j);
83 |
84 | String[] types = codecInfo.getSupportedTypes();
85 | for (int i = 0; i < types.length; i++) {
86 | if (types[i].equalsIgnoreCase("video/avc")) {
87 | return true;
88 | }
89 | }
90 | }
91 | }
92 | return false;
93 | }
94 |
95 |
96 | @Override
97 | public void surfaceCreated(SurfaceHolder surfaceHolder) {
98 | Log.w("MainActivity", "enter surfaceCreated method");
99 | // 目前设定的是,当surface创建后,就打开摄像头开始预览
100 | camera = Camera.open();
101 | camera.setDisplayOrientation(90);
102 | Camera.Parameters parameters = camera.getParameters();
103 | parameters.setPreviewFormat(ImageFormat.NV21);
104 | parameters.setPreviewSize(1280, 720);
105 |
106 | try {
107 | camera.setParameters(parameters);
108 | camera.setPreviewDisplay(surfaceHolder);
109 | camera.setPreviewCallback(this);
110 | camera.startPreview();
111 | } catch (IOException e) {
112 | e.printStackTrace();
113 | }
114 |
115 | encoder = new H264Encoder(width, height, framerate);
116 | encoder.startEncoder();
117 | }
118 |
119 | @Override
120 | public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
121 | Log.w("MainActivity", "enter surfaceChanged method");
122 | }
123 |
124 | @Override
125 | public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
126 | Log.w("MainActivity", "enter surfaceDestroyed method");
127 |
128 | // 停止预览并释放资源
129 | if (camera != null) {
130 | camera.setPreviewCallback(null);
131 | camera.stopPreview();
132 | camera = null;
133 | }
134 |
135 | if (encoder != null) {
136 | encoder.stopEncoder();
137 | }
138 | }
139 |
140 | @Override
141 | public void onPreviewFrame(byte[] bytes, Camera camera) {
142 | if (encoder != null) {
143 | encoder.putData(bytes);
144 | }
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
12 |
13 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_media_muxer.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
14 |
15 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/renhui/AndroidRecorder/cc8b79a94594abf12890a6b66953c8127ab773bb/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AndroidRecorder
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/renhui/androidrecorder/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.renhui.androidrecorder;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.3'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------