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),
86 analyseAudio(KdenliveSettings::monitor_audio()),
87 processingImage(false),
92 m_livePreview(KdenliveSettings::recording_preview()),
93 m_captureDisplayWidget(surface),
94 m_winid((int) surface->winId())
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");
202 mlt_service_unlock(service.get_service());
203 delete m_mltProducer;
204 m_mltProducer = NULL;
206 // For some reason, the consumer seems to be deleted by previous stuff when in playlist mode
207 if (!isPlaylist && m_mltConsumer) delete m_mltConsumer;
208 m_mltConsumer = NULL;
212 void MltDeviceCapture::doRefresh()
214 if (m_mltConsumer) m_mltConsumer->set("refresh", 1);
218 void MltDeviceCapture::emitFrameUpdated(Mlt::Frame& frame)
221 //TEST: is it better to convert the frame in a thread outside of MLT??
222 if (processingImage) return;
223 mlt_image_format format = (mlt_image_format) frame.get_int("format"); //mlt_image_rgb24;
224 int width = frame.get_int("width");
225 int height = frame.get_int("height");
226 unsigned char *buffer = (unsigned char *) frame.get_data("image");
227 if (format == mlt_image_yuv422) {
228 QtConcurrent::run(this, &MltDeviceCapture::uyvy2rgb, (unsigned char *) buffer, width, height);
232 mlt_image_format format = mlt_image_rgb24;
235 const uchar* image = frame.get_image(format, width, height);
236 QImage qimage(width, height, QImage::Format_ARGB32);
237 memcpy(qimage.bits(), image, width * height * 3);
238 emit frameUpdated(qimage.rgbSwapped());
241 void MltDeviceCapture::showFrame(Mlt::Frame& frame)
243 mlt_image_format format = mlt_image_rgb24;
246 const uchar* image = frame.get_image(format, width, height);
247 QImage qimage(width, height, QImage::Format_RGB888);
248 memcpy(qimage.scanLine(0), image, width * height * 3);
249 emit showImageSignal(qimage);
251 if (sendFrameForAnalysis && frame.get_frame()->convert_image) {
252 emit frameUpdated(qimage.rgbSwapped());
256 void MltDeviceCapture::showAudio(Mlt::Frame& frame)
258 if (!frame.is_valid() || frame.get_int("test_audio") != 0) {
261 mlt_audio_format audio_format = mlt_audio_s16;
263 int num_channels = 0;
265 int16_t* data = (int16_t*)frame.get_audio(audio_format, freq, num_channels, samples);
271 // Data format: [ c00 c10 c01 c11 c02 c12 c03 c13 ... c0{samples-1} c1{samples-1} for 2 channels.
272 // So the vector is of size samples*channels.
273 QVector<int16_t> sampleVector(samples*num_channels);
274 memcpy(sampleVector.data(), data, samples*num_channels*sizeof(int16_t));
276 emit audioSamplesSignal(sampleVector, freq, num_channels, samples);
280 bool MltDeviceCapture::slotStartPreview(const QString &producer, bool xmlFormat)
282 if (m_mltConsumer == NULL) {
285 char *tmp = qstrdup(producer.toUtf8().constData());
286 if (xmlFormat) m_mltProducer = new Mlt::Producer(*m_mltProfile, "xml-string", tmp);
287 else m_mltProducer = new Mlt::Producer(*m_mltProfile, tmp);
290 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) {
292 delete m_mltProducer;
293 m_mltProducer = NULL;
295 kDebug()<<"//// ERROR CREATRING PROD";
298 m_mltConsumer->connect(*m_mltProducer);
299 if (m_mltConsumer->start() == -1) {
300 delete m_mltConsumer;
301 m_mltConsumer = NULL;
304 connect(this, SIGNAL(imageReady(QImage)), this, SIGNAL(frameUpdated(QImage)));
308 void MltDeviceCapture::gotCapturedFrame(Mlt::Frame& frame)
311 int dropped = m_mltProducer->get_int("dropped");
312 if (dropped > m_droppedFrames) {
313 m_droppedFrames = dropped;
314 emit droppedFrames(m_droppedFrames);
318 if (m_livePreview == 2) return;
319 if (m_livePreview == 0 && (m_frameCount % 10 > 0)) return;
320 mlt_image_format format = mlt_image_rgb24;
323 uint8_t *data = frame.get_image(format, width, height, 0);
324 //QImage image(width, height, QImage::Format_RGB888);
325 //memcpy(image.bits(), data, width * height * 3);
326 QImage image((uchar *)data, width, height, QImage::Format_RGB888);
328 m_captureDisplayWidget->setImage(image);
330 //TEST: is it better to process frame conversion ouside MLT???
332 if (!m_livePreview || processingImage) return;
334 mlt_image_format format = (mlt_image_format) frame.get_int("format"); //mlt_image_rgb24a;
335 int width = frame.get_int("width");
336 int height = frame.get_int("height");
337 unsigned char *buffer = (unsigned char *) frame.get_data("image");
338 //unsigned char *buffer = frame.get_image(format, width, height);
339 //convert from uyvy422 to rgba
340 if (format == mlt_image_yuv422) {
341 QtConcurrent::run(this, &MltDeviceCapture::uyvy2rgb, (unsigned char *) buffer, width, height);
342 //CaptureHandler::uyvy2rgb((uchar *)frameBytes, (uchar *)image.bits(), videoFrame->GetWidth(), videoFrame->GetHeight());
346 void MltDeviceCapture::saveFrame(Mlt::Frame& frame)
348 mlt_image_format format = mlt_image_rgb24;
351 const uchar* image = frame.get_image(format, width, height);
352 QImage qimage(width, height, QImage::Format_RGB888);
353 memcpy(qimage.bits(), image, width * height * 3);
356 Mlt::Service service(m_mltProducer->parent().get_service());
357 Mlt::Tractor tractor(service);
358 Mlt::Producer trackProducer(tractor.track(0));
359 trackProducer.set("hide", 0);
361 qimage.save(m_capturePath);
362 emit frameSaved(m_capturePath);
363 m_capturePath.clear();
366 void MltDeviceCapture::captureFrame(const QString &path)
368 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
370 // Hide overlay track before doing the capture
371 Mlt::Service service(m_mltProducer->parent().get_service());
372 Mlt::Tractor tractor(service);
373 Mlt::Producer trackProducer(tractor.track(0));
374 mlt_service_lock(service.get_service());
375 trackProducer.set("hide", 1);
376 m_mltConsumer->purge();
377 mlt_service_unlock(service.get_service());
378 m_capturePath = path;
379 // Wait for 5 frames before capture to make sure overlay is gone
383 bool MltDeviceCapture::slotStartCapture(const QString ¶ms, const QString &path, const QString &playlist, int livePreview, bool xmlPlaylist)
386 m_livePreview = livePreview;
389 if (m_mltProfile) delete m_mltProfile;
390 char *tmp = qstrdup(m_activeProfile.toUtf8().constData());
391 m_mltProfile = new Mlt::Profile(tmp);
393 m_mltProfile->get_profile()->is_explicit = 1;
394 kDebug()<<"-- CREATING CAP: "<<params<<", PATH: "<<path;
395 tmp = qstrdup(QString("avformat:" + path).toUtf8().constData());
396 m_mltConsumer = new Mlt::Consumer(*m_mltProfile, tmp);
397 m_mltConsumer->set("real_time", -KdenliveSettings::mltthreads());
400 QStringList paramList = params.split(" ", QString::SkipEmptyParts);
402 for (int i = 0; i < paramList.count(); i++) {
403 tmp = qstrdup(paramList.at(i).section("=", 0, 0).toUtf8().constData());
404 QString value = paramList.at(i).section("=", 1, 1);
405 if (value == "%threads") value = QString::number(QThread::idealThreadCount());
406 tmp2 = qstrdup(value.toUtf8().constData());
407 m_mltConsumer->set(tmp, tmp2);
412 if (m_mltConsumer == NULL || !m_mltConsumer->is_valid()) {
414 delete m_mltConsumer;
415 m_mltConsumer = NULL;
420 // FIXME: the event object returned by the listen gets leaked...
421 if (m_livePreview < 2) m_mltConsumer->listen("consumer-frame-render", this, (mlt_listener) rec_consumer_frame_show);
422 tmp = qstrdup(playlist.toUtf8().constData());
424 // create an xml producer
425 m_mltProducer = new Mlt::Producer(*m_mltProfile, "xml-string", tmp);
428 // create a producer based on mltproducer parameter
429 m_mltProducer = new Mlt::Producer(*m_mltProfile, tmp);
433 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) {
434 kDebug()<<"//// ERROR CREATRING PROD";
438 m_mltConsumer->connect(*m_mltProducer);
439 if (m_mltConsumer->start() == -1) {
440 delete m_mltConsumer;
441 m_mltConsumer = NULL;
444 m_captureDisplayWidget->start();
449 void MltDeviceCapture::setOverlay(const QString &path)
451 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
452 Mlt::Producer parentProd(m_mltProducer->parent());
453 if (parentProd.get_producer() == NULL) {
454 kDebug() << "PLAYLIST BROKEN, CANNOT INSERT CLIP //////";
458 Mlt::Service service(parentProd.get_service());
459 if (service.type() != tractor_type) {
460 kWarning() << "// TRACTOR PROBLEM";
463 Mlt::Tractor tractor(service);
464 if ( tractor.count() < 2) {
465 kWarning() << "// TRACTOR PROBLEM";
468 mlt_service_lock(service.get_service());
469 Mlt::Producer trackProducer(tractor.track(0));
470 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
472 trackPlaylist.remove(0);
473 if (path.isEmpty()) {
474 mlt_service_unlock(service.get_service());
479 char *tmp = qstrdup(path.toUtf8().constData());
480 Mlt::Producer *clip = new Mlt::Producer (*m_mltProfile, "loader", tmp);
482 clip->set_in_and_out(0, 99999);
483 trackPlaylist.insert_at(0, clip, 1);
486 mlt_service serv = m_mltProducer->parent().get_service();
487 mlt_service nextservice = mlt_service_get_producer(serv);
488 mlt_properties properties = MLT_SERVICE_PROPERTIES(nextservice);
489 QString mlt_type = mlt_properties_get(properties, "mlt_type");
490 if (mlt_type != "transition") {
491 // transition does not exist, add it
492 Mlt::Field *field = tractor.field();
493 Mlt::Transition *transition = new Mlt::Transition(*m_mltProfile, "composite");
494 transition->set_in_and_out(0, 0);
495 transition->set("geometry", "0/0:100%x100%:70");
496 transition->set("fill", 1);
497 transition->set("operator", "and");
498 transition->set("a_track", 0);
499 transition->set("b_track", 1);
500 field->plant_transition(*transition, 0, 1);
502 mlt_service_unlock(service.get_service());
506 void MltDeviceCapture::setOverlayEffect(const QString &tag, QStringList parameters)
508 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
509 Mlt::Service service(m_mltProducer->parent().get_service());
510 Mlt::Tractor tractor(service);
511 Mlt::Producer trackProducer(tractor.track(0));
512 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
513 Mlt::Service trackService(trackProducer.get_service());
515 mlt_service_lock(service.get_service());
517 // delete previous effects
519 filter = trackService.filter(0);
520 if (filter && !tag.isEmpty()) {
521 QString currentService = filter->get("mlt_service");
522 if (currentService == tag) {
523 // Effect is already there
524 mlt_service_unlock(service.get_service());
529 trackService.detach(*filter);
531 filter = trackService.filter(0);
535 mlt_service_unlock(service.get_service());
539 char *tmp = qstrdup(tag.toUtf8().constData());
540 filter = new Mlt::Filter(*m_mltProfile, tmp);
542 if (filter && filter->is_valid()) {
543 for (int j = 0; j < parameters.count(); j++) {
544 filter->set(parameters.at(j).section("=", 0, 0).toUtf8().constData(), parameters.at(j).section("=", 1, 1).toUtf8().constData());
546 trackService.attach(*filter);
548 mlt_service_unlock(service.get_service());
551 void MltDeviceCapture::mirror(bool activate)
553 if (m_mltProducer == NULL || !m_mltProducer->is_valid()) return;
554 Mlt::Service service(m_mltProducer->parent().get_service());
555 Mlt::Tractor tractor(service);
556 Mlt::Producer trackProducer(tractor.track(1));
557 Mlt::Playlist trackPlaylist((mlt_playlist) trackProducer.get_service());
558 Mlt::Service trackService(trackProducer.get_service());
560 mlt_service_lock(service.get_service());
562 // delete previous effects
564 filter = trackService.filter(0);
566 trackService.detach(*filter);
568 filter = trackService.filter(0);
572 mlt_service_unlock(service.get_service());
576 filter = new Mlt::Filter(*m_mltProfile, "mirror");
577 if (filter && filter->is_valid()) {
578 filter->set("mirror", "flip");
579 trackService.attach(*filter);
581 mlt_service_unlock(service.get_service());
584 void MltDeviceCapture::uyvy2rgb(unsigned char *yuv_buffer, int width, int height)
586 processingImage = true;
587 QImage image(width, height, QImage::Format_RGB888);
588 unsigned char *rgb_buffer = image.bits();
593 int rgb_ptr, y_ptr, t;
595 len = width * height / 2;
600 for (t = 0; t < len; t++) {
603 Y = yuv_buffer[y_ptr];
604 U = yuv_buffer[y_ptr+1];
605 Y2 = yuv_buffer[y_ptr+2];
606 V = yuv_buffer[y_ptr+3];
609 r = ((298 * (Y - 16) + 409 * (V - 128) + 128) >> 8);
611 g = ((298 * (Y - 16) - 100 * (U - 128) - 208 * (V - 128) + 128) >> 8);
613 b = ((298 * (Y - 16) + 516 * (U - 128) + 128) >> 8);
615 if (r > 255) r = 255;
616 if (g > 255) g = 255;
617 if (b > 255) b = 255;
623 rgb_buffer[rgb_ptr] = r;
624 rgb_buffer[rgb_ptr+1] = g;
625 rgb_buffer[rgb_ptr+2] = b;
629 r = ((298 * (Y2 - 16) + 409 * (V - 128) + 128) >> 8);
631 g = ((298 * (Y2 - 16) - 100 * (U - 128) - 208 * (V - 128) + 128) >> 8);
633 b = ((298 * (Y2 - 16) + 516 * (U - 128) + 128) >> 8);
635 if (r > 255) r = 255;
636 if (g > 255) g = 255;
637 if (b > 255) b = 255;
643 rgb_buffer[rgb_ptr] = r;
644 rgb_buffer[rgb_ptr+1] = g;
645 rgb_buffer[rgb_ptr+2] = b;
648 //emit imageReady(image);
649 m_captureDisplayWidget->setImage(image);
650 emit unblockPreview();
651 //processingImage = false;
654 void MltDeviceCapture::slotPreparePreview()
656 QTimer::singleShot(1000, this, SLOT(slotAllowPreview()));
659 void MltDeviceCapture::slotAllowPreview()
661 processingImage = false;