summaryrefslogtreecommitdiff
path: root/examples/recorder/main.cpp
blob: 66c31a4b93fc68ef5519d03eecb9796cabbad56f (plain)
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
/*
    Copyright (C) 2011 Collabora Ltd.
      @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "ui_recorder.h"

#include <QtCore/QDir>
#include <QtGui/QApplication>
#include <QtGui/QDialog>
#include <QtGui/QMessageBox>

#include <QGlib/Error>
#include <QGlib/Connect>
#include <QGst/Init>
#include <QGst/ElementFactory>
#include <QGst/ChildProxy>
#include <QGst/PropertyProbe>
#include <QGst/Pipeline>
#include <QGst/Pad>
#include <QGst/Event>
#include <QGst/Message>
#include <QGst/Bus>

#ifdef Q_WS_X11
# include <QtGui/QX11Info>
#endif


class Recorder : public QDialog
{
    Q_OBJECT
public:
    Recorder(QWidget *parent = 0);

private:
    enum Device { AudioSrc, VideoSrc };
    void findDevices(Device device);
    void probeForDevices(const QGst::PropertyProbePtr & propertyProbe);

    QGst::BinPtr createAudioSrcBin();
    QGst::BinPtr createVideoSrcBin();

    void start();
    void stop();

    void onBusMessage(const QGst::MessagePtr & message);

private Q_SLOTS:
    void on_startStopButton_clicked();

private:
    Ui::Recorder m_ui;
    QGst::PropertyProbePtr m_audioProbe;
    QGst::PropertyProbePtr m_videoProbe;
    QGst::PipelinePtr m_pipeline;
};

Recorder::Recorder(QWidget *parent)
    : QDialog(parent)
{
    m_ui.setupUi(this);

    //setup the device combo boxes
    findDevices(AudioSrc);
    findDevices(VideoSrc);

    QGst::ElementFactoryPtr ximagesrc = QGst::ElementFactory::find("ximagesrc");
    if (!ximagesrc) {
        //if we don't have ximagesrc, disable the choice to use it
        m_ui.videoSourceComboBox->removeItem(1);
    } else {
#ifdef Q_WS_X11
        //setup the default screen to be the screen that this dialog is shown
        m_ui.displayNumSpinBox->setValue(QX11Info::appScreen());
#endif
    }

    //set default output file
    m_ui.outputFileEdit->setText(QDir::currentPath() + QDir::separator() + "out.ogv");
}

void Recorder::findDevices(Device device)
{
    const char *srcElementName = (device == AudioSrc) ? "autoaudiosrc" : "autovideosrc";
    QGst::ElementPtr src = QGst::ElementFactory::make(srcElementName);

    if (!src) {
        QMessageBox::critical(this, tr("Error"),
                              tr("Failed to create element \"%1\". Make sure you have "
                                 "gstreamer-plugins-good installed").arg(srcElementName));
        return;
    }

    QGst::PropertyProbePtr propertyProbe;

    //autoaudiosrc and autovideosrc implement the child proxy interface
    //and create the correct child element when they go to the READY state
    src->setState(QGst::StateReady);
    QGst::ChildProxyPtr childProxy = src.dynamicCast<QGst::ChildProxy>();
    if (childProxy && childProxy->childrenCount() > 0) {
        //the actual source is the first child
        //this source usually implements the property probe interface
        propertyProbe = childProxy->childByIndex(0).dynamicCast<QGst::PropertyProbe>();
    }
    //we got a reference to the underlying propertyProbe, so we don't need src anymore.
    src->setState(QGst::StateNull);

    //Most sources and sinks have a "device" property which supports probe
    //and probing it returns all the available devices on the system.
    //Here we try to make use of that to list the system's devices
    //and if it fails, we just leave the source to use its default device.
    if (propertyProbe && propertyProbe->propertySupportsProbe("device")) {
        ((device == AudioSrc) ? m_audioProbe : m_videoProbe) = propertyProbe;
        probeForDevices(propertyProbe);

        //this signal will notify us when devices change
        QGlib::connect(propertyProbe, "probe-needed",
                       this, &Recorder::probeForDevices, QGlib::PassSender);
    } else {
        QComboBox *box = (device == AudioSrc) ? m_ui.audioDeviceComboBox : m_ui.videoDeviceComboBox;
        box->addItem(tr("Default"));
    }
}

void Recorder::probeForDevices(const QGst::PropertyProbePtr & propertyProbe)
{
    QComboBox *box = (propertyProbe == m_audioProbe) ?
                     m_ui.audioDeviceComboBox : m_ui.videoDeviceComboBox;

    box->clear();
    box->addItem(tr("Default"));

    //get a list of devices that the element supports
    QList<QGlib::Value> devices = propertyProbe->probeAndGetValues("device");

    Q_FOREACH(const QGlib::Value & device, devices) {
        //set the element's device to the current device and retrieve its
        //human-readable name through the "device-name" property
        propertyProbe->setProperty("device", device);
        QString deviceName = propertyProbe->property("device-name").toString();

        //add the device on the combobox
        box->addItem(QString("%1 (%2)").arg(deviceName, device.toString()),
                     device.toString());
    }
}

QGst::BinPtr Recorder::createAudioSrcBin()
{
    QGst::BinPtr audioBin;

    try {
        audioBin = QGst::Bin::fromDescription("autoaudiosrc name=\"audiosrc\" ! audioconvert ! "
                                              "audioresample ! audiorate ! speexenc ! queue");
    } catch (const QGlib::Error & error) {
        qCritical() << "Failed to create audio source bin:" << error;
        return QGst::BinPtr();
    }

    //set the source's properties
    QVariant device = m_ui.audioDeviceComboBox->itemData(m_ui.audioDeviceComboBox->currentIndex());
    if (device.isValid()) {
        QGst::ElementPtr src = audioBin->getElementByName("audiosrc");

        //autoaudiosrc creates the actual source in the READY state
        src->setState(QGst::StateReady);

        QGst::ChildProxyPtr childProxy = src.dynamicCast<QGst::ChildProxy>();
        if (childProxy && childProxy->childrenCount() > 0) {
            //the actual source is the first child
            QGst::ObjectPtr realSrc = childProxy->childByIndex(0);
            realSrc->setProperty("device", device.toString());
        }
    }

    return audioBin;
}

QGst::BinPtr Recorder::createVideoSrcBin()
{
    QGst::BinPtr videoBin;

    try {
        if (m_ui.videoSourceComboBox->currentIndex() == 0) { //camera
            videoBin = QGst::Bin::fromDescription("autovideosrc name=\"videosrc\" ! "
                                                  "ffmpegcolorspace ! theoraenc ! queue");
        } else { //screencast
            videoBin = QGst::Bin::fromDescription("ximagesrc name=\"videosrc\" ! "
                                                  "ffmpegcolorspace ! theoraenc ! queue");
        }
    } catch (const QGlib::Error & error) {
        qCritical() << "Failed to create video source bin:" << error;
        return QGst::BinPtr();
    }

    //set the source's properties
    if (m_ui.videoSourceComboBox->currentIndex() == 0) { //camera
        QVariant device = m_ui.videoDeviceComboBox->itemData(m_ui.videoDeviceComboBox->currentIndex());
        if (device.isValid()) {
            QGst::ElementPtr src = videoBin->getElementByName("videosrc");

            //autovideosrc creates the actual source in the READY state
            src->setState(QGst::StateReady);

            QGst::ChildProxyPtr childProxy = src.dynamicCast<QGst::ChildProxy>();
            if (childProxy && childProxy->childrenCount() > 0) {
                //the actual source is the first child
                QGst::ObjectPtr realSrc = childProxy->childByIndex(0);
                realSrc->setProperty("device", device.toString());
            }
        }
    } else { //screencast
        videoBin->getElementByName("videosrc")->setProperty("screen-num", m_ui.displayNumSpinBox->value());
    }

    return videoBin;
}

void Recorder::start()
{
    QGst::BinPtr audioSrcBin = createAudioSrcBin();
    QGst::BinPtr videoSrcBin = createVideoSrcBin();
    QGst::ElementPtr mux = QGst::ElementFactory::make("oggmux");
    QGst::ElementPtr sink = QGst::ElementFactory::make("filesink");

    if (!audioSrcBin || !videoSrcBin || !mux || !sink) {
        QMessageBox::critical(this, tr("Error"), tr("One or more elements could not be created. "
                              "Verify that you have all the necessary element plugins installed."));
        return;
    }

    sink->setProperty("location", m_ui.outputFileEdit->text());

    m_pipeline = QGst::Pipeline::create();
    m_pipeline->add(audioSrcBin, videoSrcBin, mux, sink);

    //link elements
    QGst::PadPtr audioPad = mux->getRequestPad("sink_%d");
    audioSrcBin->getStaticPad("src")->link(audioPad);

    QGst::PadPtr videoPad = mux->getRequestPad("sink_%d");
    videoSrcBin->getStaticPad("src")->link(videoPad);

    mux->link(sink);

    //connect the bus
    m_pipeline->bus()->addSignalWatch();
    QGlib::connect(m_pipeline->bus(), "message", this, &Recorder::onBusMessage);

    //go!
    m_pipeline->setState(QGst::StatePlaying);
    m_ui.startStopButton->setText(tr("Stop recording"));
}

void Recorder::stop()
{
    //stop recording
    m_pipeline->setState(QGst::StateNull);

    //clear the pointer, destroying the pipeline as its reference count drops to zero.
    m_pipeline.clear();

    //restore the button's text
    m_ui.startStopButton->setText(tr("Start recording"));
}

void Recorder::onBusMessage(const QGst::MessagePtr & message)
{
    switch (message->type()) {
    case QGst::MessageEos:
        //got end-of-stream - stop the pipeline
        stop();
        break;
    case QGst::MessageError:
        //check if the pipeline exists before destroying it,
        //as we might get multiple error messages
        if (m_pipeline) {
            stop();
        }
        QMessageBox::critical(this, tr("Pipeline Error"),
                              message.staticCast<QGst::ErrorMessage>()->error().message());
        break;
    default:
        break;
    }
}

void Recorder::on_startStopButton_clicked()
{
    if (m_pipeline) { //pipeline exists - destroy it
        //send an end-of-stream event to flush metadata and cause an EosMessage to be delivered
        m_pipeline->sendEvent(QGst::EosEvent::create());
    } else { //pipeline doesn't exist - start a new one
        start();
    }
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QGst::init(&argc, &argv);

    Recorder r;
    r.show();

    return app.exec();
}

#include "recorder.moc"