1 /*
2     DeaDBeeF - The Ultimate Music Player
3     Copyright (C) 2009-2013 Alexey Yakovenko <waker@users.sourceforge.net>
4 
5     This program is free software; you can redistribute it and/or
6     modify it under the terms of the GNU General Public License
7     as published by the Free Software Foundation; either version 2
8     of the License, or (at your option) any later version.
9 
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14 
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 */
19 
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 //#include <alloca.h>
24 #include <errno.h>
25 
26 #include "../../deadbeef.h"
27 #include "../../strdupa.h"
28 
29 #include <libavformat/avformat.h>
30 #include <libavcodec/avcodec.h>
31 #include <libavutil/avutil.h>
32 #include <libavutil/avstring.h>
33 
34 #define AVERROR_EOF AVERROR(EPIPE)
35 
36 #if LIBAVFORMAT_VERSION_MAJOR < 53
37 #define av_register_protocol register_protocol
38 #endif
39 
40 #ifndef AV_VERSION_INT
41 #define AV_VERSION_INT(a, b, c) (a<<16 | b<<8 | c)
42 #endif
43 
44 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(54, 6, 0)
45 #define av_find_stream_info(ctx) avformat_find_stream_info(ctx,NULL)
46 #define avcodec_open(ctx,codec) avcodec_open2(ctx,codec,NULL)
47 #define av_get_bits_per_sample_format(fmt) (av_get_bytes_per_sample(fmt)*8)
48 #define av_close_input_file(ctx) avformat_close_input(&(ctx))
49 #endif
50 
51 //#define trace(...) { fprintf(stderr, __VA_ARGS__); }
52 #define trace(fmt,...)
53 
54 #define min(x,y) ((x)<(y)?(x):(y))
55 #define max(x,y) ((x)>(y)?(x):(y))
56 
57 static DB_decoder_t plugin;
58 static DB_functions_t *deadbeef;
59 
60 #define DEFAULT_EXTS "aa3;oma;ac3;vqf;amr;opus;tak;dsf;dff"
61 #define UNPOPULATED_EXTS_BY_FFMPEG \
62     "aif,aiff,afc,aifc,amr,asf," \
63     "wmv,wma,au,caf,webm," \
64     "gxf,lbc,mmf,mpg,mpeg,ts,m2t," \
65     "m2ts,mts,mxf,rm,ra,roq,sox," \
66     "spdif,swf,rcv,voc,w64,wav,wv"
67 
68 #define EXT_MAX 256
69 
70 #define FFMPEG_MAX_ANALYZE_DURATION 500000
71 
72 static char * exts[EXT_MAX] = {NULL};
73 
74 enum {
75     FT_ALAC = 0,
76     FT_WMA = 1,
77     FT_ATRAC3 = 2,
78     FT_VQF = 3,
79     FT_AC3 = 4,
80     FT_AMR = 5,
81     FT_UNKNOWN = 5
82 };
83 
84 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(54, 6, 0)
85 #define FF_PROTOCOL_NAME "deadbeef"
86 #endif
87 
88 typedef struct {
89     DB_fileinfo_t info;
90     AVCodec *codec;
91     AVCodecContext *ctx;
92     AVFormatContext *fctx;
93     AVPacket pkt;
94 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53, 40, 0)
95     AVFrame *frame;
96 #endif
97     int stream_id;
98 
99     int left_in_packet;
100     int have_packet;
101 
102     char *buffer;
103     int left_in_buffer;
104     int buffer_size;
105 
106     int startsample;
107     int endsample;
108     int currentsample;
109 } ffmpeg_info_t;
110 
111 static DB_playItem_t *current_track;
112 static DB_fileinfo_t *current_info;
113 
114 static DB_fileinfo_t *
ffmpeg_open(uint32_t hints)115 ffmpeg_open (uint32_t hints) {
116     DB_fileinfo_t *_info = malloc (sizeof (ffmpeg_info_t));
117     memset (_info, 0, sizeof (ffmpeg_info_t));
118     return _info;
119 }
120 
121 // ensure that the buffer can contain entire frame of frame_size bytes per channel
122 static int
ensure_buffer(ffmpeg_info_t * info,int frame_size)123 ensure_buffer (ffmpeg_info_t *info, int frame_size) {
124     if (!info->buffer || info->buffer_size < frame_size * info->ctx->channels) {
125         if (info->buffer) {
126             free (info->buffer);
127             info->buffer = NULL;
128         }
129         info->buffer_size = frame_size*info->ctx->channels;
130         info->left_in_buffer = 0;
131         int err = posix_memalign ((void **)&info->buffer, 16, info->buffer_size);
132         if (err) {
133             fprintf (stderr, "ffmpeg: failed to allocate %d bytes of buffer memory\n", info->buffer_size);
134             return -1;
135         }
136     }
137     return 0;
138 }
139 
140 static int
ffmpeg_init(DB_fileinfo_t * _info,DB_playItem_t * it)141 ffmpeg_init (DB_fileinfo_t *_info, DB_playItem_t *it) {
142     ffmpeg_info_t *info = (ffmpeg_info_t *)_info;
143     trace ("ffmpeg init %s\n", deadbeef->pl_find_meta (it, ":URI"));
144     // prepare to decode the track
145     // return -1 on failure
146 
147     int ret;
148     char *uri = NULL;
149     int i;
150 
151     deadbeef->pl_lock ();
152     {
153         const char *fname = deadbeef->pl_find_meta (it, ":URI");
154 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(54, 6, 0)
155         uri = strdupa (fname);
156 #else
157         int l = strlen (fname);
158         uri = alloca (l + sizeof (FF_PROTOCOL_NAME) + 1);
159 
160         // construct uri
161         memcpy (uri, FF_PROTOCOL_NAME, sizeof (FF_PROTOCOL_NAME)-1);
162         memcpy (uri + sizeof (FF_PROTOCOL_NAME)-1, ":", 1);
163         memcpy (uri + sizeof (FF_PROTOCOL_NAME), fname, l);
164         uri[sizeof (FF_PROTOCOL_NAME) + l] = 0;
165 #endif
166     }
167     deadbeef->pl_unlock ();
168     trace ("ffmpeg: uri: %s\n", uri);
169 
170     // open file
171     trace ("\033[0;31mffmpeg av_open_input_file\033[37;0m\n");
172     current_track = it;
173     current_info = _info;
174 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(54, 6, 0)
175     avformat_network_init();
176     info->fctx = avformat_alloc_context ();
177     if ((ret = avformat_open_input(&info->fctx, uri, NULL, NULL)) < 0) {
178 #else
179     if ((ret = av_open_input_file(&info->fctx, uri, NULL, 0, NULL)) < 0) {
180 #endif
181         current_track = NULL;
182         trace ("\033[0;31minfo->fctx is %p, ret %d/%s\033[0;31m\n", info->fctx, ret, strerror(-ret));
183         return -1;
184     }
185     trace ("\033[0;31mav_open_input_file done, ret=%d\033[0;31m\n", ret);
186     current_track = NULL;
187     current_info = NULL;
188 
189     trace ("\033[0;31mffmpeg av_find_stream_info\033[37;0m\n");
190     info->stream_id = -1;
191     info->fctx->max_analyze_duration = FFMPEG_MAX_ANALYZE_DURATION;
192     av_find_stream_info(info->fctx);
193     for (i = 0; i < info->fctx->nb_streams; i++)
194     {
195         info->ctx = info->fctx->streams[i]->codec;
196         if (info->ctx->codec_type ==
197 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 64, 0)
198             AVMEDIA_TYPE_AUDIO)
199 #else
200             CODEC_TYPE_AUDIO)
201 #endif
202         {
203             info->codec = avcodec_find_decoder (info->ctx->codec_id);
204             if (info->codec != NULL) {
205                 info->stream_id = i;
206                 break;
207             }
208         }
209     }
210 
211     if (info->codec == NULL)
212     {
213         trace ("ffmpeg can't decode %s\n", deadbeef->pl_find_meta (it, ":URI"));
214         return -1;
215     }
216     trace ("ffmpeg can decode %s\n", deadbeef->pl_find_meta (it, ":URI"));
217     trace ("ffmpeg: codec=%s, stream=%d\n", info->codec->name, i);
218 
219     if (avcodec_open (info->ctx, info->codec) < 0) {
220         trace ("ffmpeg: avcodec_open failed\n");
221         return -1;
222     }
223 
224     deadbeef->pl_replace_meta (it, "!FILETYPE", info->codec->name);
225 
226     int bps = av_get_bits_per_sample_format (info->ctx->sample_fmt);
227     int samplerate = info->ctx->sample_rate;
228     float duration = info->fctx->duration / (float)AV_TIME_BASE;
229     trace ("ffmpeg: bits per sample is %d\n", bps);
230     trace ("ffmpeg: samplerate is %d\n", samplerate);
231     trace ("ffmpeg: duration is %lld/%fsec\n", info->fctx->duration, duration);
232 
233     int totalsamples = info->fctx->duration * samplerate / AV_TIME_BASE;
234     info->left_in_packet = 0;
235     info->left_in_buffer = 0;
236 
237     memset (&info->pkt, 0, sizeof (info->pkt));
238     info->have_packet = 0;
239 
240 #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(55, 28, 0)
241     info->frame = av_frame_alloc();
242 #elif LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53, 40, 0)
243     info->frame = avcodec_alloc_frame();
244 #endif
245 
246     // fill in mandatory plugin fields
247     _info->plugin = &plugin;
248     _info->readpos = 0;
249     _info->fmt.bps = bps;
250     _info->fmt.channels = info->ctx->channels;
251     _info->fmt.samplerate = samplerate;
252     if (info->ctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
253         _info->fmt.is_float = 1;
254     }
255 
256 
257     int64_t layout = info->ctx->channel_layout;
258     if (layout != 0, 0) {
259         _info->fmt.channelmask = layout;
260     }
261     else {
262         for (int i = 0; i < _info->fmt.channels; i++) {
263             _info->fmt.channelmask |= 1 << i;
264         }
265     }
266 
267     // subtrack info
268     info->currentsample = 0;
269     if (it->endsample > 0) {
270         info->startsample = it->startsample;
271         info->endsample = it->endsample;
272         plugin.seek_sample (_info, 0);
273     }
274     else {
275         info->startsample = 0;
276         info->endsample = totalsamples - 1;
277     }
278     return 0;
279 }
280 
281 static void
282 ffmpeg_free (DB_fileinfo_t *_info) {
283     trace ("ffmpeg: free\n");
284     ffmpeg_info_t *info = (ffmpeg_info_t*)_info;
285     if (info) {
286 #if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(55, 28, 0)
287         if (info->frame) {
288             av_frame_free(&info->frame);
289         }
290 #elif LIBAVCODEC_VERSION_INT > AV_VERSION_INT(54, 59, 100)
291         if (info->frame) {
292             avcodec_free_frame(&info->frame);
293         }
294 #elif LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53, 40, 0)
295         if (info->frame) {
296             av_freep (&info->frame);
297         }
298 #endif
299         if (info->buffer) {
300             free (info->buffer);
301         }
302         // free everything allocated in _init and _read
303         if (info->have_packet) {
304             av_free_packet (&info->pkt);
305         }
306         if (info->ctx) {
307             avcodec_close (info->ctx);
308         }
309         if (info->fctx) {
310             av_close_input_file (info->fctx);
311         }
312         free (info);
313     }
314 }
315 
316 static int
317 ffmpeg_read (DB_fileinfo_t *_info, char *bytes, int size) {
318     trace ("ffmpeg_read_int16 %d\n", size);
319     ffmpeg_info_t *info = (ffmpeg_info_t*)_info;
320 
321     _info->fmt.channels = info->ctx->channels;
322     _info->fmt.samplerate = info->ctx->sample_rate;
323     _info->fmt.bps = av_get_bits_per_sample_format (info->ctx->sample_fmt);
324     _info->fmt.is_float = (info->ctx->sample_fmt == AV_SAMPLE_FMT_FLT);
325 
326     int samplesize = _info->fmt.channels * _info->fmt.bps / 8;
327 
328     if (info->endsample >= 0 && info->currentsample + size / samplesize > info->endsample) {
329         size = (info->endsample - info->currentsample + 1) * samplesize;
330         if (size <= 0) {
331             return 0;
332         }
333     }
334 
335     int initsize = size;
336 
337     int encsize = 0;
338     int decsize = 0;
339 
340     while (size > 0) {
341 
342         if (info->left_in_buffer > 0) {
343 //            int sz = min (size, info->left_in_buffer);
344             int nsamples = size / samplesize;
345             int nsamples_buf = info->left_in_buffer / samplesize;
346             nsamples = min (nsamples, nsamples_buf);
347             int sz = nsamples * samplesize;
348             memcpy (bytes, info->buffer, nsamples*samplesize);
349             bytes += nsamples * samplesize;
350             size -= nsamples * samplesize;
351             if (sz != info->left_in_buffer) {
352                 memmove (info->buffer, info->buffer+sz, info->left_in_buffer-sz);
353             }
354             info->left_in_buffer -= sz;
355         }
356 
357         while (info->left_in_packet > 0 && size > 0) {
358             int out_size = info->buffer_size;
359             int len;
360             //trace ("in: out_size=%d(%d), size=%d\n", out_size, AVCODEC_MAX_AUDIO_FRAME_SIZE, size);
361 
362 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53, 40, 0)
363             int got_frame = 0;
364             len = avcodec_decode_audio4(info->ctx, info->frame, &got_frame, &info->pkt);
365             if (len > 0) {
366                 if (ensure_buffer (info, info->frame->nb_samples * (_info->fmt.bps >> 3))) {
367                     return -1;
368                 }
369                 if (av_sample_fmt_is_planar(info->ctx->sample_fmt)) {
370                     out_size = 0;
371                     for (int c = 0; c < info->ctx->channels; c++) {
372                         for (int i = 0; i < info->frame->nb_samples; i++) {
373                             if (_info->fmt.bps == 8) {
374                                 info->buffer[i*info->ctx->channels+c] = ((int8_t *)info->frame->extended_data[c])[i];
375                                 out_size++;
376                             }
377                             else if (_info->fmt.bps == 16) {
378                                 int16_t outsample = ((int16_t *)info->frame->extended_data[c])[i];
379                                 ((int16_t*)info->buffer)[i*info->ctx->channels+c] = outsample;
380                                 out_size += 2;
381                             }
382                             else if (_info->fmt.bps == 24) {
383                                 memcpy (&info->buffer[(i*info->ctx->channels+c)*3], &((int8_t*)info->frame->extended_data[c])[i*3], 3);
384                                 out_size += 3;
385                             }
386                             else if (_info->fmt.bps == 32) {
387                                 int32_t sample = ((int32_t *)info->frame->extended_data[c])[i];
388                                 ((int32_t*)info->buffer)[i*info->ctx->channels+c] = sample;
389                                 out_size += 4;
390                             }
391                         }
392                     }
393                 }
394                 else {
395                     out_size = info->frame->nb_samples * (_info->fmt.bps >> 3) * _info->fmt.channels;
396                     memcpy (info->buffer, info->frame->extended_data[0], out_size);
397                 }
398             }
399 
400 #else
401             if (ensure_buffer (info, 16384)) { // FIXME: how to get the packet size in old ffmpeg?
402                 return -1;
403             }
404 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52,25,0)
405             len = avcodec_decode_audio3 (info->ctx, (int16_t *)info->buffer, &out_size, &info->pkt);
406 #else
407             len = avcodec_decode_audio2 (info->ctx, (int16_t *)info->buffer, &out_size, info->pkt.data, info->pkt.size);
408 #endif
409 #endif
410             trace ("out: out_size=%d, len=%d\n", out_size, len);
411             if (len <= 0) {
412                 break;
413             }
414             encsize += len;
415             decsize += out_size;
416             info->left_in_packet -= len;
417             info->left_in_buffer = out_size;
418         }
419         if (size == 0) {
420             break;
421         }
422 
423         // read next packet
424         if (info->have_packet) {
425             av_free_packet (&info->pkt);
426             info->have_packet = 0;
427         }
428         int errcount = 0;
429         for (;;) {
430             int ret;
431             if ((ret = av_read_frame (info->fctx, &info->pkt)) < 0) {
432                 trace ("ffmpeg: error %d\n", ret);
433                 if (ret == AVERROR_EOF || ret == -1) {
434                     ret = -1;
435                     break;
436                 }
437                 else {
438                     if (++errcount > 4) {
439                         trace ("ffmpeg: too many errors in a row (last is %d); interrupting stream\n", ret);
440                         ret = -1;
441                         break;
442                     }
443                     else {
444                         continue;
445                     }
446                 }
447             }
448             else {
449                 trace ("av packet size: %d, numframes: %d\n", info->pkt.size, ret);
450                 errcount = 0;
451             }
452             if (ret == -1) {
453                 break;
454             }
455             //trace ("idx:%d, stream:%d\n", info->pkt.stream_index, info->stream_id);
456             if (info->pkt.stream_index != info->stream_id) {
457                 av_free_packet (&info->pkt);
458                 continue;
459             }
460             //trace ("got packet: size=%d\n", info->pkt.size);
461             info->have_packet = 1;
462             info->left_in_packet = info->pkt.size;
463 
464             if (info->pkt.duration > 0) {
465                 AVRational *time_base = &info->fctx->streams[info->stream_id]->time_base;
466                 float sec = (float)info->pkt.duration * time_base->num / time_base->den;
467                 int bitrate = info->pkt.size * 8 / sec;
468                 if (bitrate > 0) {
469                     deadbeef->streamer_set_bitrate (bitrate / 1000);
470                 }
471             }
472 
473             break;
474         }
475         if (!info->have_packet) {
476             break;
477         }
478     }
479 
480     info->currentsample += (initsize-size) / samplesize;
481     _info->readpos = (float)info->currentsample / _info->fmt.samplerate;
482 
483     return initsize-size;
484 }
485 
486 static int
487 ffmpeg_seek_sample (DB_fileinfo_t *_info, int sample) {
488     ffmpeg_info_t *info = (ffmpeg_info_t*)_info;
489     // seek to specified sample (frame)
490     // return 0 on success
491     // return -1 on failure
492     if (info->have_packet) {
493         av_free_packet (&info->pkt);
494         info->have_packet = 0;
495     }
496     sample += info->startsample;
497     int64_t tm = (int64_t)sample/ _info->fmt.samplerate * AV_TIME_BASE;
498     trace ("ffmpeg: seek to sample: %d, t: %d\n", sample, (int)tm);
499     info->left_in_packet = 0;
500     info->left_in_buffer = 0;
501     if (av_seek_frame (info->fctx, -1, tm, AVSEEK_FLAG_ANY) < 0) {
502         trace ("ffmpeg: seek error\n");
503         return -1;
504     }
505 
506     // update readpos
507     info->currentsample = sample;
508     _info->readpos = (float)(sample - info->startsample) / _info->fmt.samplerate;
509     return 0;
510 }
511 
512 static int
513 ffmpeg_seek (DB_fileinfo_t *_info, float time) {
514     ffmpeg_info_t *info = (ffmpeg_info_t*)_info;
515     // seek to specified time in seconds
516     // return 0 on success
517     // return -1 on failure
518     return ffmpeg_seek_sample (_info, time * _info->fmt.samplerate);
519 }
520 
521 static const char *map[] = {
522     "artist", "artist",
523     "title", "title",
524     "album", "album",
525     "track", "track",
526     "tracktotal", "numtracks",
527     "date", "year",
528     "WM/Year", "year",
529     "genre", "genre",
530     "comment", "comment",
531     "performer", "performer",
532     "album_artist", "band",
533     "composer", "composer",
534     "encoder", "encoder",
535     "encoded_by", "vendor",
536     "disc", "disc",
537     "disctotal", "numdiscs",
538     "copyright", "copyright",
539     "publisher", "publisher",
540     "originaldate","original_release_time",
541     "originalyear","original_release_year",
542     "WM/OriginalReleaseTime","original_release_time",
543     "WM/OriginalReleaseYear","original_release_year",
544     NULL
545 };
546 
547 static int
548 ff_add_disc_meta (DB_playItem_t *it, const char *disc) {
549     char *slash = strchr (disc, '/');
550     if (slash) {
551         // split into disc/number
552         *slash = 0;
553         slash++;
554         deadbeef->pl_add_meta (it, "numdiscs", slash);
555     }
556     deadbeef->pl_add_meta (it, "disc", disc);
557     return 0;
558 }
559 
560 static int
561 ff_add_track_meta (DB_playItem_t *it, const char *track) {
562     char *slash = strchr (track, '/');
563     if (slash) {
564         // split into track/number
565         *slash = 0;
566         slash++;
567         deadbeef->pl_add_meta (it, "numtracks", slash);
568     }
569     deadbeef->pl_add_meta (it, "track", track);
570     return 0;
571 }
572 
573 static int
574 ffmpeg_read_metadata_internal (DB_playItem_t *it, AVFormatContext *fctx) {
575 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(52,43,0)
576     if (!strlen (fctx->title)) {
577         // title is empty, this call will set track title to filename without extension
578         deadbeef->pl_add_meta (it, "title", NULL);
579     }
580     else {
581         deadbeef->pl_add_meta (it, "title", fctx->title);
582     }
583     deadbeef->pl_add_meta (it, "artist", fctx->author);
584     deadbeef->pl_add_meta (it, "album", fctx->album);
585     deadbeef->pl_add_meta (it, "copyright", fctx->copyright);
586     deadbeef->pl_add_meta (it, "comment", fctx->comment);
587     deadbeef->pl_add_meta (it, "genre", fctx->genre);
588 
589     char tmp[10];
590     snprintf (tmp, sizeof (tmp), "%d", fctx->year);
591     deadbeef->pl_add_meta (it, "year", tmp);
592     snprintf (tmp, sizeof (tmp), "%d", fctx->track);
593     deadbeef->pl_add_meta (it, "track", tmp);
594 #else
595 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(54,23,0)
596     AVMetadata *md = fctx->metadata;
597 
598     for (int m = 0; map[m]; m += 2) {
599         AVMetadataTag *tag = NULL;
600         do {
601             tag = av_metadata_get (md, map[m], tag, AV_METADATA_DONT_STRDUP_KEY | AV_METADATA_DONT_STRDUP_VAL);
602             if (tag) {
603                 if (!strcmp (map[m+1], "disc")) {
604                     ff_add_disc_meta (it, tag->value);
605                 }
606                 else if (!strcmp (map[m+1], "track")) {
607                     ff_add_track_meta (it, tag->value);
608                 }
609                 else {
610                     deadbeef->pl_append_meta (it, map[m+1], tag->value);
611                 }
612             }
613 
614         } while (tag);
615     }
616 #else
617     // ffmpeg-0.11 new metadata format
618     AVDictionaryEntry *t = NULL;
619     int m;
620     for (int i = 0; i < fctx->nb_streams + 1; i++) {
621         AVDictionary *md = i == 0 ? fctx->metadata : fctx->streams[i-1]->metadata;
622         if (!md) {
623             continue;
624         }
625         while (t = av_dict_get (md, "", t, AV_DICT_IGNORE_SUFFIX)) {
626             if (!strcasecmp (t->key, "replaygain_album_gain")) {
627                 deadbeef->pl_set_item_replaygain (it, DDB_REPLAYGAIN_ALBUMGAIN, atof (t->value));
628                 continue;
629             }
630             else if (!strcasecmp (t->key, "replaygain_album_peak")) {
631                 deadbeef->pl_set_item_replaygain (it, DDB_REPLAYGAIN_ALBUMPEAK, atof (t->value));
632                 continue;
633             }
634             else if (!strcasecmp (t->key, "replaygain_track_gain")) {
635                 deadbeef->pl_set_item_replaygain (it, DDB_REPLAYGAIN_TRACKGAIN, atof (t->value));
636                 continue;
637             }
638             else if (!strcasecmp (t->key, "replaygain_track_peak")) {
639                 deadbeef->pl_set_item_replaygain (it, DDB_REPLAYGAIN_TRACKPEAK, atof (t->value));
640                 continue;
641             }
642 
643             for (m = 0; map[m]; m += 2) {
644                 if (!strcasecmp (t->key, map[m])) {
645                     if (!strcmp (map[m+1], "disc")) {
646                         ff_add_disc_meta (it, t->value);
647                     }
648                     else if (!strcmp (map[m+1], "track")) {
649                         ff_add_track_meta (it, t->value);
650                     }
651                     else {
652                         deadbeef->pl_append_meta (it, map[m+1], t->value);
653                     }
654                     break;
655                 }
656             }
657             if (!map[m]) {
658                 deadbeef->pl_append_meta (it, t->key, t->value);
659             }
660         }
661     }
662 #endif
663 #endif
664     return 0;
665 }
666 
667 static void
668 print_error(const char *filename, int err)
669 {
670     char errbuf[128];
671     const char *errbuf_ptr = errbuf;
672 
673     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
674         errbuf_ptr = strerror(AVUNERROR(err));
675     fprintf (stderr, "%s: %s\n", filename, errbuf_ptr);
676 }
677 
678 
679 static DB_playItem_t *
680 ffmpeg_insert (ddb_playlist_t *plt, DB_playItem_t *after, const char *fname) {
681     trace ("ffmpeg_insert %s\n", fname);
682     // read information from the track
683     // load/process cuesheet if exists
684     // insert track into playlist
685     // return track pointer on success
686     // return NULL on failure
687 
688     AVCodec *codec = NULL;
689     AVCodecContext *ctx = NULL;
690     AVFormatContext *fctx = NULL;
691     int ret;
692     int l = strlen (fname);
693     char *uri = NULL;
694     int i;
695 
696     // construct uri
697 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(54, 6, 0)
698     uri = strdupa (fname);
699 #else
700     uri = alloca (l + sizeof (FF_PROTOCOL_NAME) + 1);
701     memcpy (uri, FF_PROTOCOL_NAME, sizeof (FF_PROTOCOL_NAME)-1);
702     memcpy (uri + sizeof (FF_PROTOCOL_NAME)-1, ":", 1);
703     memcpy (uri + sizeof (FF_PROTOCOL_NAME), fname, l);
704     uri[sizeof (FF_PROTOCOL_NAME) + l] = 0;
705 #endif
706     trace ("ffmpeg: uri: %s\n", uri);
707 
708     // open file
709 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(54, 6, 0)
710     avformat_network_init();
711     fctx = avformat_alloc_context ();
712     if ((ret = avformat_open_input(&fctx, uri, NULL, NULL)) < 0) {
713 #else
714     if ((ret = av_open_input_file(&fctx, uri, NULL, 0, NULL)) < 0) {
715 #endif
716         print_error (uri, ret);
717         return NULL;
718     }
719 
720     trace ("fctx is %p, ret %d/%s\n", fctx, ret, strerror(-ret));
721     fctx->max_analyze_duration = FFMPEG_MAX_ANALYZE_DURATION;
722 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(54, 6, 0)
723     int nb_streams = fctx->nb_streams;
724     ret = avformat_find_stream_info(fctx, NULL);
725 #else
726     ret = av_find_stream_info(fctx);
727     int nb_streams = fctx->nb_streams;
728 #endif
729     if (ret < 0) {
730         trace ("av_find_stream_info ret: %d/%s\n", ret, strerror(-ret));
731     }
732     trace ("nb_streams=%x\n", nb_streams);
733     for (i = 0; i < fctx->nb_streams; i++)
734     {
735         if (!fctx->streams[i]) {
736             continue;
737         }
738         ctx = fctx->streams[i]->codec;
739         if (ctx->codec_type ==
740 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 64, 0)
741             AVMEDIA_TYPE_AUDIO)
742 #else
743             CODEC_TYPE_AUDIO)
744 #endif
745         {
746             codec = avcodec_find_decoder(ctx->codec_id);
747             if (codec != NULL) {
748                 break;
749             }
750         }
751     }
752 //    AVStream *stream = fctx->streams[i];
753 
754     if (codec == NULL)
755     {
756         trace ("ffmpeg can't decode %s\n", fname);
757         av_close_input_file(fctx);
758         return NULL;
759     }
760     trace ("ffmpeg can decode %s\n", fname);
761     trace ("ffmpeg: codec=%s, stream=%d\n", codec->name, i);
762 
763     if (avcodec_open (ctx, codec) < 0) {
764         trace ("ffmpeg: avcodec_open failed\n");
765         av_close_input_file(fctx);
766         return NULL;
767     }
768 
769     int bps = av_get_bits_per_sample_format (ctx->sample_fmt);
770     int samplerate = ctx->sample_rate;
771     float duration = fctx->duration / (float)AV_TIME_BASE;
772 //    float duration = stream->duration * stream->time_base.num / (float)stream->time_base.den;
773     trace ("ffmpeg: bits per sample is %d\n", bps);
774     trace ("ffmpeg: samplerate is %d\n", samplerate);
775     trace ("ffmpeg: duration is %f\n", duration);
776 
777     int totalsamples = fctx->duration * samplerate / AV_TIME_BASE;
778 
779     DB_playItem_t *it = deadbeef->pl_item_alloc_init (fname, plugin.plugin.id);
780     deadbeef->pl_replace_meta (it, ":FILETYPE", codec->name);
781 
782     if (!deadbeef->is_local_file (fname)) {
783         deadbeef->plt_set_item_duration (plt, it, -1);
784     }
785     else {
786         deadbeef->plt_set_item_duration (plt, it, duration);
787     }
788 
789     // add metainfo
790     ffmpeg_read_metadata_internal (it, fctx);
791 
792     int64_t fsize = -1;
793 
794     DB_FILE *fp = deadbeef->fopen (fname);
795     if (fp) {
796         if (!fp->vfs->is_streaming ()) {
797             fsize = deadbeef->fgetlength (fp);
798         }
799         deadbeef->fclose (fp);
800     }
801 
802     if (fsize >= 0 && duration > 0) {
803         char s[100];
804         snprintf (s, sizeof (s), "%lld", fsize);
805         deadbeef->pl_add_meta (it, ":FILE_SIZE", s);
806         snprintf (s, sizeof (s), "%d", av_get_bits_per_sample_format (ctx->sample_fmt));
807         deadbeef->pl_add_meta (it, ":BPS", s);
808         snprintf (s, sizeof (s), "%d", ctx->channels);
809         deadbeef->pl_add_meta (it, ":CHANNELS", s);
810         snprintf (s, sizeof (s), "%d", samplerate);
811         deadbeef->pl_add_meta (it, ":SAMPLERATE", s);
812         int br = (int)roundf(fsize / duration * 8 / 1000);
813         snprintf (s, sizeof (s), "%d", br);
814         deadbeef->pl_add_meta (it, ":BITRATE", s);
815     }
816 
817     // free decoder
818     avcodec_close (ctx);
819     av_close_input_file(fctx);
820 
821     // external cuesheet
822     DB_playItem_t *cue = deadbeef->plt_insert_cue (plt, after, it, totalsamples, samplerate);
823     if (cue) {
824         deadbeef->pl_item_unref (it);
825         deadbeef->pl_item_unref (cue);
826         return cue;
827     }
828     // now the track is ready, insert into playlist
829     after = deadbeef->plt_insert_item (plt, after, it);
830     deadbeef->pl_item_unref (it);
831     return after;
832 }
833 
834 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(54, 6, 0)
835 // vfs wrapper for ffmpeg, can't only be done with ffmpeg<0.11
836 static int
837 ffmpeg_vfs_open(URLContext *h, const char *filename, int flags)
838 {
839     DB_FILE *f;
840     av_strstart(filename, FF_PROTOCOL_NAME ":", &filename);
841 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(54, 6, 0)
842     if (flags & URL_WRONLY) {
843         return -ENOENT;
844     }
845     else
846 #endif
847     {
848         f = deadbeef->fopen (filename);
849     }
850 
851     if (f == NULL)
852         return -ENOENT;
853 
854     if (f->vfs->is_streaming ()) {
855         deadbeef->fset_track (f, current_track);
856         if (current_info) {
857             current_info->file = f;
858         }
859     }
860 
861     h->priv_data = f;
862     return 0;
863 }
864 
865 static int
866 ffmpeg_vfs_read(URLContext *h, unsigned char *buf, int size)
867 {
868     trace ("ffmpeg_vfs_read %d\n", size);
869     int res = deadbeef->fread (buf, 1, size, h->priv_data);
870     return res;
871 }
872 
873 static int
874 ffmpeg_vfs_write(URLContext *h, const unsigned char *buf, int size)
875 {
876     return -1;
877 }
878 
879 static int64_t
880 ffmpeg_vfs_seek(URLContext *h, int64_t pos, int whence)
881 {
882     trace ("ffmpeg_vfs_seek %lld %d\n", pos, whence);
883     DB_FILE *f = h->priv_data;
884 
885     if (whence == AVSEEK_SIZE) {
886         return f->vfs->is_streaming () ? -1 : deadbeef->fgetlength (h->priv_data);
887     }
888     else if (f->vfs->is_streaming ()) {
889         return -1;
890     }
891     else {
892         int ret = deadbeef->fseek (h->priv_data, pos, whence);
893         return ret;
894     }
895 }
896 
897 static int
898 ffmpeg_vfs_close(URLContext *h)
899 {
900     trace ("ffmpeg_vfs_close\n");
901     deadbeef->fclose (h->priv_data);
902     return 0;
903 }
904 
905 static URLProtocol vfswrapper = {
906     .name = FF_PROTOCOL_NAME,
907     .url_open = ffmpeg_vfs_open,
908     .url_read = ffmpeg_vfs_read,
909     .url_write = ffmpeg_vfs_write,
910     .url_seek = ffmpeg_vfs_seek,
911     .url_close = ffmpeg_vfs_close,
912 };
913 #endif
914 
915 static int
916 assign_new_ext (int n, const char* new_ext, size_t size) {
917     char* ext = malloc (size + 1);
918     strncpy (ext, new_ext, size);
919     for (int i = 0; i < n; i++) {
920         if (strcmp (exts[i], ext) == 0) {
921             free(ext);
922             return n;
923         }
924     }
925     ext[size] = '\0';
926     free (exts[n]);
927     exts[n] = ext;
928     return n + 1;
929 }
930 
931 static int
932 add_new_exts (int n, const char* new_exts, char delim) {
933     while (*new_exts) {
934         if (n >= EXT_MAX) {
935             fprintf (stderr, "ffmpeg: too many extensions, max is %d\n", EXT_MAX);
936             break;
937         }
938         const char *e = new_exts;
939         while (*e && (*e != delim || *e == ' ')) {
940             e++;
941         }
942         if (e != new_exts) {
943             n = assign_new_ext (n, new_exts, e-new_exts);
944         }
945         if (*e == 0) {
946             break;
947         }
948         new_exts = e+1;
949     }
950     return n;
951 }
952 
953 static void
954 ffmpeg_init_exts (void) {
955     deadbeef->conf_lock ();
956     const char *new_exts = deadbeef->conf_get_str_fast ("ffmpeg.extensions", DEFAULT_EXTS);
957     int use_all_ext = deadbeef->conf_get_int ("ffmpeg.enable_all_exts", 0);
958     for (int i = 0; exts[i]; i++) {
959         free (exts[i]);
960         exts[i] = NULL;
961     }
962     exts[0] = NULL;
963 
964     int n = 0;
965     if (!use_all_ext) {
966         n = add_new_exts (n, new_exts, ';');
967     }
968 	else {
969         AVInputFormat *ifmt  = NULL;
970         /*
971           * It's quite complicated to enumerate all supported extensions in
972          * ffmpeg. If a decoder defines extensions in ffmpeg, the probing
973          * mechanisim is disabled (see comments in avformat.h).
974          * Thus some decoders doesn't claim its extensions (e.g. WavPack)
975          *
976          * To get these missing extensions, we need to search corresponding
977          * encoders for the same format, which will provide extensions for
978          * encoding purpose, because ffmpeg will guess the output format from
979          * the file name specified by users.
980          */
981         while (ifmt = av_iformat_next(ifmt)) {
982 #ifdef AV_IS_INPUT_DEVICE
983             if (ifmt->priv_class && AV_IS_INPUT_DEVICE(ifmt->priv_class->category))
984                 continue; // Skip all input devices
985 #endif
986 
987             if (ifmt->flags & AVFMT_NOFILE)
988                 continue; // Skip format that's not even a file
989 
990 #ifdef AV_CODEC_ID_FIRST_AUDIO
991             if (ifmt->raw_codec_id > 0 &&
992                     (ifmt->raw_codec_id < AV_CODEC_ID_FIRST_AUDIO || ifmt->raw_codec_id > AV_CODEC_ID_FIRST_SUBTITLE)
993                )
994                 continue; // Skip all non-audio raw formats
995 #endif
996             if (ifmt->long_name && strstr(ifmt->long_name, "subtitle"))
997                 continue; // Skip all subtitle formats
998             if (ifmt->extensions)
999                 n = add_new_exts (n, ifmt->extensions, ',');
1000         }
1001         /*
1002           * The above code doesn't guarntee all extensions are
1003          * included, however. In the portable build the encoders are disabled,
1004          * thus some extensions cannot be retrived.
1005          *
1006          * To fix this, we need to add some known extensions in addition to
1007          * scanned extensions.
1008          */
1009         n = add_new_exts (n, UNPOPULATED_EXTS_BY_FFMPEG, ',');
1010     }
1011     exts[n] = NULL;
1012     deadbeef->conf_unlock ();
1013 }
1014 
1015 static int
1016 ffmpeg_message (uint32_t id, uintptr_t ctx, uint32_t p1, uint32_t p2) {
1017     switch (id) {
1018     case DB_EV_CONFIGCHANGED:
1019         ffmpeg_init_exts ();
1020         break;
1021     }
1022     return 0;
1023 }
1024 
1025 static int
1026 ffmpeg_start (void) {
1027     ffmpeg_init_exts ();
1028 #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(54, 6, 0)
1029     avcodec_register_all ();
1030 #endif
1031     av_register_all ();
1032 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(54, 6, 0)
1033 #warning FFMPEG-0.11 and higher does not expose register_protocol API, which means that it cant work with MMS and HTTP plugins. If you need this functionality, please downgrade FFMPEG to version 0.10 or less, and rebuild the FFMPEG plugin
1034 #elif LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(52, 69, 0)
1035     av_register_protocol2 (&vfswrapper, sizeof(vfswrapper));
1036 #else
1037     av_register_protocol (&vfswrapper);
1038 #endif
1039     return 0;
1040 }
1041 
1042 static int
1043 ffmpeg_stop (void) {
1044     for (int i = 0; exts[i]; i++) {
1045         free (exts[i]);
1046     }
1047     exts[0] = NULL;
1048     return 0;
1049 }
1050 
1051 int
1052 ffmpeg_read_metadata (DB_playItem_t *it) {
1053     trace ("ffmpeg_read_metadata: fname %s\n", deadbeef->pl_find_meta (it, ":URI"));
1054     AVCodec *codec = NULL;
1055     AVCodecContext *ctx = NULL;
1056     AVFormatContext *fctx = NULL;
1057     int ret;
1058     char *uri = NULL;
1059     int i;
1060 
1061     deadbeef->pl_lock ();
1062     {
1063         const char *fname = deadbeef->pl_find_meta (it, ":URI");
1064 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(54, 6, 0)
1065         uri = strdupa (fname);
1066 #else
1067         int l = strlen (fname);
1068         uri = alloca (l + sizeof (FF_PROTOCOL_NAME) + 1);
1069 
1070         // construct uri
1071         memcpy (uri, FF_PROTOCOL_NAME, sizeof (FF_PROTOCOL_NAME)-1);
1072         memcpy (uri + sizeof (FF_PROTOCOL_NAME)-1, ":", 1);
1073         memcpy (uri + sizeof (FF_PROTOCOL_NAME), fname, l);
1074         uri[sizeof (FF_PROTOCOL_NAME) + l] = 0;
1075 #endif
1076     }
1077     deadbeef->pl_unlock ();
1078     trace ("ffmpeg: uri: %s\n", uri);
1079 
1080     // open file
1081 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(54, 6, 0)
1082     avformat_network_init();
1083     fctx = avformat_alloc_context ();
1084     if ((ret = avformat_open_input(&fctx, uri, NULL, NULL)) < 0) {
1085 #else
1086     if ((ret = av_open_input_file(&fctx, uri, NULL, 0, NULL)) < 0) {
1087 #endif
1088         trace ("fctx is %p, ret %d/%s", fctx, ret, strerror(-ret));
1089         return -1;
1090     }
1091 
1092     av_find_stream_info(fctx);
1093     for (i = 0; i < fctx->nb_streams; i++)
1094     {
1095         ctx = fctx->streams[i]->codec;
1096         if (ctx->codec_type ==
1097 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 64, 0)
1098             AVMEDIA_TYPE_AUDIO)
1099 #else
1100             CODEC_TYPE_AUDIO)
1101 #endif
1102         {
1103             codec = avcodec_find_decoder(ctx->codec_id);
1104             if (codec != NULL)
1105                 break;
1106         }
1107     }
1108     if (codec == NULL)
1109     {
1110         trace ("ffmpeg can't decode %s\n", deadbeef->pl_find_meta (it, ":URI"));
1111         av_close_input_file(fctx);
1112         return -1;
1113     }
1114     if (avcodec_open (ctx, codec) < 0) {
1115         trace ("ffmpeg: avcodec_open failed\n");
1116         av_close_input_file(fctx);
1117         return -1;
1118     }
1119 
1120     deadbeef->pl_delete_all_meta (it);
1121     ffmpeg_read_metadata_internal (it, fctx);
1122 
1123     av_close_input_file(fctx);
1124     return 0;
1125 }
1126 
1127 static const char settings_dlg[] =
1128     "property \"Use all extensions supported by ffmpeg\" checkbox ffmpeg.enable_all_exts 0;\n"
1129     "property \"File Extensions (separate with ';')\" entry ffmpeg.extensions \"" DEFAULT_EXTS "\";\n"
1130 ;
1131 
1132 // define plugin interface
1133 static DB_decoder_t plugin = {
1134     .plugin.api_vmajor = 1,
1135     .plugin.api_vminor = 0,
1136     .plugin.version_major = 1,
1137     .plugin.version_minor = 2,
1138     .plugin.type = DB_PLUGIN_DECODER,
1139     .plugin.id = "ffmpeg",
1140     .plugin.name = "FFMPEG audio player",
1141     .plugin.descr = "decodes audio formats using FFMPEG libavcodec",
1142     .plugin.copyright =
1143         "Copyright (C) 2009-2013 Alexey Yakovenko <waker@users.sourceforge.net>\n"
1144         "\n"
1145         "This program is free software; you can redistribute it and/or\n"
1146         "modify it under the terms of the GNU General Public License\n"
1147         "as published by the Free Software Foundation; either version 2\n"
1148         "of the License, or (at your option) any later version.\n"
1149         "\n"
1150         "This program is distributed in the hope that it will be useful,\n"
1151         "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1152         "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1153         "GNU General Public License for more details.\n"
1154         "\n"
1155         "You should have received a copy of the GNU General Public License\n"
1156         "along with this program; if not, write to the Free Software\n"
1157         "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n"
1158     ,
1159     .plugin.website = "http://deadbeef.sf.net",
1160     .plugin.start = ffmpeg_start,
1161     .plugin.stop = ffmpeg_stop,
1162     .plugin.configdialog = settings_dlg,
1163     .plugin.message = ffmpeg_message,
1164     .open = ffmpeg_open,
1165     .init = ffmpeg_init,
1166     .free = ffmpeg_free,
1167     .read = ffmpeg_read,
1168     .seek = ffmpeg_seek,
1169     .seek_sample = ffmpeg_seek_sample,
1170     .insert = ffmpeg_insert,
1171     .read_metadata = ffmpeg_read_metadata,
1172     .exts = (const char **)exts,
1173 };
1174 
1175 DB_plugin_t *
1176 ffmpeg_load (DB_functions_t *api) {
1177     deadbeef = api;
1178     return DB_PLUGIN (&plugin);
1179 }
1180 
1181