]> git.sesse.net Git - kdenlive/blob - src/mltdevicecapture.cpp
Bring back overlay & effects in stopmotion widget, rewrite of decklink capture to...
[kdenlive] / src / mltdevicecapture.cpp
1 /***************************************************************************
2                         mltdevicecapture.cpp  -  description
3                            -------------------
4    begin                : Sun May 21 2011
5    copyright            : (C) 2011 by Jean-Baptiste Mardelle (jb@kdenlive.org)
6
7 ***************************************************************************/
8
9 /***************************************************************************
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU General Public License as published by  *
13  *   the Free Software Foundation; either version 2 of the License, or     *
14  *   (at your option) any later version.                                   *
15  *                                                                         *
16  ***************************************************************************/
17
18
19 #include "mltdevicecapture.h"
20 #include "kdenlivesettings.h"
21 #include "definitions.h"
22 //#include "recmonitor.h"
23 //#include "renderer.h"
24 #include "blackmagic/devices.h"
25
26 #include <mlt++/Mlt.h>
27
28 #include <KDebug>
29 #include <KStandardDirs>
30 #include <KMessageBox>
31 #include <KLocale>
32 #include <KTemporaryFile>
33
34 #include <QTimer>
35 #include <QDir>
36 #include <QString>
37 #include <QApplication>
38
39 #include <cstdlib>
40 #include <cstdarg>
41
42 #include <QDebug>
43
44
45
46 static void consumer_gl_frame_show(mlt_consumer, MltDeviceCapture * self, mlt_frame frame_ptr)
47 {
48     // detect if the producer has finished playing. Is there a better way to do it?
49     Mlt::Frame frame(frame_ptr);
50     self->showFrame(frame);
51 }
52
53 static void rec_consumer_frame_show(mlt_consumer, MltDeviceCapture * self, mlt_frame frame_ptr)
54 {
55     Mlt::Frame frame(frame_ptr);
56     if (!frame.is_valid()) return;
57     self->gotCapturedFrame(frame);
58 }
59
60 static void rec_consumer_frame_preview(mlt_consumer, MltDeviceCapture * self, mlt_frame frame_ptr)
61 {
62     Mlt::Frame frame(frame_ptr);
63     if (!frame.is_valid()) return;
64     if (self->sendFrameForAnalysis && frame_ptr->convert_image) {
65         self->emitFrameUpdated(frame);
66     }
67     if (self->doCapture > 0) {
68         self->doCapture --;
69         if (self->doCapture == 0) self->saveFrame(frame);
70     }
71
72 /*    if (self->analyseAudio) {
73         self->showAudio(frame);
74     }
75     if (frame.get_double("_speed") == 0.0) {
76         self->emitConsumerStopped();
77     } else if (frame.get_double("_speed") < 0.0 && mlt_frame_get_position(frame_ptr) <= 0) {
78         self->pause();
79         self->emitConsumerStopped();
80     }*/
81 }
82
83
84 MltDeviceCapture::MltDeviceCapture(QString profile, VideoPreviewContainer *surface, QWidget *parent) :
85     AbstractRender(parent),
86     doCapture(0),
87     sendFrameForAnalysis(false),
88     m_mltConsumer(NULL),
89     m_mltProducer(NULL),
90     m_mltProfile(NULL),
91     m_captureDisplayWidget(surface),
92     m_winid((int) surface->winId()),
93     m_analyseAudio(KdenliveSettings::monitor_audio())
94 {
95     if (profile.isEmpty()) profile = KdenliveSettings::current_profile();
96     buildConsumer(profile);
97 }
98
99 MltDeviceCapture::~MltDeviceCapture()
100 {
101     if (m_mltConsumer) delete m_mltConsumer;
102     if (m_mltProducer) delete m_mltProducer;
103     if (m_mltProfile) delete m_mltProfile;
104 }
105
106 void MltDeviceCapture::buildConsumer(const QString &profileName)
107 {
108     if (!profileName.isEmpty()) m_activeProfile = profileName;
109
110     if (m_mltProfile) delete m_mltProfile;
111
112     char *tmp = qstrdup(m_activeProfile.toUtf8().constData());
113     setenv("MLT_PROFILE", tmp, 1);
114     m_mltProfile = new Mlt::Profile(tmp);
115     m_mltProfile->get_profile()->is_explicit = 1;
116     delete[] tmp;
117
118     QString videoDriver = KdenliveSettings::videodrivername();
119     if (!videoDriver.isEmpty()) {
120         if (videoDriver == "x11_noaccel") {
121             setenv("SDL_VIDEO_YUV_HWACCEL", "0", 1);
122             videoDriver = "x11";
123         } else {
124             unsetenv("SDL_VIDEO_YUV_HWACCEL");
125         }
126     }
127     setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
128
129     if (m_winid == 0) {
130         // OpenGL monitor
131         m_mltConsumer = new Mlt::Consumer(*m_mltProfile, "sdl_audio");
132         m_mltConsumer->set("preview_off", 1);
133         m_mltConsumer->set("preview_format", mlt_image_rgb24a);
134         m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_gl_frame_show);
135     } else {
136         m_mltConsumer = new Mlt::Consumer(*m_mltProfile, "sdl_preview");
137         m_mltConsumer->set("window_id", m_winid);
138     }
139     m_mltConsumer->set("resize", 1);
140     //m_mltConsumer->set("terminate_on_pause", 1);
141     m_mltConsumer->set("window_background", KdenliveSettings::window_background().name().toUtf8().constData());
142     m_mltConsumer->set("rescale", "nearest");
143     
144     m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) rec_consumer_frame_preview);
145
146     QString audioDevice = KdenliveSettings::audiodevicename();
147     if (!audioDevice.isEmpty())
148         m_mltConsumer->set("audio_device", audioDevice.toUtf8().constData());
149
150     if (!videoDriver.isEmpty())
151         m_mltConsumer->set("video_driver", videoDriver.toUtf8().constData());
152
153     QString audioDriver = KdenliveSettings::audiodrivername();
154
155     if (!audioDriver.isEmpty())
156         m_mltConsumer->set("audio_driver", audioDriver.toUtf8().constData());
157
158     //m_mltConsumer->set("progressive", 1);
159     //m_mltConsumer->set("buffer", 1);
160     //m_mltConsumer->set("real_time", 0);
161 }
162
163 void MltDeviceCapture::stop()
164 {
165     bool isPlaylist = false;
166     if (m_mltConsumer) {
167         m_mltConsumer->set("refresh", 0);
168         m_mltConsumer->stop();
169         //if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
170     }
171     if (m_mltProducer) {
172         QList <Mlt::Producer *> prods;
173         Mlt::Service service(m_mltProducer->parent().get_service());
174         mlt_service_lock(service.get_service());
175         if (service.type() == tractor_type) {
176             isPlaylist = true;
177             Mlt::Tractor tractor(service);
178             mlt_tractor_close(tractor.get_tractor());
179             Mlt::Field *field = tractor.field();
180             mlt_service nextservice = mlt_service_get_producer(service.get_service());
181             mlt_service nextservicetodisconnect;
182             mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
183             QString mlt_type = mlt_properties_get(properties, "mlt_type");
184             QString resource = mlt_properties_get(properties, "mlt_service");
185             // Delete all transitions
186             while (mlt_type == "transition") {
187                 nextservicetodisconnect = nextservice;
188                 nextservice = mlt_service_producer(nextservice);
189                 mlt_field_disconnect_service(field->get_field(), nextservicetodisconnect);
190                 if (nextservice == NULL) break;
191                 properties = MLT_SERVICE_PROPERTIES(nextservice);
192                 mlt_type = mlt_properties_get(properties, "mlt_type");
193                 resource = mlt_properties_get(properties, "mlt_service");
194             }
195             for (int trackNb = tractor.count() - 1; trackNb >= 0; --trackNb) {
196                 Mlt::Producer trackProducer(tractor.track(trackNb));
197                 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
198                 if (trackPlaylist.type() == playlist_type) {
199                     for (int i = 0; i < trackPlaylist.count();i++) {
200                         // We need to manually decrease the ref count and close the producer, otherwise
201                         // the video4linux device stays open, seems like a bug in MLT that is not cleaning properly
202                         mlt_properties props = MLT_PRODUCER_PROPERTIES(trackPlaylist.get_clip(i)->get_parent());
203                         while (mlt_properties_ref_count(props) > 0) mlt_properties_dec_ref(props);
204                         if (trackPlaylist.get_clip(i)) mlt_producer_close(trackPlaylist.get_clip(i)->get_parent());
205                     }
206                     mlt_playlist_close(trackPlaylist.get_playlist());
207                     //trackPlaylist.clear();
208                 }
209             }
210             delete field;
211             field = NULL;
212         }
213         mlt_service_unlock(service.get_service());
214         delete m_mltProducer;
215         m_mltProducer = NULL;
216     }
217     // For some reason, the consumer seems to be deleted by previous stuff when in playlist mode
218     if (!isPlaylist) delete m_mltConsumer;
219     m_mltConsumer = NULL;
220 }
221
222
223 void MltDeviceCapture::doRefresh()
224 {
225     if (m_mltConsumer) m_mltConsumer->set("refresh", 1);
226 }
227
228
229 void MltDeviceCapture::emitFrameUpdated(Mlt::Frame& frame)
230 {
231     mlt_image_format format = mlt_image_rgb24a;
232     int width = 0;
233     int height = 0;
234     const uchar* image = frame.get_image(format, width, height);
235     QImage qimage(width, height, QImage::Format_ARGB32);
236     memcpy(qimage.bits(), image, width * height * 4);
237     emit frameUpdated(qimage.rgbSwapped());
238 }
239
240 void MltDeviceCapture::showFrame(Mlt::Frame& frame)
241 {
242     mlt_image_format format = mlt_image_rgb24a;
243     int width = 0;
244     int height = 0;
245     const uchar* image = frame.get_image(format, width, height);
246     QImage qimage(width, height, QImage::Format_ARGB32_Premultiplied);
247     memcpy(qimage.scanLine(0), image, width * height * 4);
248     emit showImageSignal(qimage);
249     if (m_analyseAudio) showAudio(frame);
250     if (sendFrameForAnalysis && frame.get_frame()->convert_image) {
251         emit frameUpdated(qimage.rgbSwapped());
252     }
253 }
254
255 void MltDeviceCapture::showAudio(Mlt::Frame& frame)
256 {
257     if (!frame.is_valid() || frame.get_int("test_audio") != 0) {
258         return;
259     }
260     mlt_audio_format audio_format = mlt_audio_s16;
261     int freq = 0;
262     int num_channels = 0;
263     int samples = 0;
264     int16_t* data = (int16_t*)frame.get_audio(audio_format, freq, num_channels, samples);
265
266     if (!data) {
267         return;
268     }
269
270     // Data format: [ c00 c10 c01 c11 c02 c12 c03 c13 ... c0{samples-1} c1{samples-1} for 2 channels.
271     // So the vector is of size samples*channels.
272     QVector<int16_t> sampleVector(samples*num_channels);
273     memcpy(sampleVector.data(), data, samples*num_channels*sizeof(int16_t));
274
275     if (samples > 0) {
276         emit audioSamplesSignal(sampleVector, freq, num_channels, samples);
277     }
278 }
279
280 bool MltDeviceCapture::slotStartPreview(const QString &producer, bool xmlFormat)
281 {
282     if (m_mltConsumer == NULL) buildConsumer();
283     char *tmp = qstrdup(producer.toUtf8().constData());
284     if (xmlFormat) m_mltProducer = new Mlt::Producer(*m_mltProfile, "xml-string", tmp);
285     else m_mltProducer = new Mlt::Producer(*m_mltProfile, tmp);
286     delete[] tmp;
287
288     if (m_mltProducer == NULL || !m_mltProducer->is_valid()) {
289         kDebug()<<"//// ERROR CREATRING PROD";
290         return false;
291     }
292     m_mltConsumer->connect(*m_mltProducer);
293     if (m_mltConsumer->start() == -1) {
294         delete m_mltConsumer;
295         m_mltConsumer = NULL;
296         return 0;
297     }
298     return 1;
299 }
300
301 void MltDeviceCapture::gotCapturedFrame(Mlt::Frame& frame)
302 {
303     mlt_image_format format = mlt_image_rgb24a;
304     int width = 0;
305     int height = 0;
306     const uchar* image = frame.get_image(format, width, height);
307     QImage qimage(width, height, QImage::Format_ARGB32);
308     memcpy(qimage.bits(), image, width * height * 4);
309     m_captureDisplayWidget->setImage(qimage.rgbSwapped());
310 }
311
312 void MltDeviceCapture::saveFrame(Mlt::Frame& frame)
313 {
314     mlt_image_format format = mlt_image_rgb24a;
315     int width = 0;
316     int height = 0;
317     const uchar* image = frame.get_image(format, width, height);
318     QImage qimage(width, height, QImage::Format_ARGB32);
319     memcpy(qimage.bits(), image, width * height * 4);
320
321     // Re-enable overlay
322     Mlt::Service service(m_mltProducer->parent().get_service());
323     Mlt::Tractor tractor(service);
324     Mlt::Producer trackProducer(tractor.track(0));
325     trackProducer.set("hide", 0);
326     
327     qimage.rgbSwapped().save(m_capturePath);
328     emit frameSaved(m_capturePath);
329     m_capturePath.clear();
330 }
331
332 void MltDeviceCapture::captureFrame(const QString &path)
333 {
334     if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
335
336     // Hide overlay track before doing the capture
337     Mlt::Service service(m_mltProducer->parent().get_service());
338     Mlt::Tractor tractor(service);
339     Mlt::Producer trackProducer(tractor.track(0));
340     mlt_service_lock(service.get_service());
341     trackProducer.set("hide", 1);
342     m_mltConsumer->purge();
343     mlt_service_unlock(service.get_service());
344     m_capturePath = path;
345     // Wait for 5 frames before capture to make sure overlay is gone
346     doCapture = 5;
347 }
348
349 bool MltDeviceCapture::slotStartCapture(const QString &params, const QString &path, const QString &playlist)
350 {
351     stop();
352     if (m_mltProfile) delete m_mltProfile;
353     char *tmp = qstrdup(m_activeProfile.toUtf8().constData());
354     m_mltProfile = new Mlt::Profile(tmp);
355     delete[] tmp;
356     m_mltProfile->get_profile()->is_explicit = 1;
357     kDebug()<<"-- CREATING CAP: "<<params<<", PATH: "<<path;
358     tmp = qstrdup(QString("avformat:" + path).toUtf8().constData());
359     m_mltConsumer = new Mlt::Consumer(*m_mltProfile, tmp);
360     m_mltConsumer->set("terminate_on_pause", 1);
361     delete[] tmp;
362
363     QStringList paramList = params.split(" ", QString::SkipEmptyParts);
364     char *tmp2;
365     for (int i = 0; i < paramList.count(); i++) {
366         tmp = qstrdup(paramList.at(i).section("=", 0, 0).toUtf8().constData());
367         tmp2 = qstrdup(paramList.at(i).section("=", 1, 1).toUtf8().constData());
368         m_mltConsumer->set(tmp, tmp2);
369         delete[] tmp;
370         delete[] tmp2;
371     }
372     
373     if (m_mltConsumer == NULL || !m_mltConsumer->is_valid()) {
374         if (m_mltConsumer) {
375             delete m_mltConsumer;
376             m_mltConsumer = NULL;
377         }
378         return false;
379     }
380     
381     // FIXME: the event object returned by the listen gets leaked...
382     m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) rec_consumer_frame_show);
383     tmp = qstrdup(playlist.toUtf8().constData());
384     m_mltProducer = new Mlt::Producer(*m_mltProfile, "xml-string", tmp);
385     delete[] tmp;
386
387     if (m_mltProducer == NULL || !m_mltProducer->is_valid()) {
388         kDebug()<<"//// ERROR CREATRING PROD";
389         return false;
390     }
391
392     m_mltConsumer->connect(*m_mltProducer);
393     if (m_mltConsumer->start() == -1) {
394         delete m_mltConsumer;
395         m_mltConsumer = NULL;
396         return 0;
397     }
398     return 1;
399 }
400
401
402 void MltDeviceCapture::setOverlay(const QString &path)
403 {
404     if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
405     Mlt::Producer parentProd(m_mltProducer->parent());
406     if (parentProd.get_producer() == NULL) {
407         kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
408         return;
409     }
410
411     Mlt::Service service(parentProd.get_service());
412     if (service.type() != tractor_type) {
413         kWarning() << "// TRACTOR PROBLEM";
414         return;
415     }
416     Mlt::Tractor tractor(service);
417     if ( tractor.count() < 2) {
418         kWarning() << "// TRACTOR PROBLEM";
419         return;
420     }
421     mlt_service_lock(service.get_service());
422     Mlt::Producer trackProducer(tractor.track(0));
423     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
424
425     trackPlaylist.remove(0);
426     if (path.isEmpty()) {
427         mlt_service_unlock(service.get_service());
428         return;
429     }
430
431     // Add overlay clip
432     char *tmp = qstrdup(path.toUtf8().constData());
433     Mlt::Producer *clip = new Mlt::Producer (*m_mltProfile, "loader", tmp);
434     delete[] tmp;
435     clip->set_in_and_out(0, 99999);
436     trackPlaylist.insert_at(0, clip, 1);
437
438     // Add transition
439     mlt_service serv = m_mltProducer->parent().get_service();
440     mlt_service nextservice = mlt_service_get_producer(serv);
441     mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
442     QString mlt_type = mlt_properties_get(properties, "mlt_type");
443     if (mlt_type != "transition") {
444         // transition does not exist, add it
445         Mlt::Field *field = tractor.field();
446         Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
447         transition->set_in_and_out(0, 0);
448         transition->set("geometry", "0,0:100%x100%:70");
449         transition->set("fill", 1);
450         transition->set("operator", "and");
451         transition->set("a_track", 0);
452         transition->set("b_track", 1);
453         field->plant_transition(*transition, 0, 1);
454     }
455     mlt_service_unlock(service.get_service());
456     //delete clip;
457 }
458
459 void MltDeviceCapture::setOverlayEffect(const QString tag, QStringList parameters)
460 {
461     if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
462     Mlt::Service service(m_mltProducer->parent().get_service());
463     Mlt::Tractor tractor(service);
464     Mlt::Producer trackProducer(tractor.track(0));
465     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
466     Mlt::Service trackService(trackProducer.get_service());
467
468     mlt_service_lock(service.get_service());
469
470     // delete previous effects
471     Mlt::Filter *filter;
472     filter = trackService.filter(0);
473     if (filter && !tag.isEmpty()) {
474         QString currentService = filter->get("mlt_service");
475         if (currentService == tag) {
476             // Effect is already there
477             mlt_service_unlock(service.get_service());
478             return;
479         }
480     }
481     while (filter) {
482         trackService.detach(*filter);
483         delete filter;
484         filter = trackService.filter(0);
485     }
486     
487     if (tag.isEmpty()) {
488         mlt_service_unlock(service.get_service());
489         return;
490     }
491     
492     char *tmp = qstrdup(tag.toUtf8().constData());
493     filter = new Mlt::Filter(*m_mltProfile, tmp);
494     delete[] tmp;
495     if (filter && filter->is_valid()) {
496         for (int j = 0; j < parameters.count(); j++) {
497             filter->set(parameters.at(j).section("=", 0, 0).toUtf8().constData(), parameters.at(j).section("=", 1, 1).toUtf8().constData());
498         }
499         trackService.attach(*filter);
500     }
501     mlt_service_unlock(service.get_service());
502 }
503
504 void MltDeviceCapture::mirror(bool activate)
505 {
506     if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
507     Mlt::Service service(m_mltProducer->parent().get_service());
508     Mlt::Tractor tractor(service);
509     Mlt::Producer trackProducer(tractor.track(1));
510     Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
511     Mlt::Service trackService(trackProducer.get_service());
512
513     mlt_service_lock(service.get_service());
514
515     // delete previous effects
516     Mlt::Filter *filter;
517     filter = trackService.filter(0);
518     while (filter) {
519         trackService.detach(*filter);
520         delete filter;
521         filter = trackService.filter(0);
522     }
523
524     if (!activate) {
525         mlt_service_unlock(service.get_service());
526         return;
527     }
528
529     filter = new Mlt::Filter(*m_mltProfile, "mirror");
530     if (filter && filter->is_valid()) {
531         filter->set("mirror", "flip");
532         trackService.attach(*filter);
533     }
534     mlt_service_unlock(service.get_service());
535 }
536