OSDN Git Service

46f3d9e2d063c70ca41a436958737a409ca5c2db
[android-x86/external-stagefright-plugins.git] / utils / ffmpeg_utils.cpp
1 /*
2  * Copyright 2012 Michael Chen <omxcodec@gmail.com>
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #define LOG_NDEBUG 0
18 #define LOG_TAG "FFMPEG"
19 #include <utils/Log.h>
20
21 #include <utils/Errors.h>
22
23 #ifdef __cplusplus
24 extern "C" {
25 #endif
26
27 #include "config.h"
28
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <inttypes.h>
32 #include <math.h>
33 #include <limits.h> /* INT_MAX */
34
35 #include "libavutil/avstring.h"
36 #include "libavutil/colorspace.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/pixdesc.h"
39 #include "libavutil/imgutils.h"
40 #include "libavutil/dict.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/samplefmt.h"
43 #include "libavutil/avassert.h"
44 #include "libavformat/avformat.h"
45 #include "libavdevice/avdevice.h"
46 #include "libswscale/swscale.h"
47 #include "libavcodec/audioconvert.h"
48 #include "libavutil/opt.h"
49 #include "libavutil/internal.h"
50 #include "libavcodec/avfft.h"
51 #include "libswresample/swresample.h"
52
53 #undef strncpy
54 #include <string.h>
55
56 #ifdef __cplusplus
57 }
58 #endif
59
60 #include <cutils/properties.h>
61
62 #include "ffmpeg_utils.h"
63 #include "ffmpeg_source.h"
64
65 // log
66 static int flags;
67
68 // dummy
69 const char program_name[] = "dummy";
70 const int program_birth_year = 2012;
71
72 // init ffmpeg
73 static pthread_mutex_t s_init_mutex = PTHREAD_MUTEX_INITIALIZER;
74 static int s_ref_count = 0;
75
76 namespace android {
77
78 //////////////////////////////////////////////////////////////////////////////////
79 // dummy
80 //////////////////////////////////////////////////////////////////////////////////
81 #ifdef __cplusplus
82 extern "C" {
83 #endif
84
85 void exit_program(int ret)
86 {
87     // do nothing
88 }
89
90 void show_help_default(const char *opt, const char *arg)
91 {
92     // do nothing
93 }
94
95 #ifdef __cplusplus
96 }
97 #endif
98
99 //////////////////////////////////////////////////////////////////////////////////
100 // log
101 //////////////////////////////////////////////////////////////////////////////////
102 static void sanitize(uint8_t *line){
103     while(*line){
104         if(*line < 0x08 || (*line > 0x0D && *line < 0x20))
105             *line='?';
106         line++;
107     }
108 }
109
110 // TODO, remove static variables to support multi-instances
111 void nam_av_log_callback(void* ptr, int level, const char* fmt, va_list vl)
112 {
113     static int print_prefix = 1;
114     static int count;
115     static char prev[1024];
116     char line[1024];
117     static int is_atty;
118
119     if (level > av_log_get_level())
120         return;
121     av_log_format_line(ptr, level, fmt, vl, line, sizeof(line), &print_prefix);
122
123     if (print_prefix && (flags & AV_LOG_SKIP_REPEATED) && !strcmp(line, prev)){
124         count++;
125         return;
126     }
127     if (count > 0) {
128         ALOGI("Last message repeated %d times\n", count);
129         count = 0;
130     }
131     strcpy(prev, line);
132     sanitize((uint8_t *)line);
133
134 #if 0
135     ALOGI("%s", line);
136 #else
137 #define LOG_BUF_SIZE 1024
138     static char g_msg[LOG_BUF_SIZE];
139     static int g_msg_len = 0;
140
141     int saw_lf, check_len;
142
143     do {
144         check_len = g_msg_len + strlen(line) + 1;
145         if (check_len <= LOG_BUF_SIZE) {
146             /* lf: Line feed ('\n') */
147             saw_lf = (strchr(line, '\n') != NULL) ? 1 : 0;
148             strncpy(g_msg + g_msg_len, line, strlen(line));
149             g_msg_len += strlen(line);
150             if (!saw_lf) {
151                /* skip */
152                return;
153             } else {
154                /* attach the line feed */
155                g_msg_len += 1;
156                g_msg[g_msg_len] = '\n';
157             }
158         } else {
159             /* trace is fragmented */
160             g_msg_len += 1;
161             g_msg[g_msg_len] = '\n';
162         }
163         ALOGI("%s", g_msg);
164         /* reset g_msg and g_msg_len */
165         memset(g_msg, 0, LOG_BUF_SIZE);
166         g_msg_len = 0;
167      } while (check_len > LOG_BUF_SIZE);
168 #endif
169 }
170
171 void nam_av_log_set_flags(int arg)
172 {
173     flags = arg;
174 }
175
176 #if 0
177 const struct { const char *name; int level; } log_levels[] = {
178     { "quiet"  , AV_LOG_QUIET   },
179     { "panic"  , AV_LOG_PANIC   },
180     { "fatal"  , AV_LOG_FATAL   },
181     { "error"  , AV_LOG_ERROR   },
182     { "warning", AV_LOG_WARNING },
183     { "info"   , AV_LOG_INFO    },
184     { "verbose", AV_LOG_VERBOSE },
185     { "debug"  , AV_LOG_DEBUG   },
186 };
187
188 #define AV_LOG_QUIET    -8
189 #define AV_LOG_PANIC     0
190 #define AV_LOG_FATAL     8
191 #define AV_LOG_ERROR    16
192 #define AV_LOG_WARNING  24
193 #define AV_LOG_INFO     32
194 #define AV_LOG_VERBOSE  40
195 #define AV_LOG_DEBUG    48
196 #endif
197
198 //////////////////////////////////////////////////////////////////////////////////
199 // constructor and destructor
200 //////////////////////////////////////////////////////////////////////////////////
201 /* Mutex manager callback. */
202 static int lockmgr(void **mtx, enum AVLockOp op)
203 {
204     switch (op) {
205     case AV_LOCK_CREATE:
206         *mtx = (void *)av_malloc(sizeof(pthread_mutex_t));
207         if (!*mtx)
208             return 1;
209         return !!pthread_mutex_init((pthread_mutex_t *)(*mtx), NULL);
210     case AV_LOCK_OBTAIN:
211         return !!pthread_mutex_lock((pthread_mutex_t *)(*mtx));
212     case AV_LOCK_RELEASE:
213         return !!pthread_mutex_unlock((pthread_mutex_t *)(*mtx));
214     case AV_LOCK_DESTROY:
215         pthread_mutex_destroy((pthread_mutex_t *)(*mtx));
216         av_freep(mtx);
217         return 0;
218     }
219     return 1;
220 }
221
222 /**
223  * To debug ffmpeg", type this command on the console before starting playback:
224  *     setprop debug.nam.ffmpeg 1
225  * To disable the debug, type:
226  *     setprop debug.nam.ffmpge 0
227 */
228 status_t initFFmpeg() 
229 {
230     status_t ret = OK;
231     bool debug_enabled = false;
232     char value[PROPERTY_VALUE_MAX];
233
234     pthread_mutex_lock(&s_init_mutex);
235
236     if (property_get("debug.nam.ffmpeg", value, NULL)
237         && (!strcmp(value, "1") || !av_strcasecmp(value, "true"))) {
238         ALOGI("set ffmpeg debug level to AV_LOG_DEBUG");
239         debug_enabled = true;
240     }
241     if (debug_enabled)
242         av_log_set_level(AV_LOG_DEBUG);
243     else
244         av_log_set_level(AV_LOG_INFO);
245
246     if(s_ref_count == 0) {
247         nam_av_log_set_flags(AV_LOG_SKIP_REPEATED);
248         av_log_set_callback(nam_av_log_callback);
249
250         /* register all codecs, demux and protocols */
251         avcodec_register_all();
252 #if CONFIG_AVDEVICE
253         avdevice_register_all();
254 #endif
255         av_register_all();
256         avformat_network_init();
257
258         /* register android source */
259         ffmpeg_register_android_source();
260
261         if (av_lockmgr_register(lockmgr)) {
262             ALOGE("could not initialize lock manager!");
263             ret = NO_INIT;
264         }
265     }
266
267     // update counter
268     s_ref_count++;
269
270     pthread_mutex_unlock(&s_init_mutex);
271
272     return ret;
273 }
274
275 void deInitFFmpeg()
276 {
277     pthread_mutex_lock(&s_init_mutex);
278
279     // update counter
280     s_ref_count--;
281
282     if(s_ref_count == 0) {
283         av_lockmgr_register(NULL);
284         avformat_network_deinit();
285     }
286
287     pthread_mutex_unlock(&s_init_mutex);
288 }
289
290 //////////////////////////////////////////////////////////////////////////////////
291 // parser
292 //////////////////////////////////////////////////////////////////////////////////
293 /* H.264 bitstream with start codes, NOT AVC1! ref: libavcodec/h264_parser.c */
294 static int h264_split(AVCodecContext *avctx,
295                 const uint8_t *buf, int buf_size, int check_compatible_only)
296 {
297     int i;
298     uint32_t state = -1;
299     int has_sps= 0;
300     int has_pps= 0;
301
302     //av_hex_dump(stderr, buf, 100);
303
304     for(i=0; i<=buf_size; i++){
305         if((state&0xFFFFFF1F) == 0x107) {
306             ALOGI("found NAL_SPS");
307             has_sps=1;
308         }
309         if((state&0xFFFFFF1F) == 0x108) {
310             ALOGI("found NAL_PPS");
311             has_pps=1;
312             if (check_compatible_only)
313                 return (has_sps & has_pps);
314         }
315         if((state&0xFFFFFF00) == 0x100
316                                 && ((state&0xFFFFFF1F) == 0x101
317                                         || (state&0xFFFFFF1F) == 0x102
318                                         || (state&0xFFFFFF1F) == 0x105)){
319             if(has_pps){
320                 while(i>4 && buf[i-5]==0) i--;
321                 return i-4;
322             }
323         }
324         if (i<buf_size)
325             state= (state<<8) | buf[i];
326     }
327     return 0;
328 }
329
330 /* ref: libavcodec/mpegvideo_parser.c */
331 static int mpegvideo_split(AVCodecContext *avctx,
332                 const uint8_t *buf, int buf_size, int check_compatible_only)
333 {
334     int i;
335     uint32_t state= -1;
336     int found=0;
337
338     for(i=0; i<buf_size; i++){
339         state= (state<<8) | buf[i];
340         if(state == 0x1B3){
341             found=1;
342         }else if(found && state != 0x1B5 && state < 0x200 && state >= 0x100)
343             return i-3;
344     }
345     return 0;
346 }
347
348 /* split extradata from buf for Android OMXCodec */
349 int parser_split(AVCodecContext *avctx,
350                 const uint8_t *buf, int buf_size)
351 {
352     if (!avctx || !buf || buf_size <= 0) {
353         ALOGE("parser split, valid params");
354         return 0;
355     }
356
357     if (avctx->codec_id == CODEC_ID_H264) {
358         return h264_split(avctx, buf, buf_size, 0);
359     } else if (avctx->codec_id == CODEC_ID_MPEG2VIDEO ||
360             avctx->codec_id == CODEC_ID_MPEG4) {
361         return mpegvideo_split(avctx, buf, buf_size, 0);
362     } else {
363         ALOGE("parser split, unsupport the codec, id: 0x%0x", avctx->codec_id);
364     }
365
366     return 0;
367 }
368
369 int is_extradata_compatible_with_android(AVCodecContext *avctx)
370 {
371     if (avctx->extradata_size <= 0) {
372         ALOGI("extradata_size <= 0, extradata is not compatible with "
373                                 "android decoder, the codec id: 0x%0x", avctx->codec_id);
374         return 0;
375     }
376
377     if (avctx->codec_id == CODEC_ID_H264
378                         && avctx->extradata[0] != 1 /* configurationVersion */) {
379         // SPS + PPS
380         return !!(h264_split(avctx, avctx->extradata,
381                                         avctx->extradata_size, 1) > 0);
382     } else {
383         // default, FIXME
384         return !!(avctx->extradata_size > 0);
385     }
386 }
387
388 }  // namespace android
389