OSDN Git Service

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