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