avaudenc/dec: Ignore S64BE/LE pseudo-codecs
[platform/upstream/gst-libav.git] / ext / libav / gstavauddec.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) <2012> Collabora Ltd.
4  *   Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <assert.h>
27 #include <string.h>
28
29 #include <libavcodec/avcodec.h>
30 #include <libavutil/channel_layout.h>
31
32 #include <gst/gst.h>
33
34 #include "gstav.h"
35 #include "gstavcodecmap.h"
36 #include "gstavutils.h"
37 #include "gstavauddec.h"
38
39 /* A number of function prototypes are given so we can refer to them later. */
40 static void gst_ffmpegauddec_base_init (GstFFMpegAudDecClass * klass);
41 static void gst_ffmpegauddec_class_init (GstFFMpegAudDecClass * klass);
42 static void gst_ffmpegauddec_init (GstFFMpegAudDec * ffmpegdec);
43 static void gst_ffmpegauddec_finalize (GObject * object);
44 static gboolean gst_ffmpegauddec_propose_allocation (GstAudioDecoder * decoder,
45     GstQuery * query);
46
47 static gboolean gst_ffmpegauddec_start (GstAudioDecoder * decoder);
48 static gboolean gst_ffmpegauddec_stop (GstAudioDecoder * decoder);
49 static void gst_ffmpegauddec_flush (GstAudioDecoder * decoder, gboolean hard);
50 static gboolean gst_ffmpegauddec_set_format (GstAudioDecoder * decoder,
51     GstCaps * caps);
52 static GstFlowReturn gst_ffmpegauddec_handle_frame (GstAudioDecoder * decoder,
53     GstBuffer * inbuf);
54
55 static gboolean gst_ffmpegauddec_negotiate (GstFFMpegAudDec * ffmpegdec,
56     AVCodecContext * context, AVFrame * frame, gboolean force);
57
58 static void gst_ffmpegauddec_drain (GstFFMpegAudDec * ffmpegdec);
59
60 #define GST_FFDEC_PARAMS_QDATA g_quark_from_static_string("avdec-params")
61
62 static GstElementClass *parent_class = NULL;
63
64 static void
65 gst_ffmpegauddec_base_init (GstFFMpegAudDecClass * klass)
66 {
67   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
68   GstPadTemplate *sinktempl, *srctempl;
69   GstCaps *sinkcaps, *srccaps;
70   AVCodec *in_plugin;
71   gchar *longname, *description;
72
73   in_plugin =
74       (AVCodec *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (klass),
75       GST_FFDEC_PARAMS_QDATA);
76   g_assert (in_plugin != NULL);
77
78   /* construct the element details struct */
79   longname = g_strdup_printf ("libav %s decoder", in_plugin->long_name);
80   description = g_strdup_printf ("libav %s decoder", in_plugin->name);
81   gst_element_class_set_metadata (element_class, longname,
82       "Codec/Decoder/Audio", description,
83       "Wim Taymans <wim.taymans@gmail.com>, "
84       "Ronald Bultje <rbultje@ronald.bitfreak.net>, "
85       "Edward Hervey <bilboed@bilboed.com>");
86   g_free (longname);
87   g_free (description);
88
89   /* get the caps */
90   sinkcaps = gst_ffmpeg_codecid_to_caps (in_plugin->id, NULL, FALSE);
91   if (!sinkcaps) {
92     GST_DEBUG ("Couldn't get sink caps for decoder '%s'", in_plugin->name);
93     sinkcaps = gst_caps_from_string ("unknown/unknown");
94   }
95   srccaps = gst_ffmpeg_codectype_to_audio_caps (NULL,
96       in_plugin->id, FALSE, in_plugin);
97   if (!srccaps) {
98     GST_DEBUG ("Couldn't get source caps for decoder '%s'", in_plugin->name);
99     srccaps = gst_caps_from_string ("audio/x-raw");
100   }
101
102   /* pad templates */
103   sinktempl = gst_pad_template_new ("sink", GST_PAD_SINK,
104       GST_PAD_ALWAYS, sinkcaps);
105   srctempl = gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS, srccaps);
106
107   gst_element_class_add_pad_template (element_class, srctempl);
108   gst_element_class_add_pad_template (element_class, sinktempl);
109
110   klass->in_plugin = in_plugin;
111   klass->srctempl = srctempl;
112   klass->sinktempl = sinktempl;
113 }
114
115 static void
116 gst_ffmpegauddec_class_init (GstFFMpegAudDecClass * klass)
117 {
118   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
119   GstAudioDecoderClass *gstaudiodecoder_class = GST_AUDIO_DECODER_CLASS (klass);
120
121   parent_class = g_type_class_peek_parent (klass);
122
123   gobject_class->finalize = gst_ffmpegauddec_finalize;
124
125   gstaudiodecoder_class->start = GST_DEBUG_FUNCPTR (gst_ffmpegauddec_start);
126   gstaudiodecoder_class->stop = GST_DEBUG_FUNCPTR (gst_ffmpegauddec_stop);
127   gstaudiodecoder_class->set_format =
128       GST_DEBUG_FUNCPTR (gst_ffmpegauddec_set_format);
129   gstaudiodecoder_class->handle_frame =
130       GST_DEBUG_FUNCPTR (gst_ffmpegauddec_handle_frame);
131   gstaudiodecoder_class->flush = GST_DEBUG_FUNCPTR (gst_ffmpegauddec_flush);
132   gstaudiodecoder_class->propose_allocation =
133       GST_DEBUG_FUNCPTR (gst_ffmpegauddec_propose_allocation);
134 }
135
136 static void
137 gst_ffmpegauddec_init (GstFFMpegAudDec * ffmpegdec)
138 {
139   GstFFMpegAudDecClass *klass =
140       (GstFFMpegAudDecClass *) G_OBJECT_GET_CLASS (ffmpegdec);
141
142   /* some ffmpeg data */
143   ffmpegdec->context = avcodec_alloc_context3 (klass->in_plugin);
144   ffmpegdec->context->opaque = ffmpegdec;
145   ffmpegdec->opened = FALSE;
146
147   ffmpegdec->frame = av_frame_alloc ();
148
149   GST_PAD_SET_ACCEPT_TEMPLATE (GST_VIDEO_DECODER_SINK_PAD (ffmpegdec));
150   gst_audio_decoder_set_use_default_pad_acceptcaps (GST_AUDIO_DECODER_CAST
151       (ffmpegdec), TRUE);
152
153   gst_audio_decoder_set_drainable (GST_AUDIO_DECODER (ffmpegdec), TRUE);
154   gst_audio_decoder_set_needs_format (GST_AUDIO_DECODER (ffmpegdec), TRUE);
155 }
156
157 static void
158 gst_ffmpegauddec_finalize (GObject * object)
159 {
160   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) object;
161
162   av_frame_free (&ffmpegdec->frame);
163
164   if (ffmpegdec->context != NULL) {
165     gst_ffmpeg_avcodec_close (ffmpegdec->context);
166     av_free (ffmpegdec->context);
167     ffmpegdec->context = NULL;
168   }
169
170   G_OBJECT_CLASS (parent_class)->finalize (object);
171 }
172
173 /* With LOCK */
174 static gboolean
175 gst_ffmpegauddec_close (GstFFMpegAudDec * ffmpegdec, gboolean reset)
176 {
177   GstFFMpegAudDecClass *oclass;
178
179   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
180
181   GST_LOG_OBJECT (ffmpegdec, "closing libav codec");
182
183   gst_caps_replace (&ffmpegdec->last_caps, NULL);
184   gst_buffer_replace (&ffmpegdec->outbuf, NULL);
185
186   gst_ffmpeg_avcodec_close (ffmpegdec->context);
187   ffmpegdec->opened = FALSE;
188
189   if (ffmpegdec->context->extradata) {
190     av_free (ffmpegdec->context->extradata);
191     ffmpegdec->context->extradata = NULL;
192   }
193
194   if (reset) {
195     if (avcodec_get_context_defaults3 (ffmpegdec->context,
196             oclass->in_plugin) < 0) {
197       GST_DEBUG_OBJECT (ffmpegdec, "Failed to set context defaults");
198       return FALSE;
199     }
200     ffmpegdec->context->opaque = ffmpegdec;
201   }
202
203   return TRUE;
204 }
205
206 static gboolean
207 gst_ffmpegauddec_start (GstAudioDecoder * decoder)
208 {
209   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) decoder;
210   GstFFMpegAudDecClass *oclass;
211
212   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
213
214   GST_OBJECT_LOCK (ffmpegdec);
215   gst_ffmpeg_avcodec_close (ffmpegdec->context);
216   if (avcodec_get_context_defaults3 (ffmpegdec->context, oclass->in_plugin) < 0) {
217     GST_DEBUG_OBJECT (ffmpegdec, "Failed to set context defaults");
218     GST_OBJECT_UNLOCK (ffmpegdec);
219     return FALSE;
220   }
221   ffmpegdec->context->opaque = ffmpegdec;
222   GST_OBJECT_UNLOCK (ffmpegdec);
223
224   return TRUE;
225 }
226
227 static gboolean
228 gst_ffmpegauddec_stop (GstAudioDecoder * decoder)
229 {
230   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) decoder;
231
232   GST_OBJECT_LOCK (ffmpegdec);
233   gst_ffmpegauddec_close (ffmpegdec, FALSE);
234   g_free (ffmpegdec->padded);
235   ffmpegdec->padded = NULL;
236   ffmpegdec->padded_size = 0;
237   GST_OBJECT_UNLOCK (ffmpegdec);
238   gst_audio_info_init (&ffmpegdec->info);
239   gst_caps_replace (&ffmpegdec->last_caps, NULL);
240
241   return TRUE;
242 }
243
244 /* with LOCK */
245 static gboolean
246 gst_ffmpegauddec_open (GstFFMpegAudDec * ffmpegdec)
247 {
248   GstFFMpegAudDecClass *oclass;
249
250   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
251
252   if (gst_ffmpeg_avcodec_open (ffmpegdec->context, oclass->in_plugin) < 0)
253     goto could_not_open;
254
255   ffmpegdec->opened = TRUE;
256
257   GST_LOG_OBJECT (ffmpegdec, "Opened libav codec %s, id %d",
258       oclass->in_plugin->name, oclass->in_plugin->id);
259
260   gst_audio_info_init (&ffmpegdec->info);
261
262   return TRUE;
263
264   /* ERRORS */
265 could_not_open:
266   {
267     gst_ffmpegauddec_close (ffmpegdec, TRUE);
268     GST_DEBUG_OBJECT (ffmpegdec, "avdec_%s: Failed to open libav codec",
269         oclass->in_plugin->name);
270     return FALSE;
271   }
272 }
273
274 static gboolean
275 gst_ffmpegauddec_propose_allocation (GstAudioDecoder * decoder,
276     GstQuery * query)
277 {
278   GstAllocationParams params;
279
280   gst_allocation_params_init (&params);
281   params.flags = GST_MEMORY_FLAG_ZERO_PADDED;
282   params.align = 15;
283   params.padding = FF_INPUT_BUFFER_PADDING_SIZE;
284   /* we would like to have some padding so that we don't have to
285    * memcpy. We don't suggest an allocator. */
286   gst_query_add_allocation_param (query, NULL, &params);
287
288   return GST_AUDIO_DECODER_CLASS (parent_class)->propose_allocation (decoder,
289       query);
290 }
291
292 static gboolean
293 gst_ffmpegauddec_set_format (GstAudioDecoder * decoder, GstCaps * caps)
294 {
295   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) decoder;
296   GstFFMpegAudDecClass *oclass;
297   gboolean ret = TRUE;
298
299   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
300
301   GST_DEBUG_OBJECT (ffmpegdec, "setcaps called");
302
303   GST_OBJECT_LOCK (ffmpegdec);
304
305   if (ffmpegdec->last_caps && gst_caps_is_equal (ffmpegdec->last_caps, caps)) {
306     GST_DEBUG_OBJECT (ffmpegdec, "same caps");
307     GST_OBJECT_UNLOCK (ffmpegdec);
308     return TRUE;
309   }
310
311   gst_caps_replace (&ffmpegdec->last_caps, caps);
312
313   /* close old session */
314   if (ffmpegdec->opened) {
315     GST_OBJECT_UNLOCK (ffmpegdec);
316     gst_ffmpegauddec_drain (ffmpegdec);
317     GST_OBJECT_LOCK (ffmpegdec);
318     if (!gst_ffmpegauddec_close (ffmpegdec, TRUE)) {
319       GST_OBJECT_UNLOCK (ffmpegdec);
320       return FALSE;
321     }
322   }
323
324   /* get size and so */
325   gst_ffmpeg_caps_with_codecid (oclass->in_plugin->id,
326       oclass->in_plugin->type, caps, ffmpegdec->context);
327
328   /* workaround encoder bugs */
329   ffmpegdec->context->workaround_bugs |= FF_BUG_AUTODETECT;
330   ffmpegdec->context->err_recognition = 1;
331
332   /* open codec - we don't select an output pix_fmt yet,
333    * simply because we don't know! We only get it
334    * during playback... */
335   if (!gst_ffmpegauddec_open (ffmpegdec))
336     goto open_failed;
337
338 done:
339   GST_OBJECT_UNLOCK (ffmpegdec);
340
341   return ret;
342
343   /* ERRORS */
344 open_failed:
345   {
346     GST_DEBUG_OBJECT (ffmpegdec, "Failed to open");
347     ret = FALSE;
348     goto done;
349   }
350 }
351
352 static gboolean
353 settings_changed (GstFFMpegAudDec * ffmpegdec, AVFrame * frame)
354 {
355   GstAudioFormat format;
356   gint channels =
357       av_get_channel_layout_nb_channels (av_frame_get_channel_layout (frame));
358
359   format = gst_ffmpeg_smpfmt_to_audioformat (frame->format);
360   if (format == GST_AUDIO_FORMAT_UNKNOWN)
361     return TRUE;
362
363   return !(ffmpegdec->info.rate ==
364       av_frame_get_sample_rate (frame) &&
365       ffmpegdec->info.channels == channels &&
366       ffmpegdec->info.finfo->format == format);
367 }
368
369 static gboolean
370 gst_ffmpegauddec_negotiate (GstFFMpegAudDec * ffmpegdec,
371     AVCodecContext * context, AVFrame * frame, gboolean force)
372 {
373   GstFFMpegAudDecClass *oclass;
374   GstAudioFormat format;
375   gint channels;
376   GstAudioChannelPosition pos[64] = { 0, };
377
378   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
379
380   format = gst_ffmpeg_smpfmt_to_audioformat (frame->format);
381   if (format == GST_AUDIO_FORMAT_UNKNOWN)
382     goto no_caps;
383   channels =
384       av_get_channel_layout_nb_channels (av_frame_get_channel_layout (frame));
385   if (channels == 0)
386     channels = av_frame_get_channels (frame);
387   if (channels == 0)
388     goto no_caps;
389
390   if (!force && !settings_changed (ffmpegdec, frame))
391     return TRUE;
392
393   GST_DEBUG_OBJECT (ffmpegdec,
394       "Renegotiating audio from %dHz@%dchannels (%d) to %dHz@%dchannels (%d)",
395       ffmpegdec->info.rate, ffmpegdec->info.channels,
396       ffmpegdec->info.finfo->format, av_frame_get_sample_rate (frame), channels,
397       format);
398
399   gst_ffmpeg_channel_layout_to_gst (av_frame_get_channel_layout (frame),
400       channels, pos);
401   memcpy (ffmpegdec->ffmpeg_layout, pos,
402       sizeof (GstAudioChannelPosition) * channels);
403
404   /* Get GStreamer channel layout */
405   gst_audio_channel_positions_to_valid_order (pos, channels);
406   ffmpegdec->needs_reorder =
407       memcmp (pos, ffmpegdec->ffmpeg_layout, sizeof (pos[0]) * channels) != 0;
408   gst_audio_info_set_format (&ffmpegdec->info, format,
409       av_frame_get_sample_rate (frame), channels, pos);
410
411   if (!gst_audio_decoder_set_output_format (GST_AUDIO_DECODER (ffmpegdec),
412           &ffmpegdec->info))
413     goto caps_failed;
414
415   return TRUE;
416
417   /* ERRORS */
418 no_caps:
419   {
420 #ifdef HAVE_LIBAV_UNINSTALLED
421     /* using internal ffmpeg snapshot */
422     GST_ELEMENT_ERROR (ffmpegdec, CORE, NEGOTIATION,
423         ("Could not find GStreamer caps mapping for libav codec '%s'.",
424             oclass->in_plugin->name), (NULL));
425 #else
426     /* using external ffmpeg */
427     GST_ELEMENT_ERROR (ffmpegdec, CORE, NEGOTIATION,
428         ("Could not find GStreamer caps mapping for libav codec '%s', and "
429             "you are using an external libavcodec. This is most likely due to "
430             "a packaging problem and/or libavcodec having been upgraded to a "
431             "version that is not compatible with this version of "
432             "gstreamer-libav. Make sure your gstreamer-libav and libavcodec "
433             "packages come from the same source/repository.",
434             oclass->in_plugin->name), (NULL));
435 #endif
436     return FALSE;
437   }
438 caps_failed:
439   {
440     GST_ELEMENT_ERROR (ffmpegdec, CORE, NEGOTIATION, (NULL),
441         ("Could not set caps for libav decoder (%s), not fixed?",
442             oclass->in_plugin->name));
443     memset (&ffmpegdec->info, 0, sizeof (ffmpegdec->info));
444
445     return FALSE;
446   }
447 }
448
449 static void
450 gst_avpacket_init (AVPacket * packet, guint8 * data, guint size)
451 {
452   memset (packet, 0, sizeof (AVPacket));
453   packet->data = data;
454   packet->size = size;
455 }
456
457 static gint
458 gst_ffmpegauddec_audio_frame (GstFFMpegAudDec * ffmpegdec,
459     AVCodec * in_plugin, guint8 * data, guint size, gint * have_data,
460     GstBuffer ** outbuf, GstFlowReturn * ret)
461 {
462   gint len = -1;
463   AVPacket packet;
464
465   GST_DEBUG_OBJECT (ffmpegdec, "size: %d", size);
466
467   gst_avpacket_init (&packet, data, size);
468   len =
469       avcodec_decode_audio4 (ffmpegdec->context, ffmpegdec->frame, have_data,
470       &packet);
471
472   GST_DEBUG_OBJECT (ffmpegdec,
473       "Decode audio: len=%d, have_data=%d", len, *have_data);
474
475   if (len >= 0 && *have_data) {
476     gint nsamples, channels, byte_per_sample;
477     gsize output_size;
478
479     if (!gst_ffmpegauddec_negotiate (ffmpegdec, ffmpegdec->context,
480             ffmpegdec->frame, FALSE)) {
481       *outbuf = NULL;
482       *ret = GST_FLOW_NOT_NEGOTIATED;
483       len = -1;
484       goto beach;
485     }
486
487     channels = ffmpegdec->info.channels;
488     nsamples = ffmpegdec->frame->nb_samples;
489     byte_per_sample = ffmpegdec->info.finfo->width / 8;
490
491     /* ffmpegdec->frame->linesize[0] might contain padding, allocate only what's needed */
492     output_size = nsamples * byte_per_sample * channels;
493
494     GST_DEBUG_OBJECT (ffmpegdec, "Creating output buffer");
495     if (av_sample_fmt_is_planar (ffmpegdec->context->sample_fmt)
496         && channels > 1) {
497       gint i, j;
498       GstMapInfo minfo;
499
500       /* note: linesize[0] might contain padding, allocate only what's needed */
501       *outbuf =
502           gst_audio_decoder_allocate_output_buffer (GST_AUDIO_DECODER
503           (ffmpegdec), output_size);
504
505       gst_buffer_map (*outbuf, &minfo, GST_MAP_WRITE);
506
507       switch (ffmpegdec->info.finfo->width) {
508         case 8:{
509           guint8 *odata = minfo.data;
510
511           for (i = 0; i < nsamples; i++) {
512             for (j = 0; j < channels; j++) {
513               odata[j] =
514                   ((const guint8 *) ffmpegdec->frame->extended_data[j])[i];
515             }
516             odata += channels;
517           }
518           break;
519         }
520         case 16:{
521           guint16 *odata = (guint16 *) minfo.data;
522
523           for (i = 0; i < nsamples; i++) {
524             for (j = 0; j < channels; j++) {
525               odata[j] =
526                   ((const guint16 *) ffmpegdec->frame->extended_data[j])[i];
527             }
528             odata += channels;
529           }
530           break;
531         }
532         case 32:{
533           guint32 *odata = (guint32 *) minfo.data;
534
535           for (i = 0; i < nsamples; i++) {
536             for (j = 0; j < channels; j++) {
537               odata[j] =
538                   ((const guint32 *) ffmpegdec->frame->extended_data[j])[i];
539             }
540             odata += channels;
541           }
542           break;
543         }
544         case 64:{
545           guint64 *odata = (guint64 *) minfo.data;
546
547           for (i = 0; i < nsamples; i++) {
548             for (j = 0; j < channels; j++) {
549               odata[j] =
550                   ((const guint64 *) ffmpegdec->frame->extended_data[j])[i];
551             }
552             odata += channels;
553           }
554           break;
555         }
556         default:
557           g_assert_not_reached ();
558           break;
559       }
560       gst_buffer_unmap (*outbuf, &minfo);
561     } else {
562       *outbuf =
563           gst_audio_decoder_allocate_output_buffer (GST_AUDIO_DECODER
564           (ffmpegdec), output_size);
565       gst_buffer_fill (*outbuf, 0, ffmpegdec->frame->data[0], output_size);
566     }
567
568     GST_DEBUG_OBJECT (ffmpegdec, "Buffer created. Size: %" G_GSIZE_FORMAT,
569         output_size);
570
571     /* Reorder channels to the GStreamer channel order */
572     if (ffmpegdec->needs_reorder) {
573       *outbuf = gst_buffer_make_writable (*outbuf);
574       gst_audio_buffer_reorder_channels (*outbuf, ffmpegdec->info.finfo->format,
575           ffmpegdec->info.channels, ffmpegdec->ffmpeg_layout,
576           ffmpegdec->info.position);
577     }
578
579     /* Mark corrupted frames as corrupted */
580     if (ffmpegdec->frame->flags & AV_FRAME_FLAG_CORRUPT)
581       GST_BUFFER_FLAG_SET (*outbuf, GST_BUFFER_FLAG_CORRUPTED);
582   } else {
583     *outbuf = NULL;
584   }
585
586 beach:
587   av_frame_unref (ffmpegdec->frame);
588   GST_DEBUG_OBJECT (ffmpegdec, "return flow %d, out %p, len %d",
589       *ret, *outbuf, len);
590   return len;
591 }
592
593 /* gst_ffmpegauddec_frame:
594  * ffmpegdec:
595  * data: pointer to the data to decode
596  * size: size of data in bytes
597  * got_data: 0 if no data was decoded, != 0 otherwise.
598  * in_time: timestamp of data
599  * in_duration: duration of data
600  * ret: GstFlowReturn to return in the chain function
601  *
602  * Decode the given frame and pushes it downstream.
603  *
604  * Returns: Number of bytes used in decoding, -1 on error/failure.
605  */
606
607 static gint
608 gst_ffmpegauddec_frame (GstFFMpegAudDec * ffmpegdec,
609     guint8 * data, guint size, gint * have_data, GstFlowReturn * ret)
610 {
611   GstFFMpegAudDecClass *oclass;
612   GstBuffer *outbuf = NULL;
613   gint len = 0;
614
615   if (G_UNLIKELY (ffmpegdec->context->codec == NULL))
616     goto no_codec;
617
618   GST_LOG_OBJECT (ffmpegdec, "data:%p, size:%d", data, size);
619
620   *ret = GST_FLOW_OK;
621   ffmpegdec->context->frame_number++;
622
623   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
624
625   len =
626       gst_ffmpegauddec_audio_frame (ffmpegdec, oclass->in_plugin, data, size,
627       have_data, &outbuf, ret);
628
629   if (len < 0) {
630     GST_WARNING_OBJECT (ffmpegdec,
631         "avdec_%s: decoding error (len: %d, have_data: %d)",
632         oclass->in_plugin->name, len, *have_data);
633     goto beach;
634   }
635
636   if (outbuf) {
637     GST_LOG_OBJECT (ffmpegdec, "Decoded data, now storing buffer %p", outbuf);
638
639     if (ffmpegdec->outbuf)
640       ffmpegdec->outbuf = gst_buffer_append (ffmpegdec->outbuf, outbuf);
641     else
642       ffmpegdec->outbuf = outbuf;
643   } else {
644     GST_DEBUG_OBJECT (ffmpegdec, "We didn't get a decoded buffer");
645   }
646
647 beach:
648   return len;
649
650   /* ERRORS */
651 no_codec:
652   {
653     GST_ERROR_OBJECT (ffmpegdec, "no codec context");
654     return -1;
655   }
656 }
657
658 static void
659 gst_ffmpegauddec_drain (GstFFMpegAudDec * ffmpegdec)
660 {
661   GstFFMpegAudDecClass *oclass;
662
663   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
664
665   if (oclass->in_plugin->capabilities & CODEC_CAP_DELAY) {
666     gint have_data, len;
667
668     GST_LOG_OBJECT (ffmpegdec,
669         "codec has delay capabilities, calling until libav has drained everything");
670
671     do {
672       GstFlowReturn ret;
673
674       len = gst_ffmpegauddec_frame (ffmpegdec, NULL, 0, &have_data, &ret);
675
676     } while (len >= 0 && have_data == 1);
677     avcodec_flush_buffers (ffmpegdec->context);
678   }
679
680   if (ffmpegdec->outbuf)
681     gst_audio_decoder_finish_frame (GST_AUDIO_DECODER (ffmpegdec),
682         ffmpegdec->outbuf, 1);
683   ffmpegdec->outbuf = NULL;
684 }
685
686 static void
687 gst_ffmpegauddec_flush (GstAudioDecoder * decoder, gboolean hard)
688 {
689   GstFFMpegAudDec *ffmpegdec = (GstFFMpegAudDec *) decoder;
690
691   if (ffmpegdec->opened) {
692     avcodec_flush_buffers (ffmpegdec->context);
693   }
694 }
695
696 static GstFlowReturn
697 gst_ffmpegauddec_handle_frame (GstAudioDecoder * decoder, GstBuffer * inbuf)
698 {
699   GstFFMpegAudDec *ffmpegdec;
700   GstFFMpegAudDecClass *oclass;
701   guint8 *data, *bdata;
702   GstMapInfo map;
703   gint size, bsize, len, have_data;
704   GstFlowReturn ret = GST_FLOW_OK;
705   gboolean do_padding, is_header;
706
707   ffmpegdec = (GstFFMpegAudDec *) decoder;
708
709   if (G_UNLIKELY (!ffmpegdec->opened))
710     goto not_negotiated;
711
712   if (inbuf == NULL) {
713     gst_ffmpegauddec_drain (ffmpegdec);
714     return GST_FLOW_OK;
715   }
716
717   inbuf = gst_buffer_ref (inbuf);
718   is_header = GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_HEADER);
719
720   oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
721
722   GST_LOG_OBJECT (ffmpegdec,
723       "Received new data of size %" G_GSIZE_FORMAT ", offset:%" G_GUINT64_FORMAT
724       ", ts:%" GST_TIME_FORMAT ", dur:%" GST_TIME_FORMAT,
725       gst_buffer_get_size (inbuf), GST_BUFFER_OFFSET (inbuf),
726       GST_TIME_ARGS (GST_BUFFER_PTS (inbuf)),
727       GST_TIME_ARGS (GST_BUFFER_DURATION (inbuf)));
728
729   /* workarounds, functions write to buffers:
730    *  libavcodec/svq1.c:svq1_decode_frame writes to the given buffer.
731    *  libavcodec/svq3.c:svq3_decode_slice_header too.
732    * ffmpeg devs know about it and will fix it (they said). */
733   if (oclass->in_plugin->id == AV_CODEC_ID_SVQ1 ||
734       oclass->in_plugin->id == AV_CODEC_ID_SVQ3) {
735     inbuf = gst_buffer_make_writable (inbuf);
736   }
737
738   gst_buffer_map (inbuf, &map, GST_MAP_READ);
739
740   bdata = map.data;
741   bsize = map.size;
742
743   if (bsize > 0 && (!GST_MEMORY_IS_ZERO_PADDED (map.memory)
744           || (map.maxsize - map.size) < FF_INPUT_BUFFER_PADDING_SIZE)) {
745     /* add padding */
746     if (ffmpegdec->padded_size < bsize + FF_INPUT_BUFFER_PADDING_SIZE) {
747       ffmpegdec->padded_size = bsize + FF_INPUT_BUFFER_PADDING_SIZE;
748       ffmpegdec->padded = g_realloc (ffmpegdec->padded, ffmpegdec->padded_size);
749       GST_LOG_OBJECT (ffmpegdec, "resized padding buffer to %d",
750           ffmpegdec->padded_size);
751     }
752     GST_CAT_TRACE_OBJECT (CAT_PERFORMANCE, ffmpegdec,
753         "Copy input to add padding");
754     memcpy (ffmpegdec->padded, bdata, bsize);
755     memset (ffmpegdec->padded + bsize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
756
757     bdata = ffmpegdec->padded;
758     do_padding = TRUE;
759   } else {
760     do_padding = FALSE;
761   }
762
763   do {
764     guint8 tmp_padding[FF_INPUT_BUFFER_PADDING_SIZE];
765
766     data = bdata;
767     size = bsize;
768
769     if (do_padding) {
770       /* add temporary padding */
771       GST_CAT_TRACE_OBJECT (CAT_PERFORMANCE, ffmpegdec,
772           "Add temporary input padding");
773       memcpy (tmp_padding, data + size, FF_INPUT_BUFFER_PADDING_SIZE);
774       memset (data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
775     }
776
777     /* decode a frame of audio now */
778     len = gst_ffmpegauddec_frame (ffmpegdec, data, size, &have_data, &ret);
779
780     if (do_padding) {
781       memcpy (data + size, tmp_padding, FF_INPUT_BUFFER_PADDING_SIZE);
782     }
783
784     if (ret != GST_FLOW_OK) {
785       GST_LOG_OBJECT (ffmpegdec, "breaking because of flow ret %s",
786           gst_flow_get_name (ret));
787       /* bad flow return, make sure we discard all data and exit */
788       bsize = 0;
789       break;
790     }
791
792     if (len == 0 && have_data == 0) {
793       /* nothing was decoded, this could be because no data was available or
794        * because we were skipping frames.
795        * If we have no context we must exit and wait for more data, we keep the
796        * data we tried. */
797       GST_LOG_OBJECT (ffmpegdec, "Decoding didn't return any data, breaking");
798       break;
799     } else if (len < 0) {
800       /* a decoding error happened, we must break and try again with next data. */
801       GST_LOG_OBJECT (ffmpegdec, "Decoding error, breaking");
802       bsize = 0;
803       break;
804     }
805     /* prepare for the next round, for codecs with a context we did this
806      * already when using the parser. */
807     bsize -= len;
808     bdata += len;
809
810     do_padding = TRUE;
811
812     GST_LOG_OBJECT (ffmpegdec, "Before (while bsize>0).  bsize:%d , bdata:%p",
813         bsize, bdata);
814   } while (bsize > 0);
815
816   gst_buffer_unmap (inbuf, &map);
817   gst_buffer_unref (inbuf);
818
819   if (ffmpegdec->outbuf)
820     ret =
821         gst_audio_decoder_finish_frame (GST_AUDIO_DECODER (ffmpegdec),
822         ffmpegdec->outbuf, 1);
823   else if (len < 0 || is_header)
824     ret =
825         gst_audio_decoder_finish_frame (GST_AUDIO_DECODER (ffmpegdec), NULL, 1);
826   ffmpegdec->outbuf = NULL;
827
828   if (bsize > 0) {
829     GST_DEBUG_OBJECT (ffmpegdec, "Dropping %d bytes of data", bsize);
830   }
831
832   return ret;
833
834   /* ERRORS */
835 not_negotiated:
836   {
837     oclass = (GstFFMpegAudDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
838     GST_ELEMENT_ERROR (ffmpegdec, CORE, NEGOTIATION, (NULL),
839         ("avdec_%s: input format was not set before data start",
840             oclass->in_plugin->name));
841     return GST_FLOW_NOT_NEGOTIATED;
842   }
843 }
844
845 gboolean
846 gst_ffmpegauddec_register (GstPlugin * plugin)
847 {
848   GTypeInfo typeinfo = {
849     sizeof (GstFFMpegAudDecClass),
850     (GBaseInitFunc) gst_ffmpegauddec_base_init,
851     NULL,
852     (GClassInitFunc) gst_ffmpegauddec_class_init,
853     NULL,
854     NULL,
855     sizeof (GstFFMpegAudDec),
856     0,
857     (GInstanceInitFunc) gst_ffmpegauddec_init,
858   };
859   GType type;
860   AVCodec *in_plugin;
861   gint rank;
862
863   in_plugin = av_codec_next (NULL);
864
865   GST_LOG ("Registering decoders");
866
867   while (in_plugin) {
868     gchar *type_name;
869
870     /* only decoders */
871     if (!av_codec_is_decoder (in_plugin)
872         || in_plugin->type != AVMEDIA_TYPE_AUDIO) {
873       goto next;
874     }
875
876     /* no quasi codecs, please */
877     if (in_plugin->id == AV_CODEC_ID_PCM_S16LE_PLANAR ||
878         (in_plugin->id >= AV_CODEC_ID_PCM_S16LE &&
879             in_plugin->id <= AV_CODEC_ID_PCM_BLURAY) ||
880         (in_plugin->id >= AV_CODEC_ID_PCM_S8_PLANAR &&
881             in_plugin->id <= AV_CODEC_ID_PCM_S64BE)) {
882       goto next;
883     }
884
885     /* No decoders depending on external libraries (we don't build them, but
886      * people who build against an external ffmpeg might have them.
887      * We have native gstreamer plugins for all of those libraries anyway. */
888     if (!strncmp (in_plugin->name, "lib", 3)) {
889       GST_DEBUG
890           ("Not using external library decoder %s. Use the gstreamer-native ones instead.",
891           in_plugin->name);
892       goto next;
893     }
894
895     GST_DEBUG ("Trying plugin %s [%s]", in_plugin->name, in_plugin->long_name);
896
897     /* no codecs for which we're GUARANTEED to have better alternatives */
898     /* MP1 : Use MP3 for decoding */
899     /* MP2 : Use MP3 for decoding */
900     /* Theora: Use libtheora based theoradec */
901     if (!strcmp (in_plugin->name, "vorbis") ||
902         !strcmp (in_plugin->name, "wavpack") ||
903         !strcmp (in_plugin->name, "mp1") ||
904         !strcmp (in_plugin->name, "mp2") ||
905         !strcmp (in_plugin->name, "libfaad") ||
906         !strcmp (in_plugin->name, "mpeg4aac") ||
907         !strcmp (in_plugin->name, "ass") ||
908         !strcmp (in_plugin->name, "srt") ||
909         !strcmp (in_plugin->name, "pgssub") ||
910         !strcmp (in_plugin->name, "dvdsub") ||
911         !strcmp (in_plugin->name, "dvbsub")) {
912       GST_LOG ("Ignoring decoder %s", in_plugin->name);
913       goto next;
914     }
915
916     /* construct the type */
917     type_name = g_strdup_printf ("avdec_%s", in_plugin->name);
918     g_strdelimit (type_name, ".,|-<> ", '_');
919
920     type = g_type_from_name (type_name);
921
922     if (!type) {
923       /* create the gtype now */
924       type =
925           g_type_register_static (GST_TYPE_AUDIO_DECODER, type_name, &typeinfo,
926           0);
927       g_type_set_qdata (type, GST_FFDEC_PARAMS_QDATA, (gpointer) in_plugin);
928     }
929
930     /* (Ronald) MPEG-4 gets a higher priority because it has been well-
931      * tested and by far outperforms divxdec/xviddec - so we prefer it.
932      * msmpeg4v3 same, as it outperforms divxdec for divx3 playback.
933      * VC1/WMV3 are not working and thus unpreferred for now. */
934     switch (in_plugin->id) {
935       case AV_CODEC_ID_RA_144:
936       case AV_CODEC_ID_RA_288:
937       case AV_CODEC_ID_COOK:
938       case AV_CODEC_ID_AAC:
939         rank = GST_RANK_PRIMARY;
940         break;
941         /* SIPR: decoder should have a higher rank than realaudiodec.
942          */
943       case AV_CODEC_ID_SIPR:
944         rank = GST_RANK_SECONDARY;
945         break;
946       default:
947         rank = GST_RANK_MARGINAL;
948         break;
949     }
950     if (!gst_element_register (plugin, type_name, rank, type)) {
951       g_warning ("Failed to register %s", type_name);
952       g_free (type_name);
953       return FALSE;
954     }
955
956     g_free (type_name);
957
958   next:
959     in_plugin = av_codec_next (in_plugin);
960   }
961
962   GST_LOG ("Finished Registering decoders");
963
964   return TRUE;
965 }