Merging gst-plugins-ugly
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-ugly / ext / a52dec / gsta52dec.c
1 /* GStreamer
2  * Copyright (C) <2001> David I. Lehn <dlehn@users.sourceforge.net>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 /**
21  * SECTION:element-a52dec
22  * @title: a52dec
23  *
24  * Dolby Digital (AC-3) audio decoder.
25  *
26  * ## Example launch line
27  * |[
28  * gst-launch-1.0 dvdreadsrc title=1 ! mpegpsdemux ! a52dec ! audioconvert ! audioresample ! autoaudiosink
29  * ]| Play audio part of a dvd title.
30  * |[
31  * gst-launch-1.0 filesrc location=abc.ac3 ! ac3parse ! a52dec ! audioconvert ! audioresample ! autoaudiosink
32  * ]| Decode and play a stand alone AC-3 file.
33  *
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39
40 #include <string.h>
41 #include <stdlib.h>
42 #ifdef HAVE_STDINT_H
43 #include <stdint.h>
44 #endif
45
46 #include <gst/gst.h>
47
48 #include <a52dec/a52.h>
49 #if !defined(A52_ACCEL_DETECT)
50 #  include <a52dec/mm_accel.h>
51 #endif
52 #include "gsta52dec.h"
53
54 #if HAVE_ORC
55 #include <orc/orc.h>
56 #endif
57
58 #ifdef LIBA52_DOUBLE
59 #define SAMPLE_WIDTH 64
60 #define SAMPLE_FORMAT GST_AUDIO_NE(F64)
61 #define SAMPLE_TYPE GST_AUDIO_FORMAT_F64
62 #else
63 #define SAMPLE_WIDTH 32
64 #define SAMPLE_FORMAT GST_AUDIO_NE(F32)
65 #define SAMPLE_TYPE GST_AUDIO_FORMAT_F32
66 #endif
67
68 GST_DEBUG_CATEGORY_STATIC (a52dec_debug);
69 #define GST_CAT_DEFAULT (a52dec_debug)
70
71 /* A52Dec args */
72 enum
73 {
74   ARG_0,
75   ARG_DRC,
76   ARG_MODE,
77   ARG_LFE,
78 };
79
80 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
81     GST_PAD_SINK,
82     GST_PAD_ALWAYS,
83     GST_STATIC_CAPS ("audio/x-ac3; audio/ac3; audio/x-private1-ac3")
84     );
85
86 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
87     GST_PAD_SRC,
88     GST_PAD_ALWAYS,
89     GST_STATIC_CAPS ("audio/x-raw, "
90         "format = (string) " SAMPLE_FORMAT ", "
91         "layout = (string) interleaved, "
92         "rate = (int) [ 4000, 96000 ], " "channels = (int) [ 1, 6 ]")
93     );
94
95 static gboolean a52_element_init (GstPlugin * plugin);
96
97 #define gst_a52dec_parent_class parent_class
98 G_DEFINE_TYPE (GstA52Dec, gst_a52dec, GST_TYPE_AUDIO_DECODER);
99 GST_ELEMENT_REGISTER_DEFINE_CUSTOM (a52dec, a52_element_init);
100
101 static gboolean gst_a52dec_start (GstAudioDecoder * dec);
102 static gboolean gst_a52dec_stop (GstAudioDecoder * dec);
103 static gboolean gst_a52dec_set_format (GstAudioDecoder * bdec, GstCaps * caps);
104 static GstFlowReturn gst_a52dec_parse (GstAudioDecoder * dec,
105     GstAdapter * adapter, gint * offset, gint * length);
106 static GstFlowReturn gst_a52dec_handle_frame (GstAudioDecoder * dec,
107     GstBuffer * buffer);
108
109 static GstFlowReturn gst_a52dec_chain (GstPad * pad, GstObject * parent,
110     GstBuffer * buffer);
111 static void gst_a52dec_set_property (GObject * object, guint prop_id,
112     const GValue * value, GParamSpec * pspec);
113 static void gst_a52dec_get_property (GObject * object, guint prop_id,
114     GValue * value, GParamSpec * pspec);
115
116 #define GST_TYPE_A52DEC_MODE (gst_a52dec_mode_get_type())
117 static GType
118 gst_a52dec_mode_get_type (void)
119 {
120   static GType a52dec_mode_type = 0;
121   static const GEnumValue a52dec_modes[] = {
122     {A52_MONO, "Mono", "mono"},
123     {A52_STEREO, "Stereo", "stereo"},
124     {A52_3F, "3 Front", "3f"},
125     {A52_2F1R, "2 Front, 1 Rear", "2f1r"},
126     {A52_3F1R, "3 Front, 1 Rear", "3f1r"},
127     {A52_2F2R, "2 Front, 2 Rear", "2f2r"},
128     {A52_3F2R, "3 Front, 2 Rear", "3f2r"},
129     {A52_DOLBY, "Dolby", "dolby"},
130     {0, NULL, NULL},
131   };
132
133   if (!a52dec_mode_type) {
134     a52dec_mode_type = g_enum_register_static ("GstA52DecMode", a52dec_modes);
135   }
136   return a52dec_mode_type;
137 }
138
139 static void
140 gst_a52dec_class_init (GstA52DecClass * klass)
141 {
142   GObjectClass *gobject_class;
143   GstElementClass *gstelement_class;
144   GstAudioDecoderClass *gstbase_class;
145   guint cpuflags = 0;
146
147   gobject_class = (GObjectClass *) klass;
148   gstelement_class = (GstElementClass *) klass;
149   gstbase_class = (GstAudioDecoderClass *) klass;
150
151   gobject_class->set_property = gst_a52dec_set_property;
152   gobject_class->get_property = gst_a52dec_get_property;
153
154   gstbase_class->start = GST_DEBUG_FUNCPTR (gst_a52dec_start);
155   gstbase_class->stop = GST_DEBUG_FUNCPTR (gst_a52dec_stop);
156   gstbase_class->set_format = GST_DEBUG_FUNCPTR (gst_a52dec_set_format);
157   gstbase_class->parse = GST_DEBUG_FUNCPTR (gst_a52dec_parse);
158   gstbase_class->handle_frame = GST_DEBUG_FUNCPTR (gst_a52dec_handle_frame);
159
160   /**
161    * GstA52Dec::drc
162    *
163    * Set to true to apply the recommended Dolby Digital dynamic range compression
164    * to the audio stream. Dynamic range compression makes loud sounds
165    * softer and soft sounds louder, so you can more easily listen
166    * to the stream without disturbing other people.
167    */
168   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_DRC,
169       g_param_spec_boolean ("drc", "Dynamic Range Compression",
170           "Use Dynamic Range Compression", FALSE,
171           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
172   /**
173    * GstA52Dec::mode
174    *
175    * Force a particular output channel configuration from the decoder. By default,
176    * the channel downmix (if any) is chosen automatically based on the downstream
177    * capabilities of the pipeline.
178    */
179   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_MODE,
180       g_param_spec_enum ("mode", "Decoder Mode", "Decoding Mode (default 3f2r)",
181           GST_TYPE_A52DEC_MODE, A52_3F2R,
182           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
183   /**
184    * GstA52Dec::lfe
185    *
186    * Whether to output the LFE (Low Frequency Emitter) channel of the audio stream.
187    */
188   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_LFE,
189       g_param_spec_boolean ("lfe", "LFE", "LFE", TRUE,
190           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
191
192   gst_element_class_add_static_pad_template (gstelement_class, &sink_factory);
193   gst_element_class_add_static_pad_template (gstelement_class, &src_factory);
194   gst_element_class_set_static_metadata (gstelement_class,
195       "ATSC A/52 audio decoder", "Codec/Decoder/Audio/Converter",
196       "Decodes ATSC A/52 encoded audio streams",
197       "David I. Lehn <dlehn@users.sourceforge.net>");
198
199   GST_DEBUG_CATEGORY_INIT (a52dec_debug, "a52dec", 0,
200       "AC3/A52 software decoder");
201
202   /* If no CPU instruction based acceleration is available, end up using the
203    * generic software djbfft based one when available in the used liba52 */
204 #ifdef MM_ACCEL_DJBFFT
205   klass->a52_cpuflags = MM_ACCEL_DJBFFT;
206 #elif defined(A52_ACCEL_DETECT)
207   klass->a52_cpuflags = A52_ACCEL_DETECT;
208 #else
209   klass->a52_cpuflags = 0;
210 #endif
211
212 #if HAVE_ORC && !defined(A52_ACCEL_DETECT)
213   cpuflags = orc_target_get_default_flags (orc_target_get_by_name ("mmx"));
214   if (cpuflags & ORC_TARGET_MMX_MMX)
215     klass->a52_cpuflags |= MM_ACCEL_X86_MMX;
216   if (cpuflags & ORC_TARGET_MMX_3DNOW)
217     klass->a52_cpuflags |= MM_ACCEL_X86_3DNOW;
218   if (cpuflags & ORC_TARGET_MMX_MMXEXT)
219     klass->a52_cpuflags |= MM_ACCEL_X86_MMXEXT;
220 #endif
221
222   GST_LOG ("CPU flags: a52=%08x, orc=%08x", klass->a52_cpuflags, cpuflags);
223
224   gst_type_mark_as_plugin_api (GST_TYPE_A52DEC_MODE, 0);
225 }
226
227 static void
228 gst_a52dec_init (GstA52Dec * a52dec)
229 {
230   a52dec->request_channels = A52_CHANNEL;
231   a52dec->dynamic_range_compression = FALSE;
232
233   a52dec->state = NULL;
234   a52dec->samples = NULL;
235
236   gst_audio_decoder_set_use_default_pad_acceptcaps (GST_AUDIO_DECODER_CAST
237       (a52dec), TRUE);
238   GST_PAD_SET_ACCEPT_TEMPLATE (GST_AUDIO_DECODER_SINK_PAD (a52dec));
239
240   /* retrieve and intercept base class chain.
241    * Quite HACKish, but that's dvd specs/caps for you,
242    * since one buffer needs to be split into 2 frames */
243   a52dec->base_chain = GST_PAD_CHAINFUNC (GST_AUDIO_DECODER_SINK_PAD (a52dec));
244   gst_pad_set_chain_function (GST_AUDIO_DECODER_SINK_PAD (a52dec),
245       GST_DEBUG_FUNCPTR (gst_a52dec_chain));
246 }
247
248 static gboolean
249 gst_a52dec_start (GstAudioDecoder * dec)
250 {
251   GstA52Dec *a52dec = GST_A52DEC (dec);
252   GstA52DecClass *klass;
253   static GMutex init_mutex;
254
255   GST_DEBUG_OBJECT (dec, "start");
256
257   klass = GST_A52DEC_CLASS (G_OBJECT_GET_CLASS (a52dec));
258   g_mutex_lock (&init_mutex);
259 #if defined(A52_ACCEL_DETECT)
260   a52dec->state = a52_init ();
261   /* This line is just to avoid being accused of not using klass */
262   a52_accel (klass->a52_cpuflags & A52_ACCEL_DETECT);
263 #else
264   a52dec->state = a52_init (klass->a52_cpuflags);
265 #endif
266   g_mutex_unlock (&init_mutex);
267
268   if (!a52dec->state) {
269     GST_ELEMENT_ERROR (GST_ELEMENT (a52dec), LIBRARY, INIT, (NULL),
270         ("failed to initialize a52 state"));
271     return FALSE;
272   }
273
274   a52dec->samples = a52_samples (a52dec->state);
275   a52dec->bit_rate = -1;
276   a52dec->sample_rate = -1;
277   a52dec->stream_channels = A52_CHANNEL;
278   a52dec->using_channels = A52_CHANNEL;
279   a52dec->level = 1;
280   a52dec->bias = 0;
281   a52dec->flag_update = TRUE;
282
283   /* call upon legacy upstream byte support (e.g. seeking) */
284   gst_audio_decoder_set_estimate_rate (dec, TRUE);
285
286   return TRUE;
287 }
288
289 static gboolean
290 gst_a52dec_stop (GstAudioDecoder * dec)
291 {
292   GstA52Dec *a52dec = GST_A52DEC (dec);
293
294   GST_DEBUG_OBJECT (dec, "stop");
295
296   a52dec->samples = NULL;
297   if (a52dec->state) {
298     a52_free (a52dec->state);
299     a52dec->state = NULL;
300   }
301
302   return TRUE;
303 }
304
305 static GstFlowReturn
306 gst_a52dec_parse (GstAudioDecoder * bdec, GstAdapter * adapter,
307     gint * _offset, gint * len)
308 {
309   GstA52Dec *a52dec;
310   const guint8 *data;
311   gint av, size;
312   gint length = 0, flags, sample_rate, bit_rate;
313   GstFlowReturn result = GST_FLOW_EOS;
314
315   a52dec = GST_A52DEC (bdec);
316
317   size = av = gst_adapter_available (adapter);
318   data = (const guint8 *) gst_adapter_map (adapter, av);
319
320   /* find and read header */
321   bit_rate = a52dec->bit_rate;
322   sample_rate = a52dec->sample_rate;
323   flags = 0;
324   while (size >= 7) {
325     length = a52_syncinfo ((guint8 *) data, &flags, &sample_rate, &bit_rate);
326
327     if (length == 0) {
328       /* shift window to re-find sync */
329       data++;
330       size--;
331     } else if (length <= size) {
332       GST_LOG_OBJECT (a52dec, "Sync: frame size %d", length);
333       result = GST_FLOW_OK;
334       break;
335     } else {
336       GST_LOG_OBJECT (a52dec, "Not enough data available (needed %d had %d)",
337           length, size);
338       break;
339     }
340   }
341   gst_adapter_unmap (adapter);
342
343   *_offset = av - size;
344   *len = length;
345
346   return result;
347 }
348
349 static gint
350 gst_a52dec_channels (int flags, GstAudioChannelPosition * pos)
351 {
352   gint chans = 0;
353
354   if (flags & A52_LFE) {
355     chans += 1;
356     if (pos) {
357       pos[0] = GST_AUDIO_CHANNEL_POSITION_LFE1;
358     }
359   }
360   flags &= A52_CHANNEL_MASK;
361   switch (flags) {
362     case A52_3F2R:
363       if (pos) {
364         pos[0 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT;
365         pos[1 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER;
366         pos[2 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT;
367         pos[3 + chans] = GST_AUDIO_CHANNEL_POSITION_REAR_LEFT;
368         pos[4 + chans] = GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT;
369       }
370       chans += 5;
371       break;
372     case A52_2F2R:
373       if (pos) {
374         pos[0 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT;
375         pos[1 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT;
376         pos[2 + chans] = GST_AUDIO_CHANNEL_POSITION_REAR_LEFT;
377         pos[3 + chans] = GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT;
378       }
379       chans += 4;
380       break;
381     case A52_3F1R:
382       if (pos) {
383         pos[0 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT;
384         pos[1 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER;
385         pos[2 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT;
386         pos[3 + chans] = GST_AUDIO_CHANNEL_POSITION_REAR_CENTER;
387       }
388       chans += 4;
389       break;
390     case A52_2F1R:
391       if (pos) {
392         pos[0 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT;
393         pos[1 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT;
394         pos[2 + chans] = GST_AUDIO_CHANNEL_POSITION_REAR_CENTER;
395       }
396       chans += 3;
397       break;
398     case A52_3F:
399       if (pos) {
400         pos[0 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT;
401         pos[1 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER;
402         pos[2 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT;
403       }
404       chans += 3;
405       break;
406     case A52_CHANNEL:          /* Dual mono. Should really be handled as 2 src pads */
407     case A52_STEREO:
408     case A52_DOLBY:
409       if (pos) {
410         pos[0 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT;
411         pos[1 + chans] = GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT;
412       }
413       chans += 2;
414       break;
415     case A52_MONO:
416       if (pos) {
417         pos[0 + chans] = GST_AUDIO_CHANNEL_POSITION_MONO;
418       }
419       chans += 1;
420       break;
421     default:
422       /* error, caller should post error message */
423       return 0;
424   }
425
426   return chans;
427 }
428
429 static gboolean
430 gst_a52dec_reneg (GstA52Dec * a52dec)
431 {
432   gint channels;
433   gboolean result = FALSE;
434   GstAudioChannelPosition from[6], to[6];
435   GstAudioInfo info;
436
437   channels = gst_a52dec_channels (a52dec->using_channels, from);
438
439   if (!channels)
440     goto done;
441
442   GST_INFO_OBJECT (a52dec, "reneg channels:%d rate:%d",
443       channels, a52dec->sample_rate);
444
445   memcpy (to, from, sizeof (GstAudioChannelPosition) * channels);
446   gst_audio_channel_positions_to_valid_order (to, channels);
447   gst_audio_get_channel_reorder_map (channels, from, to,
448       a52dec->channel_reorder_map);
449
450   gst_audio_info_init (&info);
451   gst_audio_info_set_format (&info,
452       SAMPLE_TYPE, a52dec->sample_rate, channels, (channels > 1 ? to : NULL));
453
454   if (!gst_audio_decoder_set_output_format (GST_AUDIO_DECODER (a52dec), &info))
455     goto done;
456
457   result = TRUE;
458
459 done:
460   return result;
461 }
462
463 static void
464 gst_a52dec_update_streaminfo (GstA52Dec * a52dec)
465 {
466   GstTagList *taglist;
467
468   taglist = gst_tag_list_new_empty ();
469   gst_tag_list_add (taglist, GST_TAG_MERGE_APPEND, GST_TAG_BITRATE,
470       (guint) a52dec->bit_rate, NULL);
471
472   gst_audio_decoder_merge_tags (GST_AUDIO_DECODER (a52dec), taglist,
473       GST_TAG_MERGE_REPLACE);
474   gst_tag_list_unref (taglist);
475 }
476
477 static GstFlowReturn
478 gst_a52dec_handle_frame (GstAudioDecoder * bdec, GstBuffer * buffer)
479 {
480   GstA52Dec *a52dec;
481   gint channels, i;
482   gboolean need_reneg = FALSE;
483   gint chans;
484   gint length = 0, flags, sample_rate, bit_rate;
485   GstMapInfo map;
486   GstFlowReturn result = GST_FLOW_OK;
487   GstBuffer *outbuf;
488   const gint num_blocks = 6;
489
490   a52dec = GST_A52DEC (bdec);
491
492   /* no fancy draining */
493   if (G_UNLIKELY (!buffer))
494     return GST_FLOW_OK;
495
496   /* parsed stuff already, so this should work out fine */
497   gst_buffer_map (buffer, &map, GST_MAP_READ);
498   g_assert (map.size >= 7);
499
500   /* re-obtain some sync header info,
501    * should be same as during _parse and could also be cached there,
502    * but anyway ... */
503   bit_rate = a52dec->bit_rate;
504   sample_rate = a52dec->sample_rate;
505   flags = 0;
506   length = a52_syncinfo (map.data, &flags, &sample_rate, &bit_rate);
507   g_assert (length == map.size);
508
509   /* update stream information, renegotiate or re-streaminfo if needed */
510   need_reneg = FALSE;
511   if (a52dec->sample_rate != sample_rate) {
512     GST_DEBUG_OBJECT (a52dec, "sample rate changed");
513     need_reneg = TRUE;
514     a52dec->sample_rate = sample_rate;
515   }
516
517   if (flags) {
518     if (a52dec->stream_channels != (flags & (A52_CHANNEL_MASK | A52_LFE))) {
519       GST_DEBUG_OBJECT (a52dec, "stream channel flags changed, marking update");
520       a52dec->flag_update = TRUE;
521     }
522     a52dec->stream_channels = flags & (A52_CHANNEL_MASK | A52_LFE);
523   }
524
525   if (bit_rate != a52dec->bit_rate) {
526     a52dec->bit_rate = bit_rate;
527     gst_a52dec_update_streaminfo (a52dec);
528   }
529
530   /* If we haven't had an explicit number of channels chosen through properties
531    * at this point, choose what to downmix to now, based on what the peer will
532    * accept - this allows a52dec to do downmixing in preference to a
533    * downstream element such as audioconvert.
534    */
535   if (a52dec->request_channels != A52_CHANNEL) {
536     flags = a52dec->request_channels;
537   } else if (a52dec->flag_update) {
538     GstCaps *caps;
539
540     a52dec->flag_update = FALSE;
541
542     caps = gst_pad_get_allowed_caps (GST_AUDIO_DECODER_SRC_PAD (a52dec));
543     if (caps && gst_caps_get_size (caps) > 0) {
544       GstCaps *copy = gst_caps_copy_nth (caps, 0);
545       GstStructure *structure = gst_caps_get_structure (copy, 0);
546       gint orig_channels = flags ? gst_a52dec_channels (flags, NULL) : 6;
547       gint fixed_channels = 0;
548       const int a52_channels[6] = {
549         A52_MONO,
550         A52_STEREO,
551         A52_STEREO | A52_LFE,
552         A52_2F2R,
553         A52_2F2R | A52_LFE,
554         A52_3F2R | A52_LFE,
555       };
556
557       /* Prefer the original number of channels, but fixate to something
558        * preferred (first in the caps) downstream if possible.
559        */
560       gst_structure_fixate_field_nearest_int (structure, "channels",
561           orig_channels);
562
563       if (gst_structure_get_int (structure, "channels", &fixed_channels)
564           && fixed_channels <= 6) {
565         if (fixed_channels < orig_channels)
566           flags = a52_channels[fixed_channels - 1];
567       } else {
568         flags = a52_channels[5];
569       }
570
571       gst_caps_unref (copy);
572     } else if (flags)
573       flags = a52dec->stream_channels;
574     else
575       flags = A52_3F2R | A52_LFE;
576
577     if (caps)
578       gst_caps_unref (caps);
579   } else {
580     flags = a52dec->using_channels;
581   }
582
583   /* process */
584   flags |= A52_ADJUST_LEVEL;
585   a52dec->level = 1;
586   if (a52_frame (a52dec->state, map.data, &flags, &a52dec->level, a52dec->bias)) {
587     gst_buffer_unmap (buffer, &map);
588     GST_AUDIO_DECODER_ERROR (a52dec, 1, STREAM, DECODE, (NULL),
589         ("a52_frame error"), result);
590     goto exit;
591   }
592   gst_buffer_unmap (buffer, &map);
593
594   channels = flags & (A52_CHANNEL_MASK | A52_LFE);
595   if (a52dec->using_channels != channels) {
596     need_reneg = TRUE;
597     a52dec->using_channels = channels;
598   }
599
600   /* negotiate if required */
601   if (need_reneg) {
602     GST_DEBUG_OBJECT (a52dec,
603         "a52dec reneg: sample_rate:%d stream_chans:%d using_chans:%d",
604         a52dec->sample_rate, a52dec->stream_channels, a52dec->using_channels);
605     if (!gst_a52dec_reneg (a52dec))
606       goto failed_negotiation;
607   }
608
609   if (a52dec->dynamic_range_compression == FALSE) {
610     a52_dynrng (a52dec->state, NULL, NULL);
611   }
612
613   flags &= (A52_CHANNEL_MASK | A52_LFE);
614   chans = gst_a52dec_channels (flags, NULL);
615   if (!chans)
616     goto invalid_flags;
617
618   /* handle decoded data;
619    * each frame has 6 blocks, one block is 256 samples, ea */
620   outbuf =
621       gst_buffer_new_and_alloc (256 * chans * (SAMPLE_WIDTH / 8) * num_blocks);
622
623   gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
624   {
625     guint8 *ptr = map.data;
626     for (i = 0; i < num_blocks; i++) {
627       if (a52_block (a52dec->state)) {
628         /* also marks discont */
629         GST_AUDIO_DECODER_ERROR (a52dec, 1, STREAM, DECODE, (NULL),
630             ("error decoding block %d", i), result);
631         if (result != GST_FLOW_OK) {
632           gst_buffer_unmap (outbuf, &map);
633           gst_buffer_unref (outbuf);
634           goto exit;
635         }
636       } else {
637         gint n, c;
638         gint *reorder_map = a52dec->channel_reorder_map;
639
640         for (n = 0; n < 256; n++) {
641           for (c = 0; c < chans; c++) {
642             ((sample_t *) ptr)[n * chans + reorder_map[c]] =
643                 a52dec->samples[c * 256 + n];
644           }
645         }
646       }
647       ptr += 256 * chans * (SAMPLE_WIDTH / 8);
648     }
649   }
650   gst_buffer_unmap (outbuf, &map);
651
652   result = gst_audio_decoder_finish_frame (bdec, outbuf, 1);
653
654 exit:
655   return result;
656
657   /* ERRORS */
658 failed_negotiation:
659   {
660     GST_ELEMENT_ERROR (a52dec, CORE, NEGOTIATION, (NULL), (NULL));
661     return GST_FLOW_ERROR;
662   }
663 invalid_flags:
664   {
665     GST_ELEMENT_ERROR (GST_ELEMENT (a52dec), STREAM, DECODE, (NULL),
666         ("Invalid channel flags: %d", flags));
667     return GST_FLOW_ERROR;
668   }
669 }
670
671 static gboolean
672 gst_a52dec_set_format (GstAudioDecoder * bdec, GstCaps * caps)
673 {
674   GstA52Dec *a52dec = GST_A52DEC (bdec);
675   GstStructure *structure;
676
677   structure = gst_caps_get_structure (caps, 0);
678
679   if (structure && gst_structure_has_name (structure, "audio/x-private1-ac3"))
680     a52dec->dvdmode = TRUE;
681   else
682     a52dec->dvdmode = FALSE;
683
684   return TRUE;
685 }
686
687 static GstFlowReturn
688 gst_a52dec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
689 {
690   GstA52Dec *a52dec = GST_A52DEC (parent);
691   GstFlowReturn ret = GST_FLOW_OK;
692   gint first_access;
693
694   if (a52dec->dvdmode) {
695     gsize size;
696     guint8 data[2];
697     gint offset;
698     gint len;
699     GstBuffer *subbuf;
700
701     size = gst_buffer_get_size (buf);
702     if (size < 2)
703       goto not_enough_data;
704
705     gst_buffer_extract (buf, 0, data, 2);
706     first_access = (data[0] << 8) | data[1];
707
708     /* Skip the first_access header */
709     offset = 2;
710
711     if (first_access > 1) {
712       /* Length of data before first_access */
713       len = first_access - 1;
714
715       if (len <= 0 || offset + len > size)
716         goto bad_first_access_parameter;
717
718       subbuf = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, offset, len);
719       GST_BUFFER_TIMESTAMP (subbuf) = GST_CLOCK_TIME_NONE;
720       ret = a52dec->base_chain (pad, parent, subbuf);
721       if (ret != GST_FLOW_OK) {
722         gst_buffer_unref (buf);
723         goto done;
724       }
725
726       offset += len;
727       len = size - offset;
728
729       if (len > 0) {
730         subbuf = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, offset, len);
731         GST_BUFFER_TIMESTAMP (subbuf) = GST_BUFFER_TIMESTAMP (buf);
732
733         ret = a52dec->base_chain (pad, parent, subbuf);
734       }
735       gst_buffer_unref (buf);
736     } else {
737       /* first_access = 0 or 1, so if there's a timestamp it applies to the first byte */
738       subbuf =
739           gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, offset,
740           size - offset);
741       GST_BUFFER_TIMESTAMP (subbuf) = GST_BUFFER_TIMESTAMP (buf);
742       gst_buffer_unref (buf);
743       ret = a52dec->base_chain (pad, parent, subbuf);
744     }
745   } else {
746     ret = a52dec->base_chain (pad, parent, buf);
747   }
748
749 done:
750   return ret;
751
752 /* ERRORS */
753 not_enough_data:
754   {
755     GST_ELEMENT_ERROR (GST_ELEMENT (a52dec), STREAM, DECODE, (NULL),
756         ("Insufficient data in buffer. Can't determine first_acess"));
757     gst_buffer_unref (buf);
758     return GST_FLOW_ERROR;
759   }
760 bad_first_access_parameter:
761   {
762     GST_ELEMENT_ERROR (GST_ELEMENT (a52dec), STREAM, DECODE, (NULL),
763         ("Bad first_access parameter (%d) in buffer", first_access));
764     gst_buffer_unref (buf);
765     return GST_FLOW_ERROR;
766   }
767 }
768
769 static void
770 gst_a52dec_set_property (GObject * object, guint prop_id, const GValue * value,
771     GParamSpec * pspec)
772 {
773   GstA52Dec *src = GST_A52DEC (object);
774
775   switch (prop_id) {
776     case ARG_DRC:
777       GST_OBJECT_LOCK (src);
778       src->dynamic_range_compression = g_value_get_boolean (value);
779       GST_OBJECT_UNLOCK (src);
780       break;
781     case ARG_MODE:
782       GST_OBJECT_LOCK (src);
783       src->request_channels &= ~A52_CHANNEL_MASK;
784       src->request_channels |= g_value_get_enum (value);
785       GST_OBJECT_UNLOCK (src);
786       break;
787     case ARG_LFE:
788       GST_OBJECT_LOCK (src);
789       src->request_channels &= ~A52_LFE;
790       src->request_channels |= g_value_get_boolean (value) ? A52_LFE : 0;
791       GST_OBJECT_UNLOCK (src);
792       break;
793     default:
794       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
795       break;
796   }
797 }
798
799 static void
800 gst_a52dec_get_property (GObject * object, guint prop_id, GValue * value,
801     GParamSpec * pspec)
802 {
803   GstA52Dec *src = GST_A52DEC (object);
804
805   switch (prop_id) {
806     case ARG_DRC:
807       GST_OBJECT_LOCK (src);
808       g_value_set_boolean (value, src->dynamic_range_compression);
809       GST_OBJECT_UNLOCK (src);
810       break;
811     case ARG_MODE:
812       GST_OBJECT_LOCK (src);
813       g_value_set_enum (value, src->request_channels & A52_CHANNEL_MASK);
814       GST_OBJECT_UNLOCK (src);
815       break;
816     case ARG_LFE:
817       GST_OBJECT_LOCK (src);
818       g_value_set_boolean (value, src->request_channels & A52_LFE);
819       GST_OBJECT_UNLOCK (src);
820       break;
821     default:
822       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
823       break;
824   }
825 }
826
827 static gboolean
828 a52_element_init (GstPlugin * plugin)
829 {
830 #if HAVE_ORC
831   orc_init ();
832 #endif
833
834   return gst_element_register (plugin, "a52dec", GST_RANK_SECONDARY,
835       GST_TYPE_A52DEC);
836 }
837
838 static gboolean
839 plugin_init (GstPlugin * plugin)
840 {
841   return GST_ELEMENT_REGISTER (a52dec, plugin);
842 }
843
844 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
845     GST_VERSION_MINOR,
846     a52dec,
847     "Decodes ATSC A/52 encoded audio streams",
848     plugin_init, VERSION, "GPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);