forked from audacity/audacity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImportGStreamer.cpp
More file actions
1415 lines (1192 loc) · 41.9 KB
/
Copy pathImportGStreamer.cpp
File metadata and controls
1415 lines (1192 loc) · 41.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
Audacity: A Digital Audio Editor
ImportGStreamer.cpp
Copyright 2008 LRN
Based on ImportFFmpeg.cpp by LRN
Rework for gstreamer 1.0 by LLL
Licensed under the GNU General Public License v2 or later
*//****************************************************************//**
\class GStreamerImportFileHandle
\brief An ImportFileHandle for GStreamer data
*//****************************************************************//**
\class GStreamerImportPlugin
\brief An ImportPlugin for GStreamer data
*//*******************************************************************/
#include "../Audacity.h" // needed before GStreamer.h // for USE_* macros
#if defined(USE_GSTREAMER)
#include "ImportGStreamer.h"
#include <wx/window.h>
#include <wx/log.h>
#define DESC XO("GStreamer-compatible files")
// On Windows we don't have configure script to turn this on or off,
// so let's use msw-specific pragma to add required libraries.
// Of course, library search path still has to be updated manually
#if defined(__WXMSW__)
# pragma comment(lib,"gstreamer-1.0.lib")
# pragma comment(lib,"gstapp-1.0.lib")
# pragma comment(lib,"gstbase-1.0.lib")
# pragma comment(lib,"glib-2.0.lib")
# pragma comment(lib,"gobject-2.0.lib")
#endif
// all the includes live here by default
#include "../Tags.h"
#include "../WaveTrack.h"
extern "C"
{
// #include <gio/gio.h>
#include <gst/app/gstappsink.h>
#include <gst/audio/audio-format.h>
}
// Convenience macros
#define AUDCTX "audacity::context"
#define GETCTX(o) (GStreamContext *) g_object_get_data(G_OBJECT((o)), AUDCTX)
#define SETCTX(o, c) g_object_set_data(G_OBJECT((o)), AUDCTX, (gpointer) (c))
#define WARN(e, msg) GST_ELEMENT_WARNING((e), STREAM, FAILED, msg, (NULL));
// Capabilities that Audacity can handle
//
// This resolves to: (on little endian)
//
// "audio/x-raw, "
// "format = (string) {S16LE, S24_32LE, F32LE}, "
// "rate = (int) [ 1, max ]",
// "channels = (int) [ 1, max ]"
static GstStaticCaps supportedCaps =
GST_STATIC_CAPS(
GST_AUDIO_CAPS_MAKE(
"{"
GST_AUDIO_NE(S16) ", "
GST_AUDIO_NE(S24_32) ", "
GST_AUDIO_NE(F32)
"}"
)
);
struct g_mutex_locker
{
explicit g_mutex_locker(GMutex &mutex_)
: mutex(mutex_)
{
g_mutex_lock(&mutex);
}
~g_mutex_locker()
{
g_mutex_unlock(&mutex);
}
GMutex &mutex;
};
template<typename T, void(*Fn)(T*)> struct Deleter {
inline void operator() (void *p) const
{
if (p)
Fn(static_cast<T*>(p));
}
};
using GstString = std::unique_ptr < gchar, Deleter<void, g_free> > ;
using GErrorHandle = std::unique_ptr < GError, Deleter<GError, g_error_free> > ;
using ParseFn = void (*)(GstMessage *message, GError **gerror, gchar **debug);
inline void GstMessageParse(ParseFn fn, GstMessage *msg, GErrorHandle &err, GstString &debug)
{
GError *error;
gchar *string;
fn(msg, &error, &string);
err.reset(error);
debug.reset(string);
}
// Context used for private stream data
struct GStreamContext
{
GstElement *mConv{}; // Audio converter
GstElement *mSink{}; // Application sink
bool mUse{}; // True if this stream should be imported
NewChannelGroup mChannels; // Array of WaveTrack pointers, one for each channel
unsigned mNumChannels{}; // Number of channels
gdouble mSampleRate{}; // Sample rate
GstString mType; // Audio type
sampleFormat mFmt{ floatSample }; // Sample format
gint64 mPosition{}; // Start position of stream
gint64 mDuration{}; // Duration of stream
GstElement *mPipeline{};
GStreamContext() {}
~GStreamContext()
{
// Remove the appsink element
if (mSink)
{
gst_bin_remove(GST_BIN(mPipeline), mSink);
}
// Remove the audioconvert element
if (mConv)
{
gst_bin_remove(GST_BIN(mPipeline), mConv);
}
}
};
// For RAII on gst objects
template<typename T> using GstObjHandle =
std::unique_ptr < T, Deleter<void, gst_object_unref > > ;
///! Does actual import, returned by GStreamerImportPlugin::Open
class GStreamerImportFileHandle final : public ImportFileHandle
{
public:
GStreamerImportFileHandle(const wxString & name);
virtual ~GStreamerImportFileHandle();
///! Format initialization
///\return true if successful, false otherwise
bool Init();
TranslatableString GetFileDescription() override;
ByteCount GetFileUncompressedBytes() override;
///! Called by Import.cpp
///\return number of readable audio streams in the file
wxInt32 GetStreamCount() override;
///! Called by Import.cpp
///\return array of strings - descriptions of the streams
const TranslatableStrings &GetStreamInfo() override;
///! Called by Import.cpp
///\param index - index of the stream in mStreamInfo and mStreams arrays
///\param use - true if this stream should be imported, false otherwise
void SetStreamUsage(wxInt32 index, bool use) override;
///! Imports audio
///\return import status (see Import.cpp)
int Import(TrackFactory *trackFactory,
TrackHolders &outTracks,
Tags *tags) override;
// =========================================================================
// Handled within the gstreamer threads
// =========================================================================
///! Called when a pad-added signal comes in from UriDecodeBin
///\param pad - source pad of uridecodebin that will not be serving any data
void OnPadAdded(GstPad *pad);
///! Called when a pad-removed signal comes in from UriDecodeBin
///\param pad - source pad of uridecodebin that will not be serving any data
void OnPadRemoved(GstPad *pad);
///! Called when a message comes through GStreamer message bus
///\param success - will be set to true if successful
///\return true if the loop should be terminated
bool ProcessBusMessage(bool & success);
///! Called when a tag message comes in from the appsink
///\param appsink - Specific sink that received the message
///\param tags - List of tags
void OnTag(GstAppSink *appsink, GstTagList *tags);
///! Called when a NEW samples are queued
///\param c - stream context
///\param sample - gstreamer sample
void OnNewSample(GStreamContext *c, GstSample *sample);
private:
TranslatableStrings mStreamInfo; //!< Array of stream descriptions. Length is the same as mStreams
Tags mTags; //!< Tags to be passed back to Audacity
TrackFactory *mTrackFactory; //!< Factory to create tracks when samples arrive
GstString mUri; //!< URI of file
GstObjHandle<GstElement> mPipeline; //!< GStreamer pipeline
GstObjHandle<GstBus> mBus; //!< Message bus
GstElement *mDec; //!< uridecodebin element
bool mAsyncDone; //!< true = 1st async-done message received
GMutex mStreamsLock; //!< Mutex protecting the mStreams array
std::vector<std::unique_ptr<GStreamContext>> mStreams; //!< Array of pointers to stream contexts
};
/// A representative of GStreamer loader in
/// the Audacity import plugin list
class GStreamerImportPlugin final : public ImportPlugin
{
public:
///! Constructor
GStreamerImportPlugin();
///! Destructor
virtual ~GStreamerImportPlugin();
TranslatableString GetPluginFormatDescription() override;
wxString GetPluginStringID() override;
FileExtensions GetSupportedExtensions() override;
///! Probes the file and opens it if appropriate
std::unique_ptr<ImportFileHandle> Open(
const wxString &Filename, AudacityProject*) override;
};
// ============================================================================
// Initialization
// ============================================================================
// ----------------------------------------------------------------------------
// Instantiate GStreamerImportPlugin and add to the list of known importers
static
Importer::RegisteredImportPlugin{ "GStreamer",
[]() -> std::unique_ptr< ImportPlugin > {
wxLogMessage(_TS("Audacity is built against GStreamer version %d.%d.%d-%d"),
GST_VERSION_MAJOR,
GST_VERSION_MINOR,
GST_VERSION_MICRO,
GST_VERSION_NANO);
// Initialize gstreamer
GErrorHandle error;
bool initError;
{
int argc = 0;
char **argv = NULL;
GError *ee;
initError = !gst_init_check(&argc, &argv, &ee);
error.reset(ee);
}
if ( initError )
{
wxLogMessage(wxT("Failed to initialize GStreamer. Error %d: %s"),
error.get()->code,
wxString::FromUTF8(error.get()->message));
return {};
}
guint major, minor, micro, nano;
gst_version(&major, &minor, µ, &nano);
wxLogMessage(wxT("Linked to GStreamer version %d.%d.%d-%d"),
major,
minor,
micro,
nano);
// Instantiate plugin
auto plug = std::make_unique<GStreamerImportPlugin>();
// No supported extensions...no gstreamer plugins installed
if (plug->GetSupportedExtensions().size() == 0)
return {};
// Add to list of importers
return std::move(plug);
}() } registered;
// ============================================================================
// GStreamerImportPlugin Class
// ============================================================================
// ----------------------------------------------------------------------------
// Constructor
GStreamerImportPlugin::GStreamerImportPlugin()
: ImportPlugin( {} )
{
}
// ----------------------------------------------------------------------------
// Destructor
GStreamerImportPlugin::~GStreamerImportPlugin()
{
}
// ----------------------------------------------------------------------------
// Return the plugin description
TranslatableString
GStreamerImportPlugin::GetPluginFormatDescription()
{
return DESC;
}
// ----------------------------------------------------------------------------
// Return the plugin name
wxString
GStreamerImportPlugin::GetPluginStringID()
{
return wxT("gstreamer");
}
// Obtains a list of supported extensions from typefind factories
// TODO: improve the list. It is obviously incomplete.
FileExtensions
GStreamerImportPlugin::GetSupportedExtensions()
{
// We refresh the extensions each time this is called in case the
// user had installed additional gstreamer plugins while Audacity
// was active.
mExtensions.clear();
// Gather extensions from all factories that support audio
{
std::unique_ptr < GList, Deleter<GList, gst_plugin_feature_list_free> >
factories{ gst_type_find_factory_get_list() };
for (GList *list = factories.get(); list != NULL; list = g_list_next(list))
{
GstTypeFindFactory *factory = GST_TYPE_FIND_FACTORY(list->data);
// We need the capabilities to determine if it handles audio
GstCaps *caps = gst_type_find_factory_get_caps(factory);
if (!caps)
{
continue;
}
// Check each structure in the caps for audio
for (guint c = 0, clen = gst_caps_get_size(caps); c < clen; c++)
{
// Bypass if it isn't for audio
GstStructure *str = gst_caps_get_structure(caps, c);
if (!g_str_has_prefix(gst_structure_get_name(str), "audio"))
{
continue;
}
// This factory can handle audio, so get the extensions
const gchar *const *extensions = gst_type_find_factory_get_extensions(factory);
if (!extensions)
{
continue;
}
// Add each extension to the list
for (guint i = 0; extensions[i] != NULL; i++)
{
wxString extension = wxString::FromUTF8(extensions[i]);
if (mExtensions.Index(extension, false) == wxNOT_FOUND)
{
mExtensions.push_back(extension);
}
}
}
}
}
// Get them in a decent order
mExtensions.Sort();
// Log it for debugging
wxString extensions = wxT("Extensions:");
for (size_t i = 0; i < mExtensions.size(); i++)
{
extensions = extensions + wxT(" ") + mExtensions[i];
}
wxLogMessage(wxT("%s"), extensions);
return mExtensions;
}
// ----------------------------------------------------------------------------
// Open the file and return an importer "file handle"
std::unique_ptr<ImportFileHandle> GStreamerImportPlugin::Open(
const wxString &filename, AudacityProject*)
{
auto handle = std::make_unique<GStreamerImportFileHandle>(filename);
// Initialize the handle
if (!handle->Init())
{
return nullptr;
}
// This std::move is needed to "upcast" the pointer type
return std::move(handle);
}
// ============================================================================
// GStreamerImportFileHandle Class
// ============================================================================
// ----------------------------------------------------------------------------
// The following methods/functions run within gstreamer thread contexts. No
// interaction with wxWidgets should be allowed. See explanation at the top
// of this file.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Filter out any video streams
//
// LRN found that by doing this here, video streams aren't decoded thus
// reducing the time/processing needed to extract the audio streams.
//
// This "gint" is really GstAutoplugSelectResult enum
static gint
GStreamerAutoplugSelectCallback(GstElement * WXUNUSED(element),
GstPad * WXUNUSED(pad),
GstCaps * WXUNUSED(caps),
GstElementFactory *factory,
gpointer WXUNUSED(data))
{
// Check factory class
const gchar *fclass = gst_element_factory_get_klass(factory);
// Skip video decoding
if (g_strrstr(fclass,"Video"))
{
return 2; // GST_AUTOPLUG_SELECT_SKIP
}
return 0; // GST_AUTOPLUG_SELECT_TRY
}
// ----------------------------------------------------------------------------
// Handle the "pad-added" signal from uridecodebin
static void
GStreamerPadAddedCallback(GstElement * WXUNUSED(element),
GstPad *pad,
gpointer data)
{
((GStreamerImportFileHandle *) data)->OnPadAdded(pad);
return;
}
// ----------------------------------------------------------------------------
// Handle the "pad-removed" signal from uridecodebin
static void
GStreamerPadRemovedCallback(GstElement * WXUNUSED(element),
GstPad *pad,
gpointer data)
{
((GStreamerImportFileHandle *) data)->OnPadRemoved(pad);
return;
}
// ----------------------------------------------------------------------------
// Handle the "NEW-sample" signal from uridecodebin
inline void GstSampleUnref(GstSample *p) { gst_sample_unref(p); } // I can't use the static function name directly...
static GstFlowReturn
GStreamerNewSample(GstAppSink *appsink, gpointer data)
{
// Don't let C++ exceptions propagate through GStreamer
return GuardedCall< GstFlowReturn > ( [&] {
GStreamerImportFileHandle *handle = (GStreamerImportFileHandle *)data;
static GMutex mutex;
// Get the sample
std::unique_ptr < GstSample, Deleter< GstSample, GstSampleUnref> >
sample{ gst_app_sink_pull_sample(appsink) };
// We must single thread here to prevent concurrent use of the
// Audacity track functions.
g_mutex_locker locker{ mutex };
handle->OnNewSample(GETCTX(appsink), sample.get());
return GST_FLOW_OK;
}, MakeSimpleGuard(GST_FLOW_ERROR) );
}
// ----------------------------------------------------------------------------
// AppSink callbacks are used instead of signals to reduce processing
static GstAppSinkCallbacks AppSinkCallbacks =
{
NULL, // eos
NULL, // new_preroll
GStreamerNewSample // new_sample
};
static GstAppSinkCallbacks AppSinkBitBucket =
{
NULL, // eos
NULL, // new_preroll
NULL // new_sample
};
inline void GstCapsUnref(GstCaps *p) { gst_caps_unref(p); } // I can't use the static function name directly...
using GstCapsHandle = std::unique_ptr < GstCaps, Deleter<GstCaps, GstCapsUnref> >;
// ----------------------------------------------------------------------------
// Handle the "pad-added" message
void
GStreamerImportFileHandle::OnPadAdded(GstPad *pad)
{
GStreamContext *c{};
{
// Retrieve the stream caps...skip stream if unavailable
GstCaps *caps = gst_pad_get_current_caps(pad);
GstCapsHandle handle{ caps };
if (!caps)
{
WARN(mPipeline.get(), ("OnPadAdded: unable to retrieve stream caps"));
return;
}
// Get the caps structure...no need to release
GstStructure *str = gst_caps_get_structure(caps, 0);
if (!str)
{
WARN(mPipeline.get(), ("OnPadAdded: unable to retrieve caps structure"));
return;
}
// Only accept audio streams...no need to release
const gchar *name = gst_structure_get_name(str);
if (!g_strrstr(name, "audio"))
{
WARN(mPipeline.get(), ("OnPadAdded: bypassing '%s' stream", name));
return;
}
{
// Allocate a NEW stream context
auto uc = std::make_unique<GStreamContext>();
c = uc.get();
if (!c)
{
WARN(mPipeline.get(), ("OnPadAdded: unable to allocate stream context"));
return;
}
// Set initial state
c->mUse = true;
// Always add it to the context list to keep the number of contexts
// in sync with the number of streams
g_mutex_locker{ mStreamsLock };
// Pass the buck from uc
mStreams.push_back(std::move(uc));
}
c->mPipeline = mPipeline.get();
// Need pointer to context during pad removal (pad-remove signal)
SETCTX(pad, c);
// Save the stream's start time and duration
gst_pad_query_position(pad, GST_FORMAT_TIME, &c->mPosition);
gst_pad_query_duration(pad, GST_FORMAT_TIME, &c->mDuration);
// Retrieve the number of channels and validate
gint channels = -1;
gst_structure_get_int(str, "channels", &channels);
if (channels <= 0)
{
WARN(mPipeline.get(), ("OnPadAdded: channel count is invalid %d", channels));
return;
}
c->mNumChannels = channels;
// Retrieve the sample rate and validate
gint rate = -1;
gst_structure_get_int(str, "rate", &rate);
if (rate <= 0)
{
WARN(mPipeline.get(), ("OnPadAdded: sample rate is invalid %d", rate));
return;
}
c->mSampleRate = (double)rate;
c->mType.reset(g_strdup(name));
if (!c->mType)
{
WARN(mPipeline.get(), ("OnPadAdded: unable to allocate audio type"));
return;
}
// Done with capabilities
}
// Create audioconvert element
c->mConv = gst_element_factory_make("audioconvert", NULL);
if (!c->mConv)
{
WARN(mPipeline.get(), ("OnPadAdded: failed to create audioconvert element"));
return;
}
// Create appsink element
c->mSink = gst_element_factory_make("appsink", NULL);
if (!c->mSink)
{
WARN(mPipeline.get(), ("OnPadAdded: failed to create appsink element"));
return;
}
SETCTX(c->mSink, c);
// Set the appsink callbacks and add the context pointer
gst_app_sink_set_callbacks(GST_APP_SINK(c->mSink), &AppSinkCallbacks, this, NULL);
{
// Set the capabilities that we desire
GstCaps *caps = gst_static_caps_get(&supportedCaps);
GstCapsHandle handle{ caps };
if (!caps)
{
WARN(mPipeline.get(), ("OnPadAdded: failed to create static caps"));
return;
}
gst_app_sink_set_caps(GST_APP_SINK(c->mSink), caps);
}
// Do not sync to the clock...process as quickly as possible
gst_base_sink_set_sync(GST_BASE_SINK(c->mSink), FALSE);
// Don't drop buffers...allow queue to build unfettered
gst_app_sink_set_drop(GST_APP_SINK(c->mSink), FALSE);
// Add both elements to the pipeline
gst_bin_add_many(GST_BIN(mPipeline.get()), c->mConv, c->mSink, NULL);
// Link them together
if (!gst_element_link(c->mConv, c->mSink))
{
WARN(mPipeline.get(), ("OnPadAdded: failed to link audioconvert and appsink"));
return;
}
// Link the audiconvert sink pad to the src pad
GstPadLinkReturn ret = GST_PAD_LINK_OK;
{
GstObjHandle<GstPad> convsink{ gst_element_get_static_pad(c->mConv, "sink") };
if (convsink)
ret = gst_pad_link(pad, convsink.get());
if (!convsink || ret != GST_PAD_LINK_OK)
{
WARN(mPipeline.get(), ("OnPadAdded: failed to link uridecodebin to audioconvert - %d", ret));
return;
}
}
// Synchronize audioconvert state with parent
if (!gst_element_sync_state_with_parent(c->mConv))
{
WARN(mPipeline.get(), ("OnPadAdded: unable to sync audioconvert state"));
return;
}
// Synchronize appsink state with parent
if (!gst_element_sync_state_with_parent(c->mSink))
{
WARN(mPipeline.get(), ("OnPadAdded: unable to sync appaink state"));
return;
}
return;
}
// ----------------------------------------------------------------------------
// Process the "pad-removed" signal from uridecodebin
void
GStreamerImportFileHandle::OnPadRemoved(GstPad *pad)
{
GStreamContext *c = GETCTX(pad);
// Set audioconvert and appsink states to NULL
gst_element_set_state(c->mSink, GST_STATE_NULL);
gst_element_set_state(c->mConv, GST_STATE_NULL);
// Unlink audioconvert -> appsink
gst_element_unlink(c->mConv, c->mSink);
// Remove the pads from the pipeilne
gst_bin_remove_many(GST_BIN(mPipeline.get()), c->mConv, c->mSink, NULL);
// And reset context
c->mConv = NULL;
c->mSink = NULL;
return;
}
// ----------------------------------------------------------------------------
// Handle the "NEW-sample" message
void
GStreamerImportFileHandle::OnNewSample(GStreamContext *c, GstSample *sample)
{
// Allocate NEW tracks
//
// It is done here because, at least in the case of chained oggs,
// not all streams are known ahead of time.
if (c->mChannels.empty())
{
// Get the sample format...no need to release caps or structure
GstCaps *caps = gst_sample_get_caps(sample);
GstStructure *str = gst_caps_get_structure(caps, 0);
const gchar *fmt = gst_structure_get_string(str, "format");
if (!fmt)
{
WARN(mPipeline.get(), ("OnNewSample: missing audio format"));
return;
}
// Determinate sample format based on negotiated format
if (strcmp(fmt, GST_AUDIO_NE(S16)) == 0)
{
c->mFmt = int16Sample;
}
else if (strcmp(fmt, GST_AUDIO_NE(S24_32)) == 0)
{
c->mFmt = int24Sample;
}
else if (strcmp(fmt, GST_AUDIO_NE(F32)) == 0)
{
c->mFmt = floatSample;
}
else
{
// This shouldn't really happen since audioconvert will only give us
// the formats we said we could handle.
WARN(mPipeline.get(), ("OnNewSample: unrecognized sample format %s", fmt));
return;
}
// Allocate the track array
c->mChannels.resize(c->mNumChannels);
if (c->mChannels.size() != c->mNumChannels)
{
WARN(mPipeline.get(), ("OnNewSample: unable to allocate track array"));
return;
}
// Allocate all channels
for (int ch = 0; ch < c->mNumChannels; ch++)
{
// Create a track
c->mChannels[ch] = mTrackFactory->NewWaveTrack(c->mFmt, c->mSampleRate);
if (!c->mChannels[ch])
{
WARN(mPipeline.get(), ("OnNewSample: unable to create track"));
return;
}
}
}
// Get the buffer for the sample...no need to release
GstBuffer *buffer = gst_sample_get_buffer(sample);
if (!buffer)
{
// No buffer...not sure if this is an error or not,
// but we can't do anything else, so just bail silently.
return;
}
// Map the buffer
GstMapInfo info;
if (!gst_buffer_map(buffer, &info, GST_MAP_READ))
{
WARN(mPipeline.get(), ("OnNewSample: mapping buffer failed"));
return;
}
auto cleanup = finally([&]{
// Release buffer
gst_buffer_unmap(buffer, &info);
});
// Cache a few items
auto nChannels = c->mNumChannels;
sampleFormat fmt = c->mFmt;
samplePtr data = (samplePtr) info.data;
size_t samples = info.size / nChannels / SAMPLE_SIZE(fmt);
// Add sample data to tracks...depends on interleaved src data
for (int chn = 0; chn < nChannels; chn++)
{
// Append one channel
c->mChannels[chn]->Append(data,
fmt,
samples,
nChannels);
// Bump src to next channel
data += SAMPLE_SIZE(fmt);
}
return;
}
// ----------------------------------------------------------------------------
// The following methods run within the main thread.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Constructor
GStreamerImportFileHandle::GStreamerImportFileHandle(const wxString & name)
: ImportFileHandle(name)
{
mDec = NULL;
mTrackFactory = NULL;
mAsyncDone = false;
g_mutex_init(&mStreamsLock);
}
// ----------------------------------------------------------------------------
// Destructor
GStreamerImportFileHandle::~GStreamerImportFileHandle()
{
// Make sure the pipeline isn't running
if (mPipeline)
{
gst_element_set_state(mPipeline.get(), GST_STATE_NULL);
}
// Delete all of the contexts
if (mStreams.size())
{
// PRL: is the FIFO destruction order important?
// If not, then you could simply clear mStreams.
{
g_mutex_locker locker{ mStreamsLock };
while (mStreams.size() > 0)
{
// remove context from the array
mStreams.erase(mStreams.begin());
}
}
// Done with the context array
}
// Release the decoder
if (mDec != NULL)
{
gst_bin_remove(GST_BIN(mPipeline.get()), mDec);
}
g_mutex_clear(&mStreamsLock);
}
// ----------------------------------------------------------------------------
// Return number of readable audio streams in the file
wxInt32
GStreamerImportFileHandle::GetStreamCount()
{
return mStreamInfo.size();
}
// ----------------------------------------------------------------------------
// Return array of strings - descriptions of the streams
const TranslatableStrings &
GStreamerImportFileHandle::GetStreamInfo()
{
return mStreamInfo;
}
// ----------------------------------------------------------------------------
// Mark streams to process as selected by the user
void
GStreamerImportFileHandle::SetStreamUsage(wxInt32 index, bool use)
{
g_mutex_locker locker{ mStreamsLock };
if ((guint) index < mStreams.size())
{
GStreamContext *c = mStreams[index].get();
c->mUse = use;
}
}
// ----------------------------------------------------------------------------
// Initialize importer
bool
GStreamerImportFileHandle::Init()
{
// Create a URI from the filename
mUri.reset(g_strdup_printf("file:///%s", mFilename.ToUTF8().data()));
if (!mUri)
{
wxLogMessage(wxT("GStreamerImport couldn't create URI"));
return false;
}
// Create a pipeline
mPipeline.reset(gst_pipeline_new("pipeline"));
// Get its bus
mBus.reset(gst_pipeline_get_bus(GST_PIPELINE(mPipeline.get())));
// Create uridecodebin and set up signal handlers
mDec = gst_element_factory_make("uridecodebin", "decoder");
g_signal_connect(mDec, "autoplug-select", G_CALLBACK(GStreamerAutoplugSelectCallback), (gpointer) this);
g_signal_connect(mDec, "pad-added", G_CALLBACK(GStreamerPadAddedCallback), (gpointer) this);
g_signal_connect(mDec, "pad-removed", G_CALLBACK(GStreamerPadRemovedCallback), (gpointer) this);
// Set the URI
g_object_set(G_OBJECT(mDec), "uri", mUri, NULL);
// Add the decoder to the pipeline
if (!gst_bin_add(GST_BIN(mPipeline.get()), mDec))
{
AudacityMessageBox(
XO("Unable to add decoder to pipeline"),
XO("GStreamer Importer"));
// Cleanup expected to occur in destructor
return false;
}
// Run the pipeline
GstStateChangeReturn state = gst_element_set_state(mPipeline.get(), GST_STATE_PAUSED);
if (state == GST_STATE_CHANGE_FAILURE)
{
AudacityMessageBox(
XO("Unable to set stream state to paused."),
XO("GStreamer Importer"));
return false;
}
// Collect info while the stream is prerolled
//
// Unfortunately, for some files this may cause a slight "pause" in the GUI
// without a progress dialog appearing. Not much can be done about it other
// than throwing up an additional progress dialog and displaying two dialogs
// may be confusing to the users.
// Process messages until we get an error or the ASYNC_DONE message is received
bool success;
while (ProcessBusMessage(success) && success)
{
// Give wxWidgets a chance to do housekeeping
wxSafeYield();
}
// Build the stream info array
g_mutex_locker locker{ mStreamsLock };
for (guint i = 0; i < mStreams.size(); i++)
{
GStreamContext *c = mStreams[i].get();
// Create stream info string
auto strinfo = XO("Index[%02d], Type[%s], Channels[%d], Rate[%d]")
.Format(
(unsigned int) i,
wxString::FromUTF8(c->mType.get()),
(int) c->mNumChannels,
(int) c->mSampleRate );
mStreamInfo.push_back(strinfo);
}
return success;
}
// ----------------------------------------------------------------------------
// Return file dialog filter description
TranslatableString