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