1 /***************************************************************************
2 mltdevicecapture.cpp - description
4 begin : Sun May 21 2011
5 copyright : (C) 2011 by Jean-Baptiste Mardelle (jb@kdenlive.org)
7 ***************************************************************************/
9 /***************************************************************************
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. *
16 ***************************************************************************/
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"
26 #include <mlt++/Mlt.h>
29 #include <KStandardDirs>
30 #include <KMessageBox>
32 #include <KTemporaryFile>
37 #include <QApplication>
47 static void consumer_gl_frame_show(mlt_consumer, MltDeviceCapture * self, mlt_frame frame_ptr)
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);
54 static void rec_consumer_frame_show(mlt_consumer, MltDeviceCapture * self, mlt_frame frame_ptr)
56 Mlt::Frame frame(frame_ptr);
57 if (!frame.is_valid()) return;
58 self->gotCapturedFrame(frame);
61 static void rec_consumer_frame_preview(mlt_consumer, MltDeviceCapture * self, mlt_frame frame_ptr)
63 Mlt::Frame frame(frame_ptr);
64 if (!frame.is_valid()) return;
65 if (self->sendFrameForAnalysis && frame_ptr->convert_image) {
66 self->emitFrameUpdated(frame);
68 if (self->doCapture > 0) {
70 if (self->doCapture == 0) self->saveFrame(frame);
73 //TODO: connect record monitor to audio scopes
75 if (self->analyseAudio) {
76 self->showAudio(frame);
82 MltDeviceCapture::MltDeviceCapture(QString profile, VideoPreviewContainer *surface, QWidget *parent) :
83 AbstractRender("capture", parent),
85 sendFrameForAnalysis(false),
90 m_livePreview(KdenliveSettings::recording_preview()),
91 m_captureDisplayWidget(surface),
92 m_winid((int) surface->winId()),
93 analyseAudio(KdenliveSettings::monitor_audio()),
94 processingImage(false)
96 if (profile.isEmpty()) profile = KdenliveSettings::current_profile();
97 buildConsumer(profile);
98 connect(this, SIGNAL(unblockPreview()), this, SLOT(slotPreparePreview()));
101 MltDeviceCapture::~MltDeviceCapture()
103 if (m_mltConsumer) delete m_mltConsumer;
104 if (m_mltProducer) delete m_mltProducer;
105 if (m_mltProfile) delete m_mltProfile;
108 void MltDeviceCapture::buildConsumer(const QString &profileName)
110 if (!profileName.isEmpty()) m_activeProfile = profileName;
112 if (m_mltProfile) delete m_mltProfile;
114 char *tmp = qstrdup(m_activeProfile.toUtf8().constData());
115 setenv("MLT_PROFILE", tmp, 1);
116 m_mltProfile = new Mlt::Profile(tmp);
117 m_mltProfile->set_explicit(true);
120 QString videoDriver = KdenliveSettings::videodrivername();
121 if (!videoDriver.isEmpty()) {
122 if (videoDriver == "x11_noaccel") {
123 setenv("SDL_VIDEO_YUV_HWACCEL", "0", 1);
126 unsetenv("SDL_VIDEO_YUV_HWACCEL");
129 setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 1);
133 m_mltConsumer = new Mlt::Consumer(*m_mltProfile, "sdl_audio");
134 m_mltConsumer->set("preview_off", 1);
135 m_mltConsumer->set("preview_format", mlt_image_rgb24);
136 m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) consumer_gl_frame_show);
138 m_mltConsumer = new Mlt::Consumer(*m_mltProfile, "sdl_preview");
139 m_mltConsumer->set("window_id", m_winid);
140 m_mltConsumer->listen("consumer-frame-show", this, (mlt_listener) rec_consumer_frame_preview);
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");
147 QString audioDevice = KdenliveSettings::audiodevicename();
148 if (!audioDevice.isEmpty())
149 m_mltConsumer->set("audio_device", audioDevice.toUtf8().constData());
151 if (!videoDriver.isEmpty())
152 m_mltConsumer->set("video_driver", videoDriver.toUtf8().constData());
154 QString audioDriver = KdenliveSettings::audiodrivername();
156 if (!audioDriver.isEmpty())
157 m_mltConsumer->set("audio_driver", audioDriver.toUtf8().constData());
159 //m_mltConsumer->set("progressive", 0);
160 //m_mltConsumer->set("buffer", 1);
161 //m_mltConsumer->set("real_time", 0);
164 void MltDeviceCapture::stop()
166 bool isPlaylist = false;
167 disconnect(this, SIGNAL(imageReady(QImage)), this, SIGNAL(frameUpdated(QImage)));
168 m_captureDisplayWidget->stop();
171 m_mltConsumer->set("refresh", 0);
172 m_mltConsumer->stop();
173 //if (!m_mltConsumer->is_stopped()) m_mltConsumer->stop();
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) {
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");
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());
210 mlt_playlist_close(trackPlaylist.get_playlist());
216 mlt_service_unlock(service.get_service());
217 delete m_mltProducer;
218 m_mltProducer = NULL;
220 // For some reason, the consumer seems to be deleted by previous stuff when in playlist mode
221 if (!isPlaylist && m_mltConsumer) delete m_mltConsumer;
222 m_mltConsumer = NULL;
226 void MltDeviceCapture::doRefresh()
228 if (m_mltConsumer) m_mltConsumer->set("refresh", 1);
232 void MltDeviceCapture::emitFrameUpdated(Mlt::Frame& frame)
235 //TEST: is it better to convert the frame in a thread outside of MLT??
236 if (processingImage) return;
237 mlt_image_format format = (mlt_image_format) frame.get_int("format"); //mlt_image_rgb24;
238 int width = frame.get_int("width");
239 int height = frame.get_int("height");
240 unsigned char *buffer = (unsigned char *) frame.get_data("image");
241 if (format == mlt_image_yuv422) {
242 QtConcurrent::run(this, &MltDeviceCapture::uyvy2rgb, (unsigned char *) buffer, width, height);
246 mlt_image_format format = mlt_image_rgb24;
249 const uchar* image = frame.get_image(format, width, height);
250 QImage qimage(width, height, QImage::Format_ARGB32);
251 memcpy(qimage.bits(), image, width * height * 3);
252 emit frameUpdated(qimage.rgbSwapped());
255 void MltDeviceCapture::showFrame(Mlt::Frame& frame)
257 mlt_image_format format = mlt_image_rgb24;
260 const uchar* image = frame.get_image(format, width, height);
261 QImage qimage(width, height, QImage::Format_RGB888);
262 memcpy(qimage.scanLine(0), image, width * height * 3);
263 emit showImageSignal(qimage);
265 if (sendFrameForAnalysis && frame.get_frame()->convert_image) {
266 emit frameUpdated(qimage.rgbSwapped());
270 void MltDeviceCapture::showAudio(Mlt::Frame& frame)
272 if (!frame.is_valid() || frame.get_int("test_audio") != 0) {
275 mlt_audio_format audio_format = mlt_audio_s16;
277 int num_channels = 0;
279 int16_t* data = (int16_t*)frame.get_audio(audio_format, freq, num_channels, samples);
285 // Data format: [ c00 c10 c01 c11 c02 c12 c03 c13 ... c0{samples-1} c1{samples-1} for 2 channels.
286 // So the vector is of size samples*channels.
287 QVector<int16_t> sampleVector(samples*num_channels);
288 memcpy(sampleVector.data(), data, samples*num_channels*sizeof(int16_t));
291 emit audioSamplesSignal(sampleVector, freq, num_channels, samples);
295 bool MltDeviceCapture::slotStartPreview(const QString &producer, bool xmlFormat)
297 if (m_mltConsumer == NULL) {
300 char *tmp = qstrdup(producer.toUtf8().constData());
301 if (xmlFormat) m_mltProducer = new Mlt::Producer(*m_mltProfile, "xml-string", tmp);
302 else m_mltProducer = new Mlt::Producer(*m_mltProfile, tmp);
305 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) {
307 delete m_mltProducer;
308 m_mltProducer = NULL;
310 kDebug()<<"//// ERROR CREATRING PROD";
313 m_mltConsumer->connect(*m_mltProducer);
314 if (m_mltConsumer->start() == -1) {
315 delete m_mltConsumer;
316 m_mltConsumer = NULL;
319 connect(this, SIGNAL(imageReady(QImage)), this, SIGNAL(frameUpdated(QImage)));
323 void MltDeviceCapture::gotCapturedFrame(Mlt::Frame& frame)
326 int dropped = m_mltProducer->get_int("dropped");
327 if (dropped > m_droppedFrames) {
328 m_droppedFrames = dropped;
329 emit droppedFrames(m_droppedFrames);
333 if (m_livePreview == 2) return;
334 if (m_livePreview == 0 && (m_frameCount % 10 > 0)) return;
335 mlt_image_format format = mlt_image_rgb24;
338 uint8_t *data = frame.get_image(format, width, height, 0);
339 //QImage image(width, height, QImage::Format_RGB888);
340 //memcpy(image.bits(), data, width * height * 3);
341 QImage image((uchar *)data, width, height, QImage::Format_RGB888);
343 m_captureDisplayWidget->setImage(image);
345 //TEST: is it better to process frame conversion ouside MLT???
347 if (!m_livePreview || processingImage) return;
349 mlt_image_format format = (mlt_image_format) frame.get_int("format"); //mlt_image_rgb24a;
350 int width = frame.get_int("width");
351 int height = frame.get_int("height");
352 unsigned char *buffer = (unsigned char *) frame.get_data("image");
353 //unsigned char *buffer = frame.get_image(format, width, height);
354 //convert from uyvy422 to rgba
355 if (format == mlt_image_yuv422) {
356 QtConcurrent::run(this, &MltDeviceCapture::uyvy2rgb, (unsigned char *) buffer, width, height);
357 //CaptureHandler::uyvy2rgb((uchar *)frameBytes, (uchar *)image.bits(), videoFrame->GetWidth(), videoFrame->GetHeight());
361 void MltDeviceCapture::saveFrame(Mlt::Frame& frame)
363 mlt_image_format format = mlt_image_rgb24;
366 const uchar* image = frame.get_image(format, width, height);
367 QImage qimage(width, height, QImage::Format_RGB888);
368 memcpy(qimage.bits(), image, width * height * 3);
371 Mlt::Service service(m_mltProducer->parent().get_service());
372 Mlt::Tractor tractor(service);
373 Mlt::Producer trackProducer(tractor.track(0));
374 trackProducer.set("hide", 0);
376 qimage.save(m_capturePath);
377 emit frameSaved(m_capturePath);
378 m_capturePath.clear();
381 void MltDeviceCapture::captureFrame(const QString &path)
383 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
385 // Hide overlay track before doing the capture
386 Mlt::Service service(m_mltProducer->parent().get_service());
387 Mlt::Tractor tractor(service);
388 Mlt::Producer trackProducer(tractor.track(0));
389 mlt_service_lock(service.get_service());
390 trackProducer.set("hide", 1);
391 m_mltConsumer->purge();
392 mlt_service_unlock(service.get_service());
393 m_capturePath = path;
394 // Wait for 5 frames before capture to make sure overlay is gone
398 bool MltDeviceCapture::slotStartCapture(const QString ¶ms, const QString &path, const QString &playlist, int livePreview, bool xmlPlaylist)
401 m_livePreview = livePreview;
404 if (m_mltProfile) delete m_mltProfile;
405 char *tmp = qstrdup(m_activeProfile.toUtf8().constData());
406 m_mltProfile = new Mlt::Profile(tmp);
408 m_mltProfile->get_profile()->is_explicit = 1;
409 kDebug()<<"-- CREATING CAP: "<<params<<", PATH: "<<path;
410 tmp = qstrdup(QString("avformat:" + path).toUtf8().constData());
411 m_mltConsumer = new Mlt::Consumer(*m_mltProfile, tmp);
412 m_mltConsumer->set("real_time", -KdenliveSettings::mltthreads());
415 QStringList paramList = params.split(" ", QString::SkipEmptyParts);
417 for (int i = 0; i < paramList.count(); i++) {
418 tmp = qstrdup(paramList.at(i).section("=", 0, 0).toUtf8().constData());
419 QString value = paramList.at(i).section("=", 1, 1);
420 if (value == "%threads") value = QString::number(QThread::idealThreadCount());
421 tmp2 = qstrdup(value.toUtf8().constData());
422 m_mltConsumer->set(tmp, tmp2);
427 if (m_mltConsumer == NULL || !m_mltConsumer->is_valid()) {
429 delete m_mltConsumer;
430 m_mltConsumer = NULL;
435 // FIXME: the event object returned by the listen gets leaked...
436 m_mltConsumer->listen("consumer-frame-render", this, (mlt_listener) rec_consumer_frame_show);
437 tmp = qstrdup(playlist.toUtf8().constData());
439 // create an xml producer
440 m_mltProducer = new Mlt::Producer(*m_mltProfile, "xml-string", tmp);
443 // create a producer based on mltproducer parameter
444 m_mltProducer = new Mlt::Producer(*m_mltProfile, tmp);
448 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) {
449 kDebug()<<"//// ERROR CREATRING PROD";
453 m_mltConsumer->connect(*m_mltProducer);
454 if (m_mltConsumer->start() == -1) {
455 delete m_mltConsumer;
456 m_mltConsumer = NULL;
459 m_captureDisplayWidget->start();
464 void MltDeviceCapture::setOverlay(const QString &path)
466 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
467 Mlt::Producer parentProd(m_mltProducer->parent());
468 if (parentProd.get_producer() == NULL) {
469 kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
473 Mlt::Service service(parentProd.get_service());
474 if (service.type() != tractor_type) {
475 kWarning() << "// TRACTOR PROBLEM";
478 Mlt::Tractor tractor(service);
479 if ( tractor.count() < 2) {
480 kWarning() << "// TRACTOR PROBLEM";
483 mlt_service_lock(service.get_service());
484 Mlt::Producer trackProducer(tractor.track(0));
485 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
487 trackPlaylist.remove(0);
488 if (path.isEmpty()) {
489 mlt_service_unlock(service.get_service());
494 char *tmp = qstrdup(path.toUtf8().constData());
495 Mlt::Producer *clip = new Mlt::Producer (*m_mltProfile, "loader", tmp);
497 clip->set_in_and_out(0, 99999);
498 trackPlaylist.insert_at(0, clip, 1);
501 mlt_service serv = m_mltProducer->parent().get_service();
502 mlt_service nextservice = mlt_service_get_producer(serv);
503 mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
504 QString mlt_type = mlt_properties_get(properties, "mlt_type");
505 if (mlt_type != "transition") {
506 // transition does not exist, add it
507 Mlt::Field *field = tractor.field();
508 Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
509 transition->set_in_and_out(0, 0);
510 transition->set("geometry", "0,0:100%x100%:70");
511 transition->set("fill", 1);
512 transition->set("operator", "and");
513 transition->set("a_track", 0);
514 transition->set("b_track", 1);
515 field->plant_transition(*transition, 0, 1);
517 mlt_service_unlock(service.get_service());
521 void MltDeviceCapture::setOverlayEffect(const QString tag, QStringList parameters)
523 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
524 Mlt::Service service(m_mltProducer->parent().get_service());
525 Mlt::Tractor tractor(service);
526 Mlt::Producer trackProducer(tractor.track(0));
527 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
528 Mlt::Service trackService(trackProducer.get_service());
530 mlt_service_lock(service.get_service());
532 // delete previous effects
534 filter = trackService.filter(0);
535 if (filter && !tag.isEmpty()) {
536 QString currentService = filter->get("mlt_service");
537 if (currentService == tag) {
538 // Effect is already there
539 mlt_service_unlock(service.get_service());
544 trackService.detach(*filter);
546 filter = trackService.filter(0);
550 mlt_service_unlock(service.get_service());
554 char *tmp = qstrdup(tag.toUtf8().constData());
555 filter = new Mlt::Filter(*m_mltProfile, tmp);
557 if (filter && filter->is_valid()) {
558 for (int j = 0; j < parameters.count(); j++) {
559 filter->set(parameters.at(j).section("=", 0, 0).toUtf8().constData(), parameters.at(j).section("=", 1, 1).toUtf8().constData());
561 trackService.attach(*filter);
563 mlt_service_unlock(service.get_service());
566 void MltDeviceCapture::mirror(bool activate)
568 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
569 Mlt::Service service(m_mltProducer->parent().get_service());
570 Mlt::Tractor tractor(service);
571 Mlt::Producer trackProducer(tractor.track(1));
572 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
573 Mlt::Service trackService(trackProducer.get_service());
575 mlt_service_lock(service.get_service());
577 // delete previous effects
579 filter = trackService.filter(0);
581 trackService.detach(*filter);
583 filter = trackService.filter(0);
587 mlt_service_unlock(service.get_service());
591 filter = new Mlt::Filter(*m_mltProfile, "mirror");
592 if (filter && filter->is_valid()) {
593 filter->set("mirror", "flip");
594 trackService.attach(*filter);
596 mlt_service_unlock(service.get_service());
599 void MltDeviceCapture::uyvy2rgb(unsigned char *yuv_buffer, int width, int height)
601 processingImage = true;
602 QImage image(width, height, QImage::Format_RGB888);
603 unsigned char *rgb_buffer = image.bits();
608 int rgb_ptr, y_ptr, t;
610 len = width * height / 2;
615 for (t = 0; t < len; t++) {
618 Y = yuv_buffer[y_ptr];
619 U = yuv_buffer[y_ptr+1];
620 Y2 = yuv_buffer[y_ptr+2];
621 V = yuv_buffer[y_ptr+3];
624 r = ((298 * (Y - 16) + 409 * (V - 128) + 128) >> 8);
626 g = ((298 * (Y - 16) - 100 * (U - 128) - 208 * (V - 128) + 128) >> 8);
628 b = ((298 * (Y - 16) + 516 * (U - 128) + 128) >> 8);
630 if (r > 255) r = 255;
631 if (g > 255) g = 255;
632 if (b > 255) b = 255;
638 rgb_buffer[rgb_ptr] = r;
639 rgb_buffer[rgb_ptr+1] = g;
640 rgb_buffer[rgb_ptr+2] = b;
644 r = ((298 * (Y2 - 16) + 409 * (V - 128) + 128) >> 8);
646 g = ((298 * (Y2 - 16) - 100 * (U - 128) - 208 * (V - 128) + 128) >> 8);
648 b = ((298 * (Y2 - 16) + 516 * (U - 128) + 128) >> 8);
650 if (r > 255) r = 255;
651 if (g > 255) g = 255;
652 if (b > 255) b = 255;
658 rgb_buffer[rgb_ptr] = r;
659 rgb_buffer[rgb_ptr+1] = g;
660 rgb_buffer[rgb_ptr+2] = b;
663 //emit imageReady(image);
664 m_captureDisplayWidget->setImage(image);
665 emit unblockPreview();
666 //processingImage = false;
669 void MltDeviceCapture::slotPreparePreview()
671 QTimer::singleShot(1000, this, SLOT(slotAllowPreview()));
674 void MltDeviceCapture::slotAllowPreview()
676 processingImage = false;