• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GStreamer libsndfile plugin
2  * Copyright (C) 2013 Stefan Sauer <ensonic@users.sf.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 self 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 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23 
24 #include <stdlib.h>
25 #include <gst/gst-i18n-plugin.h>
26 #include <gst/audio/audio.h>
27 
28 #include "gstsfelements.h"
29 #include "gstsfdec.h"
30 
31 #define FORMATS \
32     "{ "GST_AUDIO_NE (F32)", "GST_AUDIO_NE (S32)", "GST_AUDIO_NE (S16)" }"
33 
34 static GstStaticPadTemplate sf_dec_src_factory = GST_STATIC_PAD_TEMPLATE ("src",
35     GST_PAD_SRC,
36     GST_PAD_ALWAYS,
37     GST_STATIC_CAPS ("audio/x-raw, "
38         "format = (string) " FORMATS ", "
39         "layout = (string) interleaved, "
40         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]"));
41 
42 GST_DEBUG_CATEGORY_STATIC (gst_sf_dec_debug);
43 #define GST_CAT_DEFAULT gst_sf_dec_debug
44 
45 #define DEFAULT_BUFFER_FRAMES	(256)
46 
47 static gboolean gst_sf_dec_src_event (GstPad * pad, GstObject * parent,
48     GstEvent * event);
49 static gboolean gst_sf_dec_src_query (GstPad * pad, GstObject * parent,
50     GstQuery * query);
51 static GstStateChangeReturn gst_sf_dec_change_state (GstElement * element,
52     GstStateChange transition);
53 
54 static gboolean gst_sf_dec_sink_activate (GstPad * pad, GstObject * parent);
55 static gboolean gst_sf_dec_sink_activate_mode (GstPad * sinkpad,
56     GstObject * parent, GstPadMode mode, gboolean active);
57 static void gst_sf_dec_loop (GstPad * pad);
58 
59 static gboolean gst_sf_dec_start (GstSFDec * bsrc);
60 static gboolean gst_sf_dec_stop (GstSFDec * bsrc);
61 
62 #define _do_init \
63     GST_DEBUG_CATEGORY_INIT (gst_sf_dec_debug, "sfdec", 0, "sfdec element");
64 #define gst_sf_dec_parent_class parent_class
65 G_DEFINE_TYPE_WITH_CODE (GstSFDec, gst_sf_dec, GST_TYPE_ELEMENT, _do_init);
66 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (sfdec, "sfdec", GST_RANK_MARGINAL,
67     GST_TYPE_SF_DEC, sf_element_init (plugin));
68 /* sf virtual io */
69 
70 static sf_count_t
gst_sf_vio_get_filelen(void * user_data)71 gst_sf_vio_get_filelen (void *user_data)
72 {
73   GstSFDec *self = GST_SF_DEC (user_data);
74   gint64 dur;
75 
76   if (gst_pad_peer_query_duration (self->sinkpad, GST_FORMAT_BYTES, &dur)) {
77     return (sf_count_t) dur;
78   }
79   GST_WARNING_OBJECT (self, "query_duration failed");
80   return -1;
81 }
82 
83 static sf_count_t
gst_sf_vio_tell(void * user_data)84 gst_sf_vio_tell (void *user_data)
85 {
86   GstSFDec *self = GST_SF_DEC (user_data);
87   return self->pos;
88 }
89 
90 static sf_count_t
gst_sf_vio_seek(sf_count_t offset,int whence,void * user_data)91 gst_sf_vio_seek (sf_count_t offset, int whence, void *user_data)
92 {
93   GstSFDec *self = GST_SF_DEC (user_data);
94 
95   switch (whence) {
96     case SEEK_CUR:
97       self->pos += offset;
98       break;
99     case SEEK_SET:
100       self->pos = offset;
101       break;
102     case SEEK_END:
103       self->pos = gst_sf_vio_get_filelen (user_data) - offset;
104       break;
105   }
106   return (sf_count_t) self->pos;
107 }
108 
109 static sf_count_t
gst_sf_vio_read(void * ptr,sf_count_t count,void * user_data)110 gst_sf_vio_read (void *ptr, sf_count_t count, void *user_data)
111 {
112   GstSFDec *self = GST_SF_DEC (user_data);
113   GstBuffer *buffer = gst_buffer_new_wrapped_full (0, ptr, count, 0, count,
114       ptr, NULL);
115 
116   if (gst_pad_pull_range (self->sinkpad, self->pos, count, &buffer) ==
117       GST_FLOW_OK) {
118     GST_DEBUG_OBJECT (self, "read %d bytes @ pos %" G_GUINT64_FORMAT,
119         (gint) count, self->pos);
120     self->pos += count;
121     return count;
122   }
123   GST_WARNING_OBJECT (self, "read failed");
124   return 0;
125 }
126 
127 static sf_count_t
gst_sf_vio_write(const void * ptr,sf_count_t count,void * user_data)128 gst_sf_vio_write (const void *ptr, sf_count_t count, void *user_data)
129 {
130   GstSFDec *self = GST_SF_DEC (user_data);
131   GstBuffer *buffer = gst_buffer_new_memdup (ptr, count);
132 
133   if (gst_pad_push (self->srcpad, buffer) == GST_FLOW_OK) {
134     return count;
135   }
136   GST_WARNING_OBJECT (self, "write failed");
137   return 0;
138 }
139 
140 SF_VIRTUAL_IO gst_sf_vio = {
141   &gst_sf_vio_get_filelen,
142   &gst_sf_vio_seek,
143   &gst_sf_vio_read,
144   &gst_sf_vio_write,
145   &gst_sf_vio_tell,
146 };
147 
148 
149 static void
gst_sf_dec_class_init(GstSFDecClass * klass)150 gst_sf_dec_class_init (GstSFDecClass * klass)
151 {
152   GstElementClass *gstelement_class;
153 
154   gstelement_class = GST_ELEMENT_CLASS (klass);
155   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_sf_dec_change_state);
156 
157   gst_element_class_set_static_metadata (gstelement_class, "Sndfile decoder",
158       "Decoder/Audio",
159       "Read audio streams using libsndfile",
160       "Stefan Sauer <ensonic@user.sf.net>");
161 
162   gst_element_class_add_static_pad_template (gstelement_class,
163       &sf_dec_src_factory);
164 
165   gst_element_class_add_pad_template (gstelement_class,
166       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
167           gst_sf_create_audio_template_caps ()));
168 
169 }
170 
171 static void
gst_sf_dec_init(GstSFDec * self)172 gst_sf_dec_init (GstSFDec * self)
173 {
174   self->sinkpad = gst_pad_new_from_template (gst_element_class_get_pad_template
175       (GST_ELEMENT_GET_CLASS (self), "sink"), "sink");
176   gst_pad_set_activate_function (self->sinkpad,
177       GST_DEBUG_FUNCPTR (gst_sf_dec_sink_activate));
178   gst_pad_set_activatemode_function (self->sinkpad,
179       GST_DEBUG_FUNCPTR (gst_sf_dec_sink_activate_mode));
180   gst_element_add_pad (GST_ELEMENT (self), self->sinkpad);
181 
182   self->srcpad = gst_pad_new_from_static_template (&sf_dec_src_factory, "src");
183   gst_pad_set_event_function (self->srcpad,
184       GST_DEBUG_FUNCPTR (gst_sf_dec_src_event));
185   gst_pad_set_query_function (self->srcpad,
186       GST_DEBUG_FUNCPTR (gst_sf_dec_src_query));
187   gst_element_add_pad (GST_ELEMENT (self), self->srcpad);
188 }
189 
190 static gboolean
gst_sf_dec_do_seek(GstSFDec * self,GstEvent * event)191 gst_sf_dec_do_seek (GstSFDec * self, GstEvent * event)
192 {
193   gdouble rate;
194   GstFormat format;
195   GstSeekFlags flags;
196   GstSeekType cur_type, stop_type;
197   gboolean flush;
198   gint64 cur, stop, pos;
199   GstSegment seg;
200   guint64 song_length = gst_util_uint64_scale_int (self->duration, GST_SECOND,
201       self->rate);
202 
203   gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
204       &stop_type, &stop);
205 
206   if (format != GST_FORMAT_TIME)
207     goto unsupported_format;
208 
209   /* FIXME: we should be using GstSegment for all this */
210   if (cur_type != GST_SEEK_TYPE_SET || stop_type != GST_SEEK_TYPE_NONE)
211     goto unsupported_type;
212 
213   if (stop_type == GST_SEEK_TYPE_NONE)
214     stop = GST_CLOCK_TIME_NONE;
215   if (!GST_CLOCK_TIME_IS_VALID (stop) && song_length > 0)
216     stop = song_length;
217 
218   cur = CLAMP (cur, -1, song_length);
219 
220   /* cur -> pos */
221   pos = gst_util_uint64_scale_int (cur, self->rate, GST_SECOND);
222   if ((pos = sf_seek (self->file, pos, SEEK_SET) == -1))
223     goto seek_failed;
224 
225   /* pos -> cur */
226   cur = gst_util_uint64_scale_int (pos, GST_SECOND, self->rate);
227 
228   GST_DEBUG_OBJECT (self, "seek to %" GST_TIME_FORMAT,
229       GST_TIME_ARGS ((guint64) cur));
230 
231   flush = ((flags & GST_SEEK_FLAG_FLUSH) == GST_SEEK_FLAG_FLUSH);
232 
233   if (flush) {
234     gst_pad_push_event (self->srcpad, gst_event_new_flush_start ());
235   } else {
236     gst_pad_stop_task (self->sinkpad);
237   }
238 
239   GST_PAD_STREAM_LOCK (self->sinkpad);
240 
241   if (flags & GST_SEEK_FLAG_SEGMENT) {
242     gst_element_post_message (GST_ELEMENT (self),
243         gst_message_new_segment_start (GST_OBJECT (self), format, cur));
244   }
245 
246   if (flush) {
247     gst_pad_push_event (self->srcpad, gst_event_new_flush_stop (TRUE));
248   }
249 
250   GST_LOG_OBJECT (self, "sending newsegment from %" GST_TIME_FORMAT "-%"
251       GST_TIME_FORMAT ", pos=%" GST_TIME_FORMAT,
252       GST_TIME_ARGS ((guint64) cur), GST_TIME_ARGS ((guint64) stop),
253       GST_TIME_ARGS ((guint64) cur));
254 
255   gst_segment_init (&seg, GST_FORMAT_TIME);
256   seg.rate = rate;
257   seg.start = cur;
258   seg.stop = stop;
259   seg.time = cur;
260   gst_pad_push_event (self->srcpad, gst_event_new_segment (&seg));
261 
262   gst_pad_start_task (self->sinkpad,
263       (GstTaskFunction) gst_sf_dec_loop, self, NULL);
264 
265   GST_PAD_STREAM_UNLOCK (self->sinkpad);
266 
267   return TRUE;
268 
269   /* ERROR */
270 unsupported_format:
271   {
272     GST_DEBUG_OBJECT (self, "seeking is only supported in TIME format");
273     return FALSE;
274   }
275 unsupported_type:
276   {
277     GST_DEBUG_OBJECT (self, "unsupported seek type");
278     return FALSE;
279   }
280 seek_failed:
281   {
282     GST_DEBUG_OBJECT (self, "seek failed");
283     return FALSE;
284   }
285 }
286 
287 static gboolean
gst_sf_dec_src_event(GstPad * pad,GstObject * parent,GstEvent * event)288 gst_sf_dec_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
289 {
290   GstSFDec *self = GST_SF_DEC (parent);
291   gboolean res = FALSE;
292 
293   GST_DEBUG_OBJECT (self, "event %s, %" GST_PTR_FORMAT,
294       GST_EVENT_TYPE_NAME (event), event);
295 
296   switch (GST_EVENT_TYPE (event)) {
297     case GST_EVENT_SEEK:
298       if (!self->file || !self->seekable)
299         goto done;
300       res = gst_sf_dec_do_seek (self, event);
301       break;
302     default:
303       res = gst_pad_event_default (pad, parent, event);
304       break;
305   }
306 done:
307   GST_DEBUG_OBJECT (self, "event %s: %d", GST_EVENT_TYPE_NAME (event), res);
308   return res;
309 }
310 
311 static gboolean
gst_sf_dec_src_query(GstPad * pad,GstObject * parent,GstQuery * query)312 gst_sf_dec_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
313 {
314   GstSFDec *self = GST_SF_DEC (parent);
315   GstFormat format;
316   gboolean res = FALSE;
317 
318   GST_DEBUG_OBJECT (self, "query %s, %" GST_PTR_FORMAT,
319       GST_QUERY_TYPE_NAME (query), query);
320 
321   switch (GST_QUERY_TYPE (query)) {
322     case GST_QUERY_DURATION:
323       if (!self->file)
324         goto done;
325       gst_query_parse_duration (query, &format, NULL);
326       if (format == GST_FORMAT_TIME) {
327         gst_query_set_duration (query, format,
328             gst_util_uint64_scale_int (self->duration, GST_SECOND, self->rate));
329         res = TRUE;
330       }
331       break;
332     case GST_QUERY_POSITION:
333       if (!self->file)
334         goto done;
335       gst_query_parse_position (query, &format, NULL);
336       if (format == GST_FORMAT_TIME) {
337         gst_query_set_position (query, format,
338             gst_util_uint64_scale_int (self->pos, GST_SECOND, self->rate));
339         res = TRUE;
340       }
341       break;
342     default:
343       res = gst_pad_query_default (pad, parent, query);
344       break;
345   }
346 
347 done:
348   GST_DEBUG_OBJECT (self, "query %s: %d", GST_QUERY_TYPE_NAME (query), res);
349   return res;
350 }
351 
352 static GstStateChangeReturn
gst_sf_dec_change_state(GstElement * element,GstStateChange transition)353 gst_sf_dec_change_state (GstElement * element, GstStateChange transition)
354 {
355   GstStateChangeReturn ret;
356   GstSFDec *self = GST_SF_DEC (element);
357 
358   GST_INFO_OBJECT (self, "transition: %s -> %s",
359       gst_element_state_get_name (GST_STATE_TRANSITION_CURRENT (transition)),
360       gst_element_state_get_name (GST_STATE_TRANSITION_NEXT (transition)));
361 
362   switch (transition) {
363     case GST_STATE_CHANGE_READY_TO_PAUSED:
364       gst_sf_dec_start (self);
365       break;
366     default:
367       break;
368   }
369 
370   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
371 
372   switch (transition) {
373     case GST_STATE_CHANGE_PAUSED_TO_READY:
374       gst_sf_dec_stop (self);
375       break;
376     default:
377       break;
378   }
379   return ret;
380 }
381 
382 static gboolean
gst_sf_dec_start(GstSFDec * self)383 gst_sf_dec_start (GstSFDec * self)
384 {
385   return TRUE;
386 }
387 
388 static gboolean
gst_sf_dec_stop(GstSFDec * self)389 gst_sf_dec_stop (GstSFDec * self)
390 {
391   int err = 0;
392 
393   GST_INFO_OBJECT (self, "Closing sndfile stream");
394 
395   if (self->file && (err = sf_close (self->file)))
396     goto close_failed;
397 
398   self->file = NULL;
399   self->offset = 0;
400   self->channels = 0;
401   self->rate = 0;
402 
403   self->pos = 0;
404   self->duration = 0;
405 
406   return TRUE;
407 
408 close_failed:
409   {
410     GST_ELEMENT_ERROR (self, RESOURCE, CLOSE,
411         ("Could not close sndfile stream."),
412         ("soundfile error: %s", sf_error_number (err)));
413     return FALSE;
414   }
415 }
416 
417 static gboolean
gst_sf_dec_sink_activate(GstPad * sinkpad,GstObject * parent)418 gst_sf_dec_sink_activate (GstPad * sinkpad, GstObject * parent)
419 {
420   GstQuery *query;
421   gboolean pull_mode;
422 
423   query = gst_query_new_scheduling ();
424 
425   if (!gst_pad_peer_query (sinkpad, query)) {
426     gst_query_unref (query);
427     goto activate_push;
428   }
429 
430   pull_mode = gst_query_has_scheduling_mode_with_flags (query,
431       GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
432   gst_query_unref (query);
433 
434   if (!pull_mode)
435     goto activate_push;
436 
437   GST_DEBUG_OBJECT (sinkpad, "activating pull");
438   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
439 
440 activate_push:
441   {
442     GST_DEBUG_OBJECT (sinkpad, "activating push");
443     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
444   }
445 }
446 
447 static gboolean
gst_sf_dec_sink_activate_mode(GstPad * sinkpad,GstObject * parent,GstPadMode mode,gboolean active)448 gst_sf_dec_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
449     GstPadMode mode, gboolean active)
450 {
451   gboolean res;
452 
453   switch (mode) {
454     case GST_PAD_MODE_PUSH:
455       res = FALSE;              /* no push support */
456       break;
457     case GST_PAD_MODE_PULL:
458       if (active) {
459         /* if we have a scheduler we can start the task */
460         GST_DEBUG_OBJECT (sinkpad, "start task");
461         res = gst_pad_start_task (sinkpad, (GstTaskFunction) gst_sf_dec_loop,
462             sinkpad, NULL);
463       } else {
464         res = gst_pad_stop_task (sinkpad);
465       }
466       break;
467     default:
468       res = FALSE;
469       break;
470   }
471   return res;
472 }
473 
474 static void
create_and_send_tags(GstSFDec * self,SF_INFO * info,SF_LOOP_INFO * loop_info,SF_INSTRUMENT * instrument)475 create_and_send_tags (GstSFDec * self, SF_INFO * info, SF_LOOP_INFO * loop_info,
476     SF_INSTRUMENT * instrument)
477 {
478   GstTagList *tags;
479   const gchar *tag;
480   const gchar *codec_name;
481 
482   /* send tags */
483   tags = gst_tag_list_new_empty ();
484   if ((tag = sf_get_string (self->file, SF_STR_TITLE)) && *tag) {
485     gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_TITLE, tag, NULL);
486   }
487   if ((tag = sf_get_string (self->file, SF_STR_COMMENT)) && *tag) {
488     gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_COMMENT, tag, NULL);
489   }
490   if ((tag = sf_get_string (self->file, SF_STR_ARTIST)) && *tag) {
491     gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_ARTIST, tag, NULL);
492   }
493   if ((tag = sf_get_string (self->file, SF_STR_ALBUM)) && *tag) {
494     gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_ALBUM, tag, NULL);
495   }
496   if ((tag = sf_get_string (self->file, SF_STR_GENRE)) && *tag) {
497     gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_GENRE, tag, NULL);
498   }
499   if ((tag = sf_get_string (self->file, SF_STR_COPYRIGHT)) && *tag) {
500     gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_COPYRIGHT, tag, NULL);
501   }
502   if ((tag = sf_get_string (self->file, SF_STR_LICENSE)) && *tag) {
503     gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_LICENSE, tag, NULL);
504   }
505   if ((tag = sf_get_string (self->file, SF_STR_SOFTWARE)) && *tag) {
506     gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_APPLICATION_NAME, tag,
507         NULL);
508   }
509   if ((tag = sf_get_string (self->file, SF_STR_TRACKNUMBER)) && *tag) {
510     guint track = atoi (tag);
511     gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_TRACK_NUMBER, track,
512         NULL);
513   }
514   if ((tag = sf_get_string (self->file, SF_STR_DATE)) && *tag) {
515     GValue tag_val = { 0, };
516     GType tag_type = gst_tag_get_type (GST_TAG_DATE_TIME);
517 
518     g_value_init (&tag_val, tag_type);
519     if (gst_value_deserialize (&tag_val, tag)) {
520       gst_tag_list_add_value (tags, GST_TAG_MERGE_APPEND, GST_TAG_DATE_TIME,
521           &tag_val);
522     } else {
523       GST_WARNING_OBJECT (self, "could not deserialize '%s' into a "
524           "tag %s of type %s", tag, GST_TAG_DATE_TIME, g_type_name (tag_type));
525     }
526     g_value_unset (&tag_val);
527   }
528   if (loop_info) {
529     if (loop_info->bpm != 0.0) {
530       gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_BEATS_PER_MINUTE,
531           (gdouble) loop_info->bpm, NULL);
532     }
533     if (loop_info->root_key != -1) {
534       gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_MIDI_BASE_NOTE,
535           (guint) loop_info->root_key, NULL);
536     }
537   }
538   if (instrument) {
539     gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE, GST_TAG_MIDI_BASE_NOTE,
540         (guint) instrument->basenote, NULL);
541   }
542   /* TODO: calculate bitrate: GST_TAG_BITRATE */
543   switch (info->format & SF_FORMAT_SUBMASK) {
544     case SF_FORMAT_PCM_S8:
545     case SF_FORMAT_PCM_16:
546     case SF_FORMAT_PCM_24:
547     case SF_FORMAT_PCM_32:
548     case SF_FORMAT_PCM_U8:
549       codec_name = "Uncompressed PCM audio";
550       break;
551     case SF_FORMAT_FLOAT:
552     case SF_FORMAT_DOUBLE:
553       codec_name = "Uncompressed IEEE float audio";
554       break;
555     case SF_FORMAT_ULAW:
556       codec_name = "µ-law audio";
557       break;
558     case SF_FORMAT_ALAW:
559       codec_name = "A-law audio";
560       break;
561     case SF_FORMAT_IMA_ADPCM:
562     case SF_FORMAT_MS_ADPCM:
563     case SF_FORMAT_VOX_ADPCM:
564     case SF_FORMAT_G721_32:
565     case SF_FORMAT_G723_24:
566     case SF_FORMAT_G723_40:
567       codec_name = "ADPCM audio";
568       break;
569     case SF_FORMAT_GSM610:
570       codec_name = "MS GSM audio";
571       break;
572     case SF_FORMAT_DWVW_12:
573     case SF_FORMAT_DWVW_16:
574     case SF_FORMAT_DWVW_24:
575     case SF_FORMAT_DWVW_N:
576       codec_name = "Delta Width Variable Word encoded audio";
577       break;
578     case SF_FORMAT_DPCM_8:
579     case SF_FORMAT_DPCM_16:
580       codec_name = "differential PCM audio";
581       break;
582     case SF_FORMAT_VORBIS:
583       codec_name = "Vorbis";
584       break;
585     default:
586       codec_name = NULL;
587       GST_WARNING_OBJECT (self, "unmapped codec_type: %d",
588           info->format & SF_FORMAT_SUBMASK);
589       break;
590   }
591   if (codec_name) {
592     gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_AUDIO_CODEC,
593         codec_name, NULL);
594   }
595 
596   if (!gst_tag_list_is_empty (tags)) {
597     GST_DEBUG_OBJECT (self, "have tags");
598     gst_pad_push_event (self->srcpad, gst_event_new_tag (tags));
599   } else {
600     gst_tag_list_unref (tags);
601   }
602 }
603 
604 static gboolean
is_valid_loop(gint mode,guint start,guint end)605 is_valid_loop (gint mode, guint start, guint end)
606 {
607   if (!end)
608     return FALSE;
609   if (start >= end)
610     return FALSE;
611   if (!mode)
612     return FALSE;
613 
614   return TRUE;
615 }
616 
617 static void
create_and_send_toc(GstSFDec * self,SF_INFO * info,SF_LOOP_INFO * loop_info,SF_INSTRUMENT * instrument)618 create_and_send_toc (GstSFDec * self, SF_INFO * info, SF_LOOP_INFO * loop_info,
619     SF_INSTRUMENT * instrument)
620 {
621   GstToc *toc;
622   GstTocEntry *entry = NULL, *subentry = NULL;
623   gint64 start, stop;
624   gchar *id;
625   gint i;
626   gboolean have_loops = FALSE;
627 
628   if (!instrument)
629     return;
630 
631   for (i = 0; i < 16; i++) {
632     if (is_valid_loop (instrument->loops[i].mode, instrument->loops[i].start,
633             instrument->loops[i].end)) {
634       have_loops = TRUE;
635       break;
636     }
637   }
638   if (!have_loops) {
639     GST_INFO_OBJECT (self, "Have no loops");
640     return;
641   }
642 
643 
644   toc = gst_toc_new (GST_TOC_SCOPE_GLOBAL);
645   GST_DEBUG_OBJECT (self, "have toc");
646 
647   /* add cue edition */
648   entry = gst_toc_entry_new (GST_TOC_ENTRY_TYPE_EDITION, "loops");
649   stop = gst_util_uint64_scale_int (self->duration, GST_SECOND, self->rate);
650   gst_toc_entry_set_start_stop_times (entry, 0, stop);
651   gst_toc_append_entry (toc, entry);
652 
653   for (i = 0; i < 16; i++) {
654     GST_DEBUG_OBJECT (self,
655         "loop[%2d]: mode=%d, start=%u, end=%u, count=%u", i,
656         instrument->loops[i].mode, instrument->loops[i].start,
657         instrument->loops[i].end, instrument->loops[i].count);
658     if (is_valid_loop (instrument->loops[i].mode, instrument->loops[i].start,
659             instrument->loops[i].end)) {
660       id = g_strdup_printf ("%08x", i);
661       subentry = gst_toc_entry_new (GST_TOC_ENTRY_TYPE_CHAPTER, id);
662       g_free (id);
663       start = gst_util_uint64_scale_int (instrument->loops[i].start,
664           GST_SECOND, self->rate);
665       stop = gst_util_uint64_scale_int (instrument->loops[i].end,
666           GST_SECOND, self->rate);
667       gst_toc_entry_set_start_stop_times (subentry, start, stop);
668       gst_toc_entry_append_sub_entry (entry, subentry);
669     }
670   }
671 
672   gst_pad_push_event (self->srcpad, gst_event_new_toc (toc, FALSE));
673 }
674 
675 static gboolean
gst_sf_dec_open_file(GstSFDec * self)676 gst_sf_dec_open_file (GstSFDec * self)
677 {
678   SF_INFO info = { 0, };
679   SF_LOOP_INFO loop_info = { 0, };
680   SF_INSTRUMENT instrument = { 0, };
681   GstCaps *caps;
682   GstStructure *s;
683   GstSegment seg;
684   gint width;
685   const gchar *format;
686   gchar *stream_id;
687   gboolean have_loop_info = FALSE;
688   gboolean have_instrument = FALSE;
689 
690   GST_DEBUG_OBJECT (self, "opening the stream");
691   if (!(self->file = sf_open_virtual (&gst_sf_vio, SFM_READ, &info, self)))
692     goto open_failed;
693 
694   stream_id =
695       gst_pad_create_stream_id (self->srcpad, GST_ELEMENT_CAST (self), NULL);
696   gst_pad_push_event (self->srcpad, gst_event_new_stream_start (stream_id));
697   g_free (stream_id);
698 
699   self->channels = info.channels;
700   self->rate = info.samplerate;
701   self->duration = info.frames;
702   self->seekable = info.seekable;
703   GST_DEBUG_OBJECT (self, "stream openend: channels=%d, rate=%d, seekable=%d",
704       info.channels, info.samplerate, info.seekable);
705 
706   /* negotiate srcpad caps */
707   if ((caps = gst_pad_get_allowed_caps (self->srcpad)) == NULL) {
708     caps = gst_pad_get_pad_template_caps (self->srcpad);
709   }
710   caps = gst_caps_make_writable (caps);
711   GST_DEBUG_OBJECT (self, "allowed caps %" GST_PTR_FORMAT, caps);
712 
713   s = gst_caps_get_structure (caps, 0);
714   gst_structure_set (s,
715       "channels", G_TYPE_INT, self->channels,
716       "rate", G_TYPE_INT, self->rate, NULL);
717 
718   if (!gst_structure_fixate_field_string (s, "format", GST_AUDIO_NE (S16)))
719     GST_WARNING_OBJECT (self, "Failed to fixate format to S16NE");
720 
721   caps = gst_caps_fixate (caps);
722 
723   GST_DEBUG_OBJECT (self, "fixated caps %" GST_PTR_FORMAT, caps);
724 
725   /* configure to output the negotiated format */
726   s = gst_caps_get_structure (caps, 0);
727   format = gst_structure_get_string (s, "format");
728   if (g_str_equal (format, GST_AUDIO_NE (S32))) {
729     self->reader = (GstSFReader) sf_readf_int;
730     width = 32;
731   } else if (g_str_equal (format, GST_AUDIO_NE (S16))) {
732     self->reader = (GstSFReader) sf_readf_short;
733     width = 16;
734   } else {
735     self->reader = (GstSFReader) sf_readf_float;
736     width = 32;
737   }
738   self->bytes_per_frame = width * self->channels / 8;
739 
740   gst_pad_set_caps (self->srcpad, caps);
741   gst_caps_unref (caps);
742 
743   /* push initial segment */
744   gst_segment_init (&seg, GST_FORMAT_TIME);
745   seg.stop = gst_util_uint64_scale_int (self->duration, GST_SECOND, self->rate);
746   gst_pad_push_event (self->srcpad, gst_event_new_segment (&seg));
747 
748   /* get extra details */
749   if (sf_command (self->file, SFC_GET_LOOP_INFO, &loop_info,
750           sizeof (loop_info))) {
751     GST_DEBUG_OBJECT (self, "have loop info");
752     have_loop_info = TRUE;
753   }
754   if (sf_command (self->file, SFC_GET_INSTRUMENT, &instrument,
755           sizeof (instrument))) {
756     GST_DEBUG_OBJECT (self, "have instrument");
757     have_instrument = TRUE;
758   }
759 
760   create_and_send_tags (self, &info, (have_loop_info ? &loop_info : NULL),
761       (have_instrument ? &instrument : NULL));
762 
763   create_and_send_toc (self, &info, (have_loop_info ? &loop_info : NULL),
764       (have_instrument ? &instrument : NULL));
765 
766   return TRUE;
767 
768 open_failed:
769   {
770     GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ,
771         (_("Could not open sndfile stream for reading.")),
772         ("soundfile error: %s", sf_strerror (NULL)));
773     return FALSE;
774   }
775 }
776 
777 static void
gst_sf_dec_loop(GstPad * pad)778 gst_sf_dec_loop (GstPad * pad)
779 {
780   GstSFDec *self = GST_SF_DEC (GST_PAD_PARENT (pad));
781   GstBuffer *buf;
782   GstMapInfo map;
783   GstFlowReturn flow;
784   sf_count_t frames_read;
785   guint num_frames = 1024;      /* arbitrary */
786 
787   if (G_UNLIKELY (!self->file)) {
788     /* not started yet */
789     if (!gst_sf_dec_open_file (self))
790       goto pause;
791   }
792 
793   buf = gst_buffer_new_and_alloc (self->bytes_per_frame * num_frames);
794   gst_buffer_map (buf, &map, GST_MAP_WRITE);
795   frames_read = self->reader (self->file, map.data, num_frames);
796   GST_LOG_OBJECT (self, "read %d / %d bytes = %d frames of audio",
797       (gint) frames_read, (gint) map.size, num_frames);
798   gst_buffer_unmap (buf, &map);
799 
800   if (G_UNLIKELY (frames_read < 0))
801     goto could_not_read;
802 
803   if (G_UNLIKELY (frames_read == 0))
804     goto eos;
805 
806   GST_BUFFER_OFFSET (buf) = self->offset;
807   GST_BUFFER_TIMESTAMP (buf) = gst_util_uint64_scale_int (self->offset,
808       GST_SECOND, self->rate);
809   self->offset += frames_read;
810   GST_BUFFER_DURATION (buf) = gst_util_uint64_scale_int (self->offset,
811       GST_SECOND, self->rate) - GST_BUFFER_TIMESTAMP (buf);
812 
813   flow = gst_pad_push (self->srcpad, buf);
814   if (flow != GST_FLOW_OK) {
815     GST_LOG_OBJECT (self, "pad push flow: %s", gst_flow_get_name (flow));
816     goto pause;
817   }
818 
819   return;
820 
821   /* ERROR */
822 could_not_read:
823   {
824     GST_ELEMENT_ERROR (self, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
825     gst_buffer_unref (buf);
826     goto pause;
827   }
828 eos:
829   {
830     GST_DEBUG_OBJECT (self, "EOS");
831     gst_buffer_unref (buf);
832     gst_pad_push_event (self->srcpad, gst_event_new_eos ());
833     goto pause;
834   }
835 pause:
836   {
837     GST_INFO_OBJECT (self, "Pausing");
838     gst_pad_pause_task (self->sinkpad);
839   }
840 }
841