OSDN Git Service

e1d961be9a19c03a117ad9345ffd27bc70f03e22
[android-x86/external-stagefright-plugins.git] / utils / ffmpeg_utils.cpp
1 /*
2  * Copyright 2012 Michael Chen <omxcodec@gmail.com>
3  * Copyright 2015 The CyanogenMod Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 //#define LOG_NDEBUG 0
19 #define LOG_TAG "FFMPEG"
20 #include <utils/Log.h>
21
22 #include <utils/Errors.h>
23
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27
28 #include "config.h"
29
30 #include <unistd.h>
31 #include <stdlib.h>
32 #include <inttypes.h>
33 #include <math.h>
34 #include <limits.h> /* INT_MAX */
35 #include <time.h>
36
37 #undef strncpy
38 #include <string.h>
39
40 #ifdef __cplusplus
41 }
42 #endif
43
44 #include <cutils/properties.h>
45
46 #include "ffmpeg_utils.h"
47 #include "ffmpeg_source.h"
48
49 // log
50 static int flags;
51
52 // dummy
53 const char program_name[] = "dummy";
54 const int program_birth_year = 2012;
55
56 // init ffmpeg
57 static pthread_mutex_t s_init_mutex = PTHREAD_MUTEX_INITIALIZER;
58 static int s_ref_count = 0;
59
60 namespace android {
61
62 //////////////////////////////////////////////////////////////////////////////////
63 // log
64 //////////////////////////////////////////////////////////////////////////////////
65 static void sanitize(uint8_t *line){
66     while(*line){
67         if(*line < 0x08 || (*line > 0x0D && *line < 0x20))
68             *line='?';
69         line++;
70     }
71 }
72
73 // TODO, remove static variables to support multi-instances
74 void nam_av_log_callback(void* ptr, int level, const char* fmt, va_list vl)
75 {
76     static int print_prefix = 1;
77     static int count;
78     static char prev[1024];
79     char line[1024];
80     static int is_atty;
81
82     if (level > av_log_get_level())
83         return;
84     av_log_format_line(ptr, level, fmt, vl, line, sizeof(line), &print_prefix);
85
86     if (print_prefix && (flags & AV_LOG_SKIP_REPEATED) && !strcmp(line, prev)){
87         count++;
88         return;
89     }
90     if (count > 0) {
91         ALOGI("Last message repeated %d times\n", count);
92         count = 0;
93     }
94     strcpy(prev, line);
95     sanitize((uint8_t *)line);
96
97 #if 0
98     ALOGI("%s", line);
99 #else
100 #define LOG_BUF_SIZE 1024
101     static char g_msg[LOG_BUF_SIZE];
102     static int g_msg_len = 0;
103
104     int saw_lf, check_len;
105
106     do {
107         check_len = g_msg_len + strlen(line) + 1;
108         if (check_len <= LOG_BUF_SIZE) {
109             /* lf: Line feed ('\n') */
110             saw_lf = (strchr(line, '\n') != NULL) ? 1 : 0;
111             strncpy(g_msg + g_msg_len, line, strlen(line));
112             g_msg_len += strlen(line);
113             if (!saw_lf) {
114                /* skip */
115                return;
116             } else {
117                /* attach the line feed */
118                g_msg_len += 1;
119                g_msg[g_msg_len] = '\n';
120             }
121         } else {
122             /* trace is fragmented */
123             g_msg_len += 1;
124             g_msg[g_msg_len] = '\n';
125         }
126         ALOGI("%s", g_msg);
127         /* reset g_msg and g_msg_len */
128         memset(g_msg, 0, LOG_BUF_SIZE);
129         g_msg_len = 0;
130      } while (check_len > LOG_BUF_SIZE);
131 #endif
132 }
133
134 void nam_av_log_set_flags(int arg)
135 {
136     flags = arg;
137 }
138
139 #if 0
140 const struct { const char *name; int level; } log_levels[] = {
141     { "quiet"  , AV_LOG_QUIET   },
142     { "panic"  , AV_LOG_PANIC   },
143     { "fatal"  , AV_LOG_FATAL   },
144     { "error"  , AV_LOG_ERROR   },
145     { "warning", AV_LOG_WARNING },
146     { "info"   , AV_LOG_INFO    },
147     { "verbose", AV_LOG_VERBOSE },
148     { "debug"  , AV_LOG_DEBUG   },
149 };
150
151 #define AV_LOG_QUIET    -8
152 #define AV_LOG_PANIC     0
153 #define AV_LOG_FATAL     8
154 #define AV_LOG_ERROR    16
155 #define AV_LOG_WARNING  24
156 #define AV_LOG_INFO     32
157 #define AV_LOG_VERBOSE  40
158 #define AV_LOG_DEBUG    48
159 #endif
160
161 //////////////////////////////////////////////////////////////////////////////////
162 // constructor and destructor
163 //////////////////////////////////////////////////////////////////////////////////
164 /* Mutex manager callback. */
165 static int lockmgr(void **mtx, enum AVLockOp op)
166 {
167     switch (op) {
168     case AV_LOCK_CREATE:
169         *mtx = (void *)av_malloc(sizeof(pthread_mutex_t));
170         if (!*mtx)
171             return 1;
172         return !!pthread_mutex_init((pthread_mutex_t *)(*mtx), NULL);
173     case AV_LOCK_OBTAIN:
174         return !!pthread_mutex_lock((pthread_mutex_t *)(*mtx));
175     case AV_LOCK_RELEASE:
176         return !!pthread_mutex_unlock((pthread_mutex_t *)(*mtx));
177     case AV_LOCK_DESTROY:
178         pthread_mutex_destroy((pthread_mutex_t *)(*mtx));
179         av_freep(mtx);
180         return 0;
181     }
182     return 1;
183 }
184
185 /**
186  * To debug ffmpeg", type this command on the console before starting playback:
187  *     setprop debug.nam.ffmpeg 1
188  * To disable the debug, type:
189  *     setprop debug.nam.ffmpge 0
190 */
191 status_t initFFmpeg() 
192 {
193     status_t ret = OK;
194     bool debug_enabled = false;
195     char value[PROPERTY_VALUE_MAX];
196
197     pthread_mutex_lock(&s_init_mutex);
198
199     if (property_get("debug.nam.ffmpeg", value, NULL)
200         && (!strcmp(value, "1") || !av_strcasecmp(value, "true"))) {
201         ALOGI("set ffmpeg debug level to AV_LOG_DEBUG");
202         debug_enabled = true;
203     }
204     if (debug_enabled)
205         av_log_set_level(AV_LOG_DEBUG);
206     else
207         av_log_set_level(AV_LOG_INFO);
208
209     if(s_ref_count == 0) {
210         nam_av_log_set_flags(AV_LOG_SKIP_REPEATED);
211         av_log_set_callback(nam_av_log_callback);
212
213         /* register all codecs, demux and protocols */
214         avcodec_register_all();
215 #if 0
216         avdevice_register_all();
217 #endif
218         av_register_all();
219         avformat_network_init();
220
221         /* register android source */
222         ffmpeg_register_android_source();
223
224         if (av_lockmgr_register(lockmgr)) {
225             ALOGE("could not initialize lock manager!");
226             ret = NO_INIT;
227         }
228     }
229
230     // update counter
231     s_ref_count++;
232
233     pthread_mutex_unlock(&s_init_mutex);
234
235     return ret;
236 }
237
238 void deInitFFmpeg()
239 {
240     pthread_mutex_lock(&s_init_mutex);
241
242     // update counter
243     s_ref_count--;
244
245     if(s_ref_count == 0) {
246         av_lockmgr_register(NULL);
247         avformat_network_deinit();
248     }
249
250     pthread_mutex_unlock(&s_init_mutex);
251 }
252
253 //////////////////////////////////////////////////////////////////////////////////
254 // parser
255 //////////////////////////////////////////////////////////////////////////////////
256 /* H.264 bitstream with start codes, NOT AVC1! */
257 static int h264_split(AVCodecContext *avctx __unused,
258         const uint8_t *buf, int buf_size, int check_compatible_only)
259 {
260     int i;
261     uint32_t state = -1;
262     int has_sps= 0;
263     int has_pps= 0;
264
265     //av_hex_dump(stderr, buf, 100);
266
267     for(i=0; i<=buf_size; i++){
268         if((state&0xFFFFFF1F) == 0x107) {
269             ALOGI("found NAL_SPS");
270             has_sps=1;
271         }
272         if((state&0xFFFFFF1F) == 0x108) {
273             ALOGI("found NAL_PPS");
274             has_pps=1;
275             if (check_compatible_only)
276                 return (has_sps & has_pps);
277         }
278         if((state&0xFFFFFF00) == 0x100
279                 && ((state&0xFFFFFF1F) == 0x101
280                     || (state&0xFFFFFF1F) == 0x102
281                     || (state&0xFFFFFF1F) == 0x105)){
282             if(has_pps){
283                 while(i>4 && buf[i-5]==0) i--;
284                 return i-4;
285             }
286         }
287         if (i<buf_size)
288             state= (state<<8) | buf[i];
289     }
290     return 0;
291 }
292
293 static int mpegvideo_split(AVCodecContext *avctx __unused,
294         const uint8_t *buf, int buf_size, int check_compatible_only __unused)
295 {
296     int i;
297     uint32_t state= -1;
298     int found=0;
299
300     for(i=0; i<buf_size; i++){
301         state= (state<<8) | buf[i];
302         if(state == 0x1B3){
303             found=1;
304         }else if(found && state != 0x1B5 && state < 0x200 && state >= 0x100)
305             return i-3;
306     }
307     return 0;
308 }
309
310 /* split extradata from buf for Android OMXCodec */
311 int parser_split(AVCodecContext *avctx,
312         const uint8_t *buf, int buf_size)
313 {
314     if (!avctx || !buf || buf_size <= 0) {
315         ALOGE("parser split, valid params");
316         return 0;
317     }
318
319     if (avctx->codec_id == AV_CODEC_ID_H264) {
320         return h264_split(avctx, buf, buf_size, 0);
321     } else if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
322             avctx->codec_id == AV_CODEC_ID_MPEG4) {
323         return mpegvideo_split(avctx, buf, buf_size, 0);
324     } else {
325         ALOGE("parser split, unsupport the codec, id: 0x%0x", avctx->codec_id);
326     }
327
328     return 0;
329 }
330
331 int is_extradata_compatible_with_android(AVCodecContext *avctx)
332 {
333     if (avctx->extradata_size <= 0) {
334         ALOGI("extradata_size <= 0, extradata is not compatible with "
335                 "android decoder, the codec id: 0x%0x", avctx->codec_id);
336         return 0;
337     }
338
339     if (avctx->codec_id == AV_CODEC_ID_H264
340             && avctx->extradata[0] != 1 /* configurationVersion */) {
341         // SPS + PPS
342         return !!(h264_split(avctx, avctx->extradata,
343                     avctx->extradata_size, 1) > 0);
344     } else {
345         // default, FIXME
346         return !!(avctx->extradata_size > 0);
347     }
348 }
349
350 //////////////////////////////////////////////////////////////////////////////////
351 // packet queue
352 //////////////////////////////////////////////////////////////////////////////////
353 void packet_queue_init(PacketQueue *q)
354 {
355     memset(q, 0, sizeof(PacketQueue));
356     q->abort_request = 1;
357 }
358
359 void packet_queue_destroy(PacketQueue *q)
360 {
361     packet_queue_abort(q);
362     packet_queue_flush(q);
363 }
364
365 void packet_queue_flush(PacketQueue *q)
366 {
367     AVPacketList *pkt, *pkt1;
368
369     Mutex::Autolock autoLock(q->lock);
370     for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
371         pkt1 = pkt->next;
372         av_free_packet(&pkt->pkt);
373         av_freep(&pkt);
374     }
375     q->last_pkt = NULL;
376     q->first_pkt = NULL;
377     q->nb_packets = 0;
378     q->size = 0;
379 }
380
381 void packet_queue_abort(PacketQueue *q)
382 {
383     q->abort_request = 1;
384     Mutex::Autolock autoLock(q->lock);
385     q->cond.signal();
386 }
387
388 static int packet_queue_put_private(PacketQueue *q, AVPacket *pkt)
389 {
390     AVPacketList *pkt1;
391
392     if (q->abort_request)
393         return -1;
394
395     pkt1 = (AVPacketList *)av_malloc(sizeof(AVPacketList));
396     if (!pkt1)
397         return -1;
398     pkt1->pkt = *pkt;
399     pkt1->next = NULL;
400
401     if (!q->last_pkt)
402         q->first_pkt = pkt1;
403     else
404         q->last_pkt->next = pkt1;
405     q->last_pkt = pkt1;
406     q->nb_packets++;
407     //q->size += pkt1->pkt.size + sizeof(*pkt1);
408     q->size += pkt1->pkt.size;
409     q->cond.signal();
410     return 0;
411 }
412
413 int packet_queue_put(PacketQueue *q, AVPacket *pkt)
414 {
415     int ret;
416
417     /* duplicate the packet */
418     if (pkt != &q->flush_pkt && av_dup_packet(pkt) < 0)
419         return -1;
420
421     q->lock.lock();
422     ret = packet_queue_put_private(q, pkt);
423     q->lock.unlock();
424
425     if (pkt != &q->flush_pkt && ret < 0)
426         av_free_packet(pkt);
427
428     return ret;
429 }
430
431 int packet_queue_is_wait_for_data(PacketQueue *q)
432 {
433     Mutex::Autolock autoLock(q->lock);
434     return q->wait_for_data;
435 }
436
437 int packet_queue_put_nullpacket(PacketQueue *q, int stream_index)
438 {
439     AVPacket pkt1, *pkt = &pkt1;
440     av_init_packet(pkt);
441     pkt->data = NULL;
442     pkt->size = 0;
443     pkt->stream_index = stream_index;
444     return packet_queue_put(q, pkt);
445 }
446
447 /* packet queue handling */
448 /* return < 0 if aborted, 0 if no packet and > 0 if packet.  */
449 int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
450 {
451     AVPacketList *pkt1;
452     int ret = -1;
453
454     Mutex::Autolock autoLock(q->lock);
455
456     while (!q->abort_request) {
457         pkt1 = q->first_pkt;
458         if (pkt1) {
459             q->first_pkt = pkt1->next;
460             if (!q->first_pkt)
461                 q->last_pkt = NULL;
462             q->nb_packets--;
463             //q->size -= pkt1->pkt.size + sizeof(*pkt1);
464             q->size -= pkt1->pkt.size;
465             *pkt = pkt1->pkt;
466             av_free(pkt1);
467             ret = 1;
468             break;
469         } else if (!block) {
470             ret = 0;
471             break;
472         } else {
473             q->wait_for_data = 1;
474             q->cond.waitRelative(q->lock, 10000000LL);
475         }
476     }
477     q->wait_for_data = 0;
478     return ret;
479 }
480
481 void packet_queue_start(PacketQueue *q)
482 {
483     Mutex::Autolock autoLock(q->lock);
484     av_init_packet(&q->flush_pkt);
485     q->flush_pkt.data = (uint8_t *)&q->flush_pkt;
486     q->flush_pkt.size = 0;
487     q->abort_request = 0;
488     packet_queue_put_private(q, &q->flush_pkt);
489 }
490
491 //////////////////////////////////////////////////////////////////////////////////
492 // misc
493 //////////////////////////////////////////////////////////////////////////////////
494 bool setup_vorbis_extradata(uint8_t **extradata, int *extradata_size,
495         const uint8_t *header_start[3], const int header_len[3])
496 {
497     uint8_t *p = NULL;
498     int len = 0;
499     int i = 0;
500
501     len = header_len[0] + header_len[1] + header_len[2];
502     p = *extradata = (uint8_t *)av_mallocz(64 + len + len/255);
503     if (!p) {
504         ALOGE("oom for vorbis extradata");
505         return false;
506     }
507
508     *p++ = 2;
509     p += av_xiphlacing(p, header_len[0]);
510     p += av_xiphlacing(p, header_len[1]);
511     for (i = 0; i < 3; i++) {
512         if (header_len[i] > 0) {
513             memcpy(p, header_start[i], header_len[i]);
514             p += header_len[i];
515         }
516     }
517     *extradata_size = p - *extradata;
518
519     return true;
520 }
521
522 int64_t get_timestamp() {
523     struct timeval tv;
524     gettimeofday(&tv, NULL);
525     return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
526 }
527
528 audio_format_t to_android_audio_format(enum AVSampleFormat fmt) {
529     AVSampleFormat packed = av_get_packed_sample_fmt(fmt);
530     if (packed == AV_SAMPLE_FMT_U8)
531         return AUDIO_FORMAT_PCM_8_BIT;
532     if (packed == AV_SAMPLE_FMT_S16)
533         return AUDIO_FORMAT_PCM_16_BIT;
534     if (packed == AV_SAMPLE_FMT_S32)
535         return AUDIO_FORMAT_PCM_32_BIT;
536     if (packed == AV_SAMPLE_FMT_FLT)
537         return AUDIO_FORMAT_PCM_FLOAT;
538     return AUDIO_FORMAT_DEFAULT;
539 }
540
541 }  // namespace android
542