asset drag/drop to viewers, bluebanana bug, listbox fontlist highlight
[goodguy/history.git] / cinelerra-5.1 / cinelerra / record.C
1 /*
2  * CINELERRA
3  * Copyright (C) 2009-2013 Adam Williams <broadcast at earthling dot net>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  */
20
21 #include "asset.h"
22 #include "assets.h"
23 #include "audiodevice.h"
24 #include "awindow.h"
25 #include "awindowgui.h"
26 #include "batch.h"
27 #include "bchash.h"
28 #include "channel.h"
29 #include "channeldb.h"
30 #include "channelpicker.h"
31 #include "clip.h"
32 #include "commercials.h"
33 #include "condition.h"
34 #include "cwindow.h"
35 #include "devicedvbinput.h"
36 #include "drivesync.h"
37 #include "edl.h"
38 #include "edlsession.h"
39 #include "errorbox.h"
40 #include "file.h"
41 #include "filexml.h"
42 #include "filesystem.h"
43 #include "filethread.h"
44 #include "formatcheck.h"
45 #include "indexfile.h"
46 #include "keys.h"
47 #include "language.h"
48 #include "localsession.h"
49 #include "libdv.h"
50 #include "libmjpeg.h"
51 #include "libzmpeg3.h"
52 #include "mainmenu.h"
53 #include "mainundo.h"
54 #include "mwindow.h"
55 #include "mwindowgui.h"
56 #include "mutex.h"
57 #include "picture.h"
58 #include "playbackengine.h"
59 #include "preferences.h"
60 #include "record.h"
61 #include "recordaudio.h"
62 #include "recordconfig.h"
63 #include "recordgui.h"
64 #include "recordlabel.h"
65 #include "recordmonitor.h"
66 #include "recordprefs.inc"
67 #include "recordthread.h"
68 #include "recordvideo.h"
69 #include "removefile.h"
70 #include "mainsession.h"
71 #include "sighandler.h"
72 #include "testobject.h"
73 #include "theme.h"
74 #include "timebar.h"
75 #include "tracks.h"
76 #include "videoconfig.h"
77 #include "videodevice.h"
78
79 #include <string.h>
80 #include <sys/types.h>
81 #include <sys/wait.h>
82
83
84 RecordMenuItem::RecordMenuItem(MWindow *mwindow)
85  : BC_MenuItem(_("Record..."), "r", 'r')
86 {
87         this->mwindow = mwindow;
88         record = new Record(mwindow, this);
89 }
90
91 RecordMenuItem::~RecordMenuItem()
92 {
93         delete record;
94 }
95
96 int RecordMenuItem::handle_event()
97 {
98         record->start();
99         return 1;
100 }
101
102
103 Record::Record(MWindow *mwindow, RecordMenuItem *menu_item)
104  : Thread(1, 0, 0),
105    record_batches(mwindow)
106 {
107         this->mwindow = mwindow;
108         this->menu_item = menu_item;
109         mwindow->gui->record = this;
110         adevice = 0;
111         vdevice = 0;
112         file = 0;
113         picture = new PictureConfig();
114         channeldb = new ChannelDB;
115         master_channel = new Channel;
116         record_channel = new RecordChannel(this);
117         channel = 0;
118         current_channel = 0;
119         default_asset = 0;
120         load_mode = 0 ;
121         pause_lock = new Mutex("Record::pause_lock");
122         init_lock = new Condition(0,"Record::init_lock");
123         record_audio = 0;
124         record_video = 0;
125         record_thread = 0;
126         record_monitor = 0;
127         record_gui = 0;
128         session_sample_offset = 0;
129         device_sample_offset = 0;
130         recording = 0;
131         capturing = 0;
132         single_frame = 0;
133         writing_file = 0;
134         drop_overrun_frames = 0;
135         fill_underrun_frames = 0;
136         power_off = 0;
137         commercial_check = skimming_active = 0;
138         commercial_start_time = -1;
139         commercial_fd = -1;
140         deletions = 0;
141         status_color = -1;
142         keybfr[0] = 0;
143         last_key = -1;
144         do_audio = 0;
145         do_video = 0;
146         current_frame = written_frames = total_frames = 0;
147         current_sample = written_samples = total_samples = 0;
148         audio_time = video_time = -1.;
149         play_gain = mute_gain = 1.;
150         drivesync = 0;
151         input_threads_pausing = 0;
152         window_lock = new Mutex("Record::window_lock");
153         timer_lock = new Mutex("Record::timer_lock");
154         file_lock = new Mutex("Record::file_lock");
155         adevice_lock = new Mutex("Record::adevice_lock");
156         vdevice_lock = new Mutex("Record::vdevice_lock");
157         batch_lock = new Mutex("Record::batch_lock");
158         skim_thread = new SkimDbThread();
159         cutads_status = new RecordCutAdsStatus(this);
160         blink_status = new RecordBlinkStatus(this);
161 }
162
163 Record::~Record()
164 {
165         mwindow->gui->record = 0;
166         stop();
167         delete blink_status;
168         delete cutads_status;
169         stop_skimming();
170         delete skim_thread;
171         delete deletions;
172         delete picture;
173         delete channeldb;
174         delete record_channel;
175         delete master_channel;
176         delete window_lock;
177         delete timer_lock;
178         delete record_audio;
179         delete record_video;
180         delete adevice_lock;
181         delete vdevice_lock;
182         delete batch_lock;
183         delete file_lock;
184         delete pause_lock;
185         delete init_lock;
186 }
187
188 int Record::load_defaults()
189 {
190
191         char string[BCTEXTLEN];
192         BC_Hash *defaults = mwindow->defaults;
193         EDLSession *session = SESSION;
194         default_asset->copy_from(session->recording_format, 0);
195         default_asset->channels = session->aconfig_in->channels;
196         default_asset->sample_rate = session->aconfig_in->in_samplerate;
197         default_asset->frame_rate = session->vconfig_in->in_framerate;
198         default_asset->width = session->vconfig_in->w;
199         default_asset->height = session->vconfig_in->h;
200         default_asset->layers = 1;
201 // Fix encoding parameters depending on driver.
202 // These are locked by a specific driver.
203         const char *vcodec = 0;
204         switch( session->vconfig_in->driver ) {
205         case CAPTURE_DVB:
206         case VIDEO4LINUX2MPEG:
207                 break;
208         case VIDEO4LINUX2JPEG:
209                 vcodec = CODEC_TAG_MJPEG;
210                 break;
211         case CAPTURE_FIREWIRE:
212         case CAPTURE_IEC61883:
213                 vcodec = CODEC_TAG_DVSD;
214                 break;
215         }
216         if( vcodec )
217                 strcpy(default_asset->vcodec, vcodec);
218
219         record_batches.load_defaults(channeldb, this);
220
221         int cur_chan_no = defaults->get("RECORD_CURRENT_CHANNEL", 0);
222         current_channel = channeldb->get(cur_chan_no);
223         load_mode = defaults->get("RECORD_LOADMODE", LOADMODE_PASTE);
224         monitor_audio = defaults->get("RECORD_MONITOR_AUDIO", 1);
225         metering_audio = defaults->get("RECORD_METERING_AUDIO", 1);
226         monitor_video = defaults->get("RECORD_MONITOR_VIDEO", 1);
227         video_window_open = defaults->get("RECORD_MONITOR_OPEN", 1);
228         video_x = defaults->get("RECORD_VIDEO_X", 0);
229         video_y = defaults->get("RECORD_VIDEO_Y", 0);
230         video_zoom = defaults->get("RECORD_VIDEO_Z", (float)1);
231         picture->load_defaults();
232         reverse_interlace = defaults->get("REVERSE_INTERLACE", 0);
233         for( int i=0; i<MAXCHANNELS; ++i ) {
234                 sprintf(string, "RECORD_DCOFFSET_%d", i);
235                 dc_offset[i] = defaults->get(string, 0);
236         }
237         drop_overrun_frames = defaults->get("DROP_OVERRUN_FRAMES", 0);
238         fill_underrun_frames = defaults->get("FILL_UNDERRUN_FRAMES", 0);
239         commercial_check = defaults->get("COMMERCIAL_CHECK", 0);
240         return 0;
241 }
242
243 int Record::save_defaults()
244 {
245         char string[BCTEXTLEN];
246         BC_Hash *defaults = mwindow->defaults;
247         set_editing_batch(0);
248 // Save default asset path but not the format because that's
249 // overridden by the driver.
250 // The format is saved in preferences.
251         if( record_batches.total() )
252                 strcpy(default_asset->path, record_batches[0]->asset->path);
253         default_asset->save_defaults(defaults, "RECORD_", 0, 0, 0, 0, 0);
254
255         record_batches.save_defaults(channeldb);
256
257         int cur_chan_no = channeldb->number_of(current_channel);
258         defaults->update("RECORD_CURRENT_CHANNEL", cur_chan_no);
259         defaults->update("RECORD_LOADMODE", load_mode);
260         defaults->update("RECORD_MONITOR_AUDIO", monitor_audio);
261         defaults->update("RECORD_METERING_AUDIO", metering_audio);
262         defaults->update("RECORD_MONITOR_VIDEO", monitor_video);
263         defaults->update("RECORD_MONITOR_OPEN", video_window_open);
264         defaults->update("RECORD_VIDEO_X", video_x);
265         defaults->update("RECORD_VIDEO_Y", video_y);
266         defaults->update("RECORD_VIDEO_Z", video_zoom);
267         picture->save_defaults();
268         defaults->update("REVERSE_INTERLACE", reverse_interlace);
269         for( int i=0; i<MAXCHANNELS; ++i ) {
270                 sprintf(string, "RECORD_DCOFFSET_%d", i);
271                 defaults->update(string, dc_offset[i]);
272         }
273         defaults->update("DROP_OVERRUN_FRAMES", drop_overrun_frames);
274         defaults->update("FILL_UNDERRUN_FRAMES", fill_underrun_frames);
275         defaults->update("COMMERCIAL_CHECK", commercial_check);
276 SET_TRACE
277
278         return 0;
279 }
280
281 void Record::configure_batches()
282 {
283 // printf("Record::configure_batches %d\n",__LINE__);
284 // default_assset->dump();
285         strcpy(record_batches[0]->asset->path, default_asset->path);
286         int total_batches = record_batches.total();
287         for( int i=0; i<total_batches; ++i ) {
288                 Batch *batch = record_batches[i];
289                 batch->asset->copy_format(default_asset);
290         }
291 }
292
293 void Record::run()
294 {
295         int result = 0;
296         record_gui = 0;
297 // Default asset forms the first path in the batch capture
298 // and the file format for all operations.
299         default_asset = new Asset;
300
301 // Determine information about the device.
302         AudioInConfig *aconfig_in = SESSION->aconfig_in;
303         VideoInConfig *vconfig_in = SESSION->vconfig_in;
304         int driver = vconfig_in->driver;
305         VideoDevice::load_channeldb(channeldb, vconfig_in);
306         fixed_compression = VideoDevice::is_compressed(driver, 0, 1);
307         load_defaults();
308 // Apply a major kludge
309         if( fixed_compression ) {
310                 VideoDevice device;
311                 device.fix_asset(default_asset, driver);
312         }
313         default_asset->channels = aconfig_in->channels;
314         VideoDevice::save_channeldb(channeldb, vconfig_in);
315         save_defaults();
316         mwindow->save_defaults();
317         configure_batches();
318         set_current_batch(0);
319         set_editing_batch(0);
320
321 // Run recordgui
322         edl = new EDL;
323         edl->create_objects();
324         edl->session->output_w = default_asset->width;
325         edl->session->output_h = default_asset->height;
326         edl->session->aspect_w = SESSION->aspect_w;
327         edl->session->aspect_h = SESSION->aspect_h;
328
329         window_lock->lock("Record::run 3");
330         record_gui = new RecordGUI(mwindow, this);
331         record_gui->create_objects();
332
333         record_monitor = new RecordMonitor(mwindow, this);
334         record_monitor->create_objects();
335         record_gui->update_batch_sources();
336
337         record_gui->show_window();
338         record_gui->flush();
339
340         if( mwindow->gui->remote_control->deactivate() )
341                 mwindow->gui->record_remote_handler->activate();
342
343         if( video_window_open ) {
344                 record_monitor->window->show_window();
345                 record_monitor->window->raise_window();
346                 record_monitor->window->flush();
347         }
348
349         window_lock->unlock();
350         channel = 0;
351         start_input_threads();
352         update_position();
353         init_lock->unlock();
354
355         result = record_gui->run_window();
356 // record gui operates here until window is closed
357 // wait for it
358         if( record_gui->get_window_lock() ) {
359                 record_gui->lock_window();
360                 record_gui->unlock_window();
361         }
362
363 // Need to stop everything this time
364
365         stop_commercial_capture(0);
366         int video_stream = -1;
367         if( default_asset->format == FILE_MPEG ) {
368                 Channel *channel = get_current_channel();
369                 if( channel )
370                         video_stream = channel->video_stream;
371         }
372         stop(0);
373         edl->Garbage::remove_user();
374
375         if( mwindow->gui->remote_control->deactivate() )
376                 mwindow->gui->cwindow_remote_handler->activate();
377
378 // Save everything again
379         save_defaults();
380
381 // Paste into EDL
382         if( !result && load_mode != LOADMODE_NOTHING ) {
383                 mwindow->gui->lock_window("Record::run");
384                 ArrayList<EDL*> new_edls;
385 // Paste assets
386                 int total_batches = record_batches.total();
387                 for( int i=0; i<total_batches; ++i ) {
388                         Batch *batch = record_batches[i];
389                         Asset *asset = batch->asset;
390                         if( batch->recorded ) {
391                                 EDL *new_edl = new EDL;
392                                 mwindow->remove_asset_from_caches(asset);
393                                 new_edl->create_objects();
394                                 new_edl->copy_session(mwindow->edl);
395                                 mwindow->asset_to_edl(new_edl, asset, batch->labels);
396                                 new_edls.append(new_edl);
397                         }
398                 }
399
400                 if(new_edls.total) {
401                         mwindow->undo->update_undo_before();
402 // For pasting, clear the active region
403                         if(load_mode == LOADMODE_PASTE)
404                                 mwindow->clear(0);
405
406                         mwindow->paste_edls(&new_edls, load_mode, 0, -1,
407                                 SESSION->labels_follow_edits,
408                                 SESSION->plugins_follow_edits,
409                                 SESSION->autos_follow_edits,
410                                 0);// overwrite
411                         for( int i=0; i<new_edls.total; ++i )
412                                 new_edls.get(i)->Garbage::remove_user();
413                         new_edls.remove_all();
414                         if( video_stream >= 0 ) {
415                                 mwindow->select_asset(video_stream, -1);
416                                 mwindow->fit_selection();
417                         }
418                         mwindow->save_backup();
419                         mwindow->undo->update_undo_after(_("record"), LOAD_ALL);
420                         mwindow->restart_brender();
421                         mwindow->update_plugin_guis();
422                         mwindow->gui->update(1, 2, 1, 1, 1, 1, 0);
423                         mwindow->sync_parameters(CHANGE_ALL);
424                 }
425                 mwindow->gui->unlock_window();
426
427                 AWindowGUI *agui = mwindow->awindow->gui;
428                 agui->async_update_assets();
429         }
430
431 // Delete everything
432         record_batches.clear();
433         default_asset->Garbage::remove_user();
434 }
435
436 void Record::stop(int wait)
437 {
438         stop_operation();
439         if( wait && running() )
440                 record_gui->set_done(1);
441         join();
442         window_lock->lock("Record::stop");
443         delete record_thread;   record_thread = 0;
444         delete record_monitor;  record_monitor = 0;
445         delete record_gui;      record_gui = 0;
446         window_lock->unlock();
447 }
448
449 void Record::activate_batch(int number)
450 {
451         if( number != current_batch() ) {
452                 stop_writing();
453                 set_current_batch(number);
454                 record_gui->update_batches();
455                 record_gui->update_position(current_display_position());
456                 record_gui->update_batch_tools();
457         }
458 }
459
460
461 void Record::delete_index_file(Asset *asset)
462 {
463         IndexFile::delete_index(mwindow->preferences, asset, ".toc");
464         IndexFile::delete_index(mwindow->preferences, asset, ".idx");
465         IndexFile::delete_index(mwindow->preferences, asset, ".mkr");
466 }
467
468 void Record::delete_batch()
469 {
470 // Abort if one batch left
471         int edit_batch = editing_batch();
472         int total_batches = record_batches.total();
473         if( total_batches > 1 && edit_batch < total_batches ) {
474                 int cur_batch = current_batch();
475                 Batch *batch = record_batches[edit_batch];
476                 record_batches.remove(batch);  delete batch;
477                 if( cur_batch == edit_batch ) stop_writing();
478                 record_gui->update_batches();
479                 record_gui->update_batch_tools();
480         }
481 }
482
483 void Record::change_editing_batch(int number)
484 {
485         set_editing_batch(number);
486         record_gui->update_batch_tools();
487 }
488
489 Batch* Record::new_batch()
490 {
491         Batch *batch = new Batch(mwindow, this);
492 //printf("Record::new_batch 1\n");
493         batch->create_objects();
494         record_batches.append(batch);
495         batch->asset->copy_format(default_asset);
496
497 //printf("Record::new_batch 1\n");
498         batch->create_default_path();
499         Batch *edit_batch = get_editing_batch();
500         if( edit_batch )
501                 batch->copy_from(edit_batch);
502         int total_batches = record_batches.total();
503         set_editing_batch(total_batches - 1);
504 //printf("Record::new_batch 1\n");
505 // Update GUI if created yet
506         if(record_gui)
507                 record_gui->update_batch_tools();
508 //printf("Record::new_batch 2\n");
509         return batch;
510 }
511
512 int Record::current_batch()
513 {
514         return record_batches.current_item;
515 }
516
517 int Record::set_current_batch(int i)
518 {
519         return record_batches.current_item = i;
520 }
521
522 int Record::editing_batch()
523 {
524         return record_batches.editing_item;
525 }
526
527 int Record::set_editing_batch(int i)
528 {
529         return record_batches.editing_item = i;
530 }
531
532 int Record::delete_output_file()
533 {
534         Batch *batch = get_current_batch();
535 // Delete old file
536         if( !file && batch && !access(batch->asset->path, F_OK) ) {
537                 batch->set_notice(_("Deleting"));
538                 record_gui->update_batches();
539                 Asset *asset = batch->asset;
540                 remove_file(asset->path);
541                 mwindow->remove_asset_from_caches(asset);
542                 delete_index_file(asset);
543                 batch->clear_notice();
544                 record_gui->update_batches();
545         } while(0);
546         return 0;
547 }
548
549 int Record::open_output_file()
550 {
551         int result = 0;
552         file_lock->lock();
553         Batch *batch = get_current_batch();
554         if( !file && batch ) {
555                 delete_output_file();
556                 Asset *asset = batch->asset;
557                 asset->frame_rate = default_asset->frame_rate;
558                 asset->sample_rate = default_asset->sample_rate;
559                 asset->width = default_asset->width;
560                 asset->height = default_asset->height;
561                 int wr = 1;
562                 if( default_asset->format == FILE_MPEG ) {
563                         asset->layers = vdevice ? vdevice->total_video_streams() : 0;
564                         asset->channels = adevice ? adevice->total_audio_channels() : 0;
565                         wr = 0;
566                 }
567                 file = new File;
568                 result = file->open_file(mwindow->preferences, asset, 0, wr);
569                 if( !result ) {
570                         mwindow->sighandler->push_file(file);
571                         batch->recorded = 1;
572                         file->set_processors(mwindow->preferences->real_processors);
573                         record_gui->update_batches();
574                 }
575                 else {
576                         delete file;
577                         file = 0;
578                 }
579         }
580         file_lock->unlock();
581         return result;
582 }
583
584 void Record::start()
585 {
586         if( running() ) {
587                 window_lock->lock("Record::start");
588                 record_gui->lock_window("Record::start");
589                 record_gui->raise_window();
590                 record_gui->unlock_window();
591                 window_lock->unlock();
592         }
593         else {
594                 init_lock->reset();
595                 Thread::start();
596         }
597 }
598
599 void Record::start_over()
600 {
601         stop_writing();
602         Batch *batch = get_current_batch();
603         if( batch ) batch->start_over();
604         record_gui->update_batches();
605 }
606
607 void Record::stop_operation()
608 {
609         stop_writing();
610         stop_input_threads();
611 }
612
613 int Record::cron_active()
614 {
615         return !record_thread ? 0 : record_thread->cron_active;
616 }
617
618 void Record::close_output_file()
619 {
620         file_lock->lock();
621         if( file ) {
622                 mwindow->sighandler->pull_file(file);
623                 file->close_file();
624                 delete file;
625                 file = 0;
626         }
627         file_lock->unlock();
628         record_gui->update_batches();
629 }
630
631 void Record::toggle_label()
632 {
633         Batch *batch = get_current_batch();
634         if( batch ) batch->toggle_label(current_display_position());
635         record_gui->update_labels(current_display_position());
636 }
637
638 void Record::clear_labels()
639 {
640         Batch *batch = get_current_batch();
641         if( batch ) batch->clear_labels();
642         record_gui->update_labels(0);
643 }
644
645 int Record::get_fragment_samples()
646 {
647         const int min_samples = 1024, max_samples = 32768;
648         int samples, low_bit;
649         samples = default_asset->sample_rate / SESSION->record_speed;
650         if( samples < min_samples ) samples = min_samples;
651         else if( samples > max_samples ) samples = max_samples;
652         // loop until only one bit left standing
653         while( (low_bit=(samples & ~(samples-1))) != samples )
654                 samples += low_bit;
655         return samples;
656 }
657
658 int Record::get_buffer_samples()
659 {
660         int fragment_samples = get_fragment_samples();
661         if( !fragment_samples ) return 0;
662         int fragments = (SESSION->record_write_length+fragment_samples-1) / fragment_samples;
663         if( fragments < 1 ) fragments = 1;
664         return fragments * fragment_samples;
665 }
666
667 Batch* Record::get_current_batch()
668 {
669         return record_batches.get_current_batch();
670 }
671
672 Batch* Record::get_editing_batch()
673 {
674         return record_batches.get_editing_batch();
675 }
676
677 int Record::get_next_batch(int incr)
678 {
679         int i = current_batch();
680         if( i >= 0 ) {
681                 i += incr;
682                 int total_batches = record_batches.total();
683                 while( i < total_batches ) {
684                         if( record_batches[i]->enabled ) return i;
685                         ++i;
686                 }
687         }
688         return -1;
689 }
690
691 const char* Record::current_mode()
692 {
693         Batch *batch = get_current_batch();
694         return batch ? Batch::mode_to_text(batch->record_mode) : "";
695 }
696
697 double Record::current_display_position()
698 {
699 //printf("Record::current_display_position "
700 //  _LD " " _LD "\n", total_samples, total_frames)
701         double result = -1.;
702         Asset *asset = default_asset;
703         if( writing_file ) {
704                 if( asset->video_data && record_video )
705                         result = (double) written_frames / asset->frame_rate;
706                 else if( asset->audio_data && record_audio )
707                         result = (double) written_samples / asset->sample_rate;
708         }
709         if( result < 0. ) {
710                 if( asset->video_data && record_video )
711                         result = (double) total_frames / asset->frame_rate;
712                 else if( asset->audio_data && record_audio )
713                         result = (double) total_samples / asset->sample_rate;
714                 else
715                         result = (double) total_time.get_difference() / 1000.;
716         }
717         return result;
718 }
719
720 const char* Record::current_source()
721 {
722         Batch *batch = get_current_batch();
723         return batch ? batch->get_source_text() : _("Unknown");
724 }
725
726 Asset* Record::current_asset()
727 {
728         Batch *batch = get_current_batch();
729         return batch ? batch->asset : 0;
730 }
731
732 Channel *Record::get_current_channel()
733 {
734         return current_channel;
735 }
736
737 Channel *Record::get_editing_channel()
738 {
739         Batch *batch = get_editing_batch();
740         return batch ? batch->channel : 0;
741 }
742
743 ArrayList<Channel*>* Record::get_video_inputs()
744 {
745         return default_asset->video_data && vdevice ? vdevice->get_inputs() : 0;
746 }
747
748
749 int64_t Record::timer_position()
750 {
751         timer_lock->lock("RecordAudio::timer_positioin");
752         int samplerate = default_asset->sample_rate;
753         int64_t result = timer.get_scaled_difference(samplerate);
754         result += session_sample_offset;
755         timer_lock->unlock();
756         return result;
757 }
758
759 void Record::reset_position(int64_t position)
760 {
761         timer_lock->lock("RecordAudio::reset_position");
762         session_sample_offset = position;
763         device_sample_offset = adevice ? adevice->current_position() : 0;
764         timer.update();
765         timer_lock->unlock();
766 }
767
768 void Record::update_position()
769 {
770         int64_t position = sync_position();
771         reset_position(position);
772         current_frame = current_sample = 0;
773         audio_time = video_time = -1.;
774 }
775
776 int64_t Record::adevice_position()
777 {
778         timer_lock->lock("RecordAudio::adevice_position");
779         int64_t result = adevice->current_position();
780         result += session_sample_offset - device_sample_offset;
781         timer_lock->unlock();
782         return result;
783 }
784
785 int64_t Record::sync_position()
786 {
787         int64_t sync_position = -1;
788         double sync_time = -1.;
789         double next_audio_time = -1.;
790         double next_video_time = -1.;
791
792         if( current_frame == 0 && current_sample == 0 ) {
793                 audio_time = video_time = -1.;
794                 reset_position(0);
795         }
796         switch( SESSION->record_positioning ) {
797         case RECORD_POS_TIMESTAMPS:
798                 if( default_asset->video_data && record_video )
799                         next_video_time = vdevice->get_timestamp();
800                 if( default_asset->audio_data && record_audio ) {
801                         next_audio_time =
802                                  !adevice->is_monitoring() || writing_file > 0 ?
803                                         adevice->get_itimestamp() :
804                                         adevice->get_otimestamp();
805                 }
806                 if( next_audio_time >= 0. )
807                         sync_time = next_audio_time;
808                 else if( next_video_time > 0. )
809                         sync_time = next_video_time;
810                 if( sync_time >= 0. ) {
811                         sync_position = sync_time * default_asset->sample_rate;
812                 }
813                 if( sync_position >= 0 ) break;
814         case RECORD_POS_DEVICE:
815                 if( default_asset->audio_data && record_audio )
816                         sync_position = adevice_position();
817                 if( sync_position > 0 ) break;
818         case RECORD_POS_SOFTWARE:
819                 sync_position = timer_position();
820                 if( sync_position > 0 ) break;
821         case RECORD_POS_SAMPLE:
822         default:
823                 sync_position = current_sample;
824                 break;
825         }
826
827         if( next_video_time < 0. )
828                 next_video_time = current_frame / default_asset->frame_rate;
829         if( next_video_time > video_time )
830                 video_time = next_video_time;
831         if( next_audio_time < 0. )
832                 next_audio_time = (double)sync_position / default_asset->sample_rate;
833         if( next_audio_time > audio_time )
834                 audio_time = next_audio_time;
835
836         return sync_position;
837 }
838
839
840 void Record::adevice_drain()
841 {
842         if( adevice && record_audio ) {
843                 adevice->stop_audio(0);
844                 adevice->start_recording();
845         }
846 }
847
848
849 #define dbmsg if( debug ) printf
850 void Record::resync()
851 {
852         dropped = behind = 0;
853         int64_t audio_position = sync_position();
854         double audiotime = (double) audio_position / default_asset->sample_rate;
855         double diff = video_time - audiotime;
856         const int debug = 0;
857         dbmsg("resync video %f audio %f/%f diff %f",
858                 video_time, audiotime, audio_time, diff);
859         if( fabs(diff) > 5. ) {
860                 dbmsg("  drain audio");
861 // jam job dvb file tesing, comment next line
862                 record_channel->drain_audio();
863         }
864         else if( diff > 0. ) {
865                 int64_t delay = (int64_t)(1000.0 * diff);
866                 dbmsg("  delay %8jd", delay);
867                 if( delay > 500 ) {
868                         video_time = audio_time = -1.;
869                         delay = 500;
870                 }
871                 if( delay > 1 )
872                         Timer::delay(delay);
873         }
874         else {
875                 behind = (int)(-diff * default_asset->frame_rate);
876                 dbmsg("  behind %d", behind);
877                 if( behind > 1 && fill_underrun_frames ) {
878                         dropped = behind > 3 ? 3 : behind-1;
879                         dbmsg("  dropped %d", dropped);
880                 }
881         }
882         dbmsg("\n");
883         int frames = dropped + 1;
884         current_frame += frames;
885         total_frames += frames;
886         record_gui->update_video(dropped, behind);
887         if( dropped > 0 && drop_overrun_frames )
888                 if( vdevice ) vdevice->drop_frames(dropped);
889 }
890
891
892 void Record::close_audio_input()
893 {
894         adevice_lock->lock();
895         if( adevice ) {
896                 adevice->close_all();
897                 delete adevice;
898                 adevice = 0;
899         }
900         adevice_lock->unlock();
901 }
902
903 void Record::close_video_input()
904 {
905         vdevice_lock->lock();
906         if( vdevice ) {
907                 vdevice->close_all();
908                 delete vdevice;
909                 vdevice = 0;
910         }
911         vdevice_lock->unlock();
912 }
913
914 void Record::close_input_devices()
915 {
916         close_audio_input();
917         close_video_input();
918 }
919
920 void Record::stop_audio_thread()
921 {
922         if( record_audio ) {
923                 record_audio->stop_recording();
924                 delete record_audio;
925                 record_audio = 0;
926         }
927         close_audio_input();
928         recording = 0;
929 }
930
931 void Record::stop_video_thread()
932 {
933         if( record_video ) {
934                 record_video->stop_recording();
935                 delete record_video;
936                 record_video = 0;
937         }
938         close_video_input();
939         capturing = 0;
940         single_frame = 0;
941 }
942
943 void Record::stop_input_threads()
944 {
945         pause_lock->lock("Record::stop_input_threads");
946         stop_skimming();
947         stop_playback();
948         stop_audio_thread();
949         stop_video_thread();
950         pause_lock->unlock();
951 }
952
953 void Record::stop_playback()
954 {
955         if( record_monitor )
956                 record_monitor->stop_playback();
957 }
958
959 void Record::open_audio_input()
960 {
961         close_audio_input();
962         adevice_lock->lock();
963 // Create devices
964         if( default_asset->audio_data )
965                 adevice = new AudioDevice(mwindow);
966 // Configure audio
967         if( adevice ) {
968                 int sw_pos = SESSION->record_positioning == RECORD_POS_SOFTWARE;
969                 adevice->set_software_positioning(sw_pos);
970                 adevice->open_input(SESSION->aconfig_in, SESSION->vconfig_in,
971                         default_asset->sample_rate, get_fragment_samples(),
972                         default_asset->channels, SESSION->real_time_record);
973                 adevice->start_recording();
974                 adevice->open_monitor(SESSION->playback_config->aconfig,monitor_audio);
975                 adevice->set_vdevice(vdevice);
976                 if( vdevice ) vdevice->set_adevice(adevice);
977         }
978         adevice_lock->unlock();
979 }
980
981 void Record::open_video_input()
982 {
983         close_video_input();
984         vdevice_lock->lock();
985         if( default_asset->video_data )
986                 vdevice = new VideoDevice(mwindow);
987 // Initialize video
988         if( vdevice ) {
989                 vdevice->set_quality(default_asset->jpeg_quality);
990                 vdevice->open_input(SESSION->vconfig_in, video_x, video_y,
991                         video_zoom, default_asset->frame_rate);
992 // Get configuration parameters from device probe
993                 color_model = vdevice->get_best_colormodel(default_asset);
994                 master_channel->copy_usage(vdevice->channel);
995                 picture->copy_usage(vdevice->picture);
996                 vdevice->set_field_order(reverse_interlace);
997                 vdevice->set_adevice(adevice);
998                 if( adevice ) adevice->set_vdevice(vdevice);
999                 set_dev_channel(get_current_channel());
1000         }
1001         vdevice_lock->unlock();
1002 }
1003
1004 void Record::start_audio_thread()
1005 {
1006         open_audio_input();
1007         if( !record_audio ) {
1008                 total_samples = current_sample = 0;  audio_time = -1.;
1009                 record_audio = new RecordAudio(mwindow,this);
1010                 record_audio->arm_recording();
1011                 record_audio->start_recording();
1012         }
1013         recording = 1;
1014 }
1015
1016 void Record::start_video_thread()
1017 {
1018         open_video_input();
1019         if( !record_video ) {
1020                 total_frames = current_frame = 0;  video_time = -1.;
1021                 record_video = new RecordVideo(mwindow,this);
1022                 record_video->arm_recording();
1023                 record_video->start_recording();
1024         }
1025         capturing = 1;
1026 }
1027
1028 void Record::start_input_threads()
1029 {
1030         behind = 0;
1031         input_threads_pausing = 0;
1032         if( default_asset->audio_data )
1033                 start_audio_thread();
1034         if( default_asset->video_data )
1035                 start_video_thread();
1036         start_skimming();
1037 }
1038
1039 void Record::pause_input_threads()
1040 {
1041         pause_lock->lock("Record::pause_input_threads");
1042         input_threads_pausing = 1;
1043         stop_skimming();
1044         adevice_lock->lock();
1045         vdevice_lock->lock();
1046         if( record_audio )
1047                 record_audio->pause_recording();
1048         if( record_video )
1049                 record_video->pause_recording();
1050 }
1051
1052 void Record::resume_input_threads()
1053 {
1054         if( record_audio )
1055                 record_audio->resume_recording();
1056         if( record_video )
1057                 record_video->resume_recording();
1058         vdevice_lock->unlock();
1059         adevice_lock->unlock();
1060         input_threads_pausing = 0;
1061         start_skimming();
1062         pause_lock->unlock();
1063
1064 }
1065
1066 int Record::start_toc()
1067 {
1068         if( !mwindow->edl->session->record_realtime_toc ) return 0;
1069         Batch *batch = get_current_batch();
1070         Asset *asset = batch->asset;
1071         char source_filename[BCTEXTLEN], toc_path[BCTEXTLEN];
1072         IndexFile::get_index_filename(source_filename,
1073                 mwindow->preferences->index_directory,
1074                 toc_path, asset->path,".toc");
1075         if( default_asset->video_data )
1076                 return vdevice->start_toc(asset->path, toc_path);
1077         if( default_asset->audio_data )
1078                 return adevice->start_toc(asset->path, toc_path);
1079         return -1;
1080 }
1081
1082 int Record::start_record(int fd)
1083 {
1084         start_toc();
1085         if( default_asset->video_data )
1086                 return vdevice->start_record(fd);
1087         if( default_asset->audio_data )
1088                 return adevice->start_record(fd);
1089         return -1;
1090 }
1091
1092 void Record::start_writing_file()
1093 {
1094         if( !writing_file ) {
1095                 written_frames = 0;
1096                 written_samples = 0;
1097                 do_video = File::supports_video(default_asset->format);
1098                 do_audio = File::supports_audio(default_asset->format);
1099                 if( single_frame ) do_audio = 0;
1100                 if( !do_video && single_frame )
1101                         single_frame = 0;
1102                 else if( !open_output_file() )
1103                         writing_file = default_asset->format == FILE_MPEG ? -1 : 1;
1104                 if( do_audio && record_audio && writing_file > 0 ) {
1105                         int buffer_samples = get_buffer_samples();
1106                         record_audio->set_write_buffer_samples(buffer_samples);
1107                         file->start_audio_thread(buffer_samples, FILE_RING_BUFFERS);
1108                 }
1109                 if( do_video && record_video && writing_file > 0 ) {
1110                         int disk_frames = SESSION->video_write_length;
1111                         int cmodel = vdevice->get_best_colormodel(default_asset);
1112                         int cpress = vdevice->is_compressed(1, 0);
1113                         file->start_video_thread(disk_frames, cmodel, FILE_RING_BUFFERS, cpress);
1114                 }
1115                 if( writing_file < 0 ) {
1116                         int fd = file->record_fd();
1117                         if( fd >= 0 )
1118                                 start_record(fd);
1119                 }
1120                 if( writing_file ) {
1121                         record_gui->start_flash_batch();
1122                         if( SESSION->record_sync_drives ) {
1123                                 drivesync = new DriveSync();
1124                                 drivesync->start();
1125                         }
1126                 }
1127         }
1128         update_position();
1129 }
1130
1131 int Record::stop_record()
1132 {
1133         if( default_asset->video_data )
1134                 return vdevice->stop_record();
1135         if( default_asset->audio_data )
1136                 return adevice->stop_record();
1137         return -1;
1138 }
1139
1140 void Record::flush_buffer()
1141 {
1142         if( record_audio )
1143                 record_audio->flush_buffer();
1144         if( record_video )
1145                 record_video->flush_buffer();
1146 }
1147
1148 void Record::stop_writing_file()
1149 {
1150         record_gui->stop_flash_batch();
1151         if( !writing_file ) return;
1152         if( writing_file > 0 )
1153                 flush_buffer();
1154         if( writing_file < 0 )
1155                 stop_record();
1156         close_output_file();
1157         writing_file = 0;
1158         Asset *asset = current_asset();
1159         asset->audio_length = written_samples;
1160         asset->video_length = written_frames;
1161         record_gui->flash_batch();
1162         if( drivesync ) {
1163                 drivesync->done = 1;
1164                 delete drivesync;
1165                 drivesync = 0;
1166         }
1167 }
1168
1169 void Record::stop_writing()
1170 {
1171         if( writing_file ) {
1172                 pause_input_threads();
1173                 stop_writing_file();
1174                 resume_input_threads();
1175         }
1176 }
1177
1178
1179 void Record::start_cron_thread()
1180 {
1181         if( cron_active() < 0 ) {
1182                 delete record_thread;
1183                 record_thread = 0;
1184         }
1185         if( !record_thread ) {
1186                 record_thread = new RecordThread(mwindow,this);
1187                 record_thread->start();
1188                 record_gui->disable_batch_buttons();
1189                 record_gui->update_cron_status(_("Running"));
1190         }
1191 }
1192
1193 void Record::stop_cron_thread(const char *msg)
1194 {
1195         if( record_thread ) {
1196                 delete record_thread;
1197                 record_thread = 0;
1198                 record_gui->enable_batch_buttons();
1199                 record_gui->update_cron_status(msg);
1200         }
1201 }
1202
1203 void Record::set_power_off(int value)
1204 {
1205         power_off = value;
1206         record_gui->power_off->update(value);
1207 }
1208
1209 int Record::set_video_picture()
1210 {
1211         if( default_asset->video_data && vdevice )
1212                 vdevice->set_picture(picture);
1213         return 0;
1214 }
1215
1216 void Record::set_translation(int x, int y)
1217 {
1218         video_x = x;
1219         video_y = y;
1220         if(default_asset->video_data && vdevice)
1221                 vdevice->set_translation(video_x, video_y);
1222 }
1223
1224 int Record::set_channel(Channel *channel)
1225 {
1226         if( !channel ) return 1;
1227 printf("set_channel %s\n",channel->title);
1228         if( record_channel->set(channel) ) return 1;
1229         RecordMonitorGUI *window = record_monitor->window;
1230         window->lock_window("Record::set_channel");
1231         window->channel_picker->channel_text->update(channel->title);
1232         window->unlock_window();
1233         return 0;
1234 }
1235
1236 int Record::set_channel_no(int chan_no)
1237 {
1238         if( chan_no < 0 || chan_no >= channeldb->size() ) return 1;
1239         Channel *channel = channeldb->get(chan_no);
1240         return set_channel(channel);
1241 }
1242
1243 int Record::channel_down()
1244 {
1245         Channel *channel = get_current_channel();
1246         if( !channel || !channeldb->size() ) return 1;
1247         int n = channeldb->number_of(channel);
1248         if( n < 0 ) return 1;
1249         if( --n < 0 ) n =  channeldb->size() - 1;
1250         return set_channel_no(n);
1251 }
1252
1253 int Record::channel_up()
1254 {
1255         Channel *channel = get_current_channel();
1256         if( !channel || !channeldb->size() ) return 1;
1257         int n = channeldb->number_of(channel);
1258         if( n < 0 ) return 1;
1259         if( ++n >=  channeldb->size() ) n = 0;
1260         return set_channel_no(n);
1261 }
1262
1263 int Record::set_channel_name(const char *name)
1264 {
1265         Channel *channel = 0;
1266         int ch = 0, nch = channeldb->size();
1267         while( ch < nch ) {
1268                 channel = channeldb->get(ch);
1269                 if( channel && !channel->cstrcmp(name) ) break;
1270                 ++ch;
1271         }
1272         if( ch >= nch || !channel ) return 1;
1273         return set_channel(channel);
1274 }
1275
1276 void Record::set_batch_channel_no(int chan_no)
1277 {
1278         Channel *channel = channeldb->get(chan_no);
1279         if( channel ) {
1280                 Batch *batch = get_editing_batch();
1281                 if( batch ) batch->channel = channel;
1282                 record_gui->batch_source->update(channel->title);
1283         }
1284 }
1285
1286 void Record::set_dev_channel(Channel *channel)
1287 {
1288         // should be tuner device, not vdevice
1289         if( channel && vdevice &&
1290             (!this->channel || *channel != *this->channel) ) {
1291                 current_channel = channel;
1292                 if( this->channel ) delete this->channel;
1293                 this->channel = new Channel(channel);
1294                 vdevice->set_channel(channel);
1295                 int strk = !SESSION->decode_subtitles ? -1 : SESSION->subtitle_number;
1296                 vdevice->set_captioning(strk);
1297                 set_video_picture();
1298 printf("new channel %s, has_signal=%d\n",channel->title,vdevice->has_signal());
1299                 total_frames = 0;
1300                 total_samples = 0;
1301                 total_time.update();
1302         }
1303 }
1304
1305 /* widget holds xlock and set_channel pauses rendering, deadlock */
1306 /*   use a background thread to update channel after widget sets it */
1307 RecordChannel::RecordChannel(Record *record)
1308  : Thread(1, 0, 0)
1309 {
1310         this->record = record;
1311         change_channel = new Condition(0,"RecordSetChannel::change_channel");
1312         channel_lock = new Condition(1,"Record::channel_lock",1);
1313         new_channel = 0;
1314         Thread::start();
1315 }
1316
1317 RecordChannel::~RecordChannel()
1318 {
1319         done = 1;
1320         change_channel->unlock();
1321         Thread::join();
1322         delete change_channel;
1323         delete channel_lock;
1324 }
1325
1326 int RecordChannel::set(Channel *channel)
1327 {
1328         if( !channel || new_channel ) return 1;
1329         new_channel = channel;
1330         channel_lock->lock();        // block has_signal
1331         change_channel->unlock();    // resume channel changer thread
1332         return 0;
1333 }
1334
1335 void RecordChannel::drain_audio()
1336 {
1337         if( !audio_drain ) {
1338                 audio_drain = 1;
1339                 change_channel->unlock();
1340         }
1341 }
1342
1343 void RecordChannel::run()
1344 {
1345         done = 0;
1346         while( !done ) {
1347                 change_channel->lock();
1348                 if( done ) break;
1349                 if( !new_channel && !audio_drain ) continue;
1350                 record->pause_input_threads();
1351                 if( new_channel ) {
1352                         record->set_dev_channel(new_channel);
1353                         record->record_gui->reset_video();
1354                         record->record_gui->reset_audio();
1355                         audio_drain = 0;
1356                 }
1357                 if( audio_drain ) {
1358                         audio_drain = 0;
1359                         record->adevice_drain();
1360                 }
1361                 record->update_position();
1362                 record->resume_input_threads();
1363                 if( new_channel ) {
1364                         new_channel = 0;
1365                         channel_lock->unlock();
1366                 }
1367         }
1368 }
1369
1370 int Record::has_signal()
1371 {
1372         record_channel->channel_lock->lock("Record::has_signal");
1373         record_channel->channel_lock->unlock();
1374         vdevice_lock->lock();
1375         int result = vdevice ? vdevice->has_signal() : 0;
1376         vdevice_lock->unlock();
1377         return result;
1378 }
1379
1380 int Record::create_channeldb(ArrayList<Channel*> *channeldb)
1381 {
1382         return vdevice ? vdevice->create_channeldb(channeldb) : 1;
1383 }
1384
1385
1386 void Record::set_audio_monitoring(int mode)
1387 {
1388         update_position();
1389         monitor_audio = mode;
1390         if( record_audio )
1391                 record_audio->set_monitoring(mode);
1392         record_gui->lock_window("Record::set_audio_monitoring");
1393         if( record_gui->monitor_audio )
1394                 record_gui->monitor_audio->update(mode);
1395         record_gui->unlock_window();
1396 }
1397
1398 void Record::set_audio_metering(int mode)
1399 {
1400         metering_audio = mode;
1401         record_gui->lock_window("Record::set_audio_metering");
1402         if( record_gui->meter_audio )
1403                 record_gui->meter_audio->update(mode);
1404         record_gui->unlock_window();
1405         RecordMonitorGUI *window = record_monitor->window;
1406         window->lock_window("Record::set_audio_metering 1");
1407         window->resize_event(window->get_w(),window->get_h());
1408         window->unlock_window();
1409 }
1410
1411
1412 void Record::set_video_monitoring(int mode)
1413 {
1414         monitor_video = mode;
1415         record_gui->lock_window("Record::set_video_monitoring");
1416         if( record_gui->monitor_video )
1417                 record_gui->monitor_video->update(mode);
1418         record_gui->flush();
1419         record_gui->unlock_window();
1420 }
1421
1422 int Record::get_time_format()
1423 {
1424         return SESSION->time_format;
1425 }
1426
1427 int Record::set_record_mode(int value)
1428 {
1429         Batch *batch = get_editing_batch();
1430         batch->record_mode = value;
1431         record_gui->update_batches();
1432         return 0;
1433 }
1434
1435 int Record::check_batch_complete()
1436 {
1437         int result = 0;
1438         batch_lock->lock();
1439         if( writing_file && cron_active() > 0 ) {
1440                 Batch *batch = get_current_batch();
1441                 if( batch && batch->recorded > 0 &&
1442                         batch->record_mode == RECORD_TIMED &&
1443                         current_display_position() >= batch->record_duration ) {
1444                         batch->recorded = -1;
1445                         batch->enabled = 0;
1446                         record_gui->update_batches();
1447                         record_thread->batch_timed_lock->unlock();
1448                         result = 1;
1449                 }
1450         }
1451         batch_lock->unlock();
1452         return result;
1453 }
1454
1455
1456 int Record::skimming(void *vp, int track)
1457 {
1458         return ((Record*)vp)->skimming(track);
1459 }
1460
1461 int Record::skimming(int track)
1462 {
1463         int64_t framenum; uint8_t *tdat; int mw, mh;
1464         if( !vdevice ) return -1;
1465         if( vdevice->get_thumbnail(track, framenum, tdat, mw, mh) ) return 1;
1466         int pid, width, height;  double framerate;
1467         if( vdevice->get_video_info(track, pid, framerate, width, height, 0) ) return 1;
1468         if( !framerate ) return 1;
1469         return skim_thread->skim(pid,framenum,framerate, tdat,mw,mh,width,height);
1470 }
1471
1472 void Record::start_skimming()
1473 {
1474         if( commercial_check && vdevice && !skimming_active ) {
1475                 skimming_active = 1;
1476                 skim_thread->start(mwindow->commercials);
1477                 vdevice->set_skimming(0, 0, skimming, this);
1478         }
1479 }
1480
1481 void Record::stop_skimming()
1482 {
1483         if( skimming_active && vdevice ) {
1484                 skimming_active = 0;
1485                 vdevice->set_skimming(0, 0, 0, 0);
1486                 skim_thread->stop();
1487         }
1488 }
1489
1490 void Record::update_skimming(int v)
1491 {
1492         if( (commercial_check=v) != 0 )
1493                 start_skimming();
1494         else
1495                 stop_skimming();
1496 }
1497
1498 RecordRemoteHandler::RecordRemoteHandler(RemoteControl *remote_control)
1499  : RemoteHandler(remote_control->gui, GREEN)
1500 {
1501 }
1502
1503 RecordRemoteHandler::~RecordRemoteHandler()
1504 {
1505 }
1506
1507 void Record::
1508 display_video_text(int x, int y, const char *text, int font,
1509         int bg_color, int color, int alpha, double secs, double scale)
1510 {
1511 // gotta have a window for resources
1512         record_monitor->window->
1513                 display_video_text(x, y, text, font,
1514                         bg_color, color, alpha, secs, scale);
1515 }
1516
1517 void Record::
1518 display_cut_icon(int x, int y)
1519 {
1520         VFrame *cut_icon = *mwindow->theme->get_image_set("commercial");
1521         double scale = 3;
1522         x += cut_icon->get_w()*scale;  y += cut_icon->get_h()*scale;
1523         display_vframe(cut_icon, x, y, 200, 1.0, scale);
1524 }
1525
1526 #ifdef HAVE_DVB
1527 DeviceDVBInput *Record::
1528 dvb_device()
1529 {
1530         DeviceDVBInput *dvb_dev = !vdevice ? 0 :
1531                 (DeviceDVBInput *)vdevice->mpeg_device();
1532         if( !dvb_dev ) dvb_dev = !adevice ? 0 :
1533                 (DeviceDVBInput *)adevice->mpeg_device();
1534         return dvb_dev;
1535 }
1536 #endif
1537
1538 #if 0
1539
1540 void Record::
1541 display_vframe(VFrame *in, int x, int y, int alpha, double secs, double scale)
1542 {
1543         if( !channel ) return;
1544         if( !vdevice || vdevice->in_config->driver != CAPTURE_DVB ) return;
1545         DeviceDVBInput *dvb_input = dvb_device();
1546         if( !dvb_input ) return 1;
1547         zmpeg3_t *fd = dvb_input->get_src();
1548         if( !fd ) return;
1549         scale *= fd->video_height(channel->video_stream) / 1080.;
1550         int ww = in->get_w() * scale, hh = in->get_h() * scale;
1551         VFrame out(ww, hh, BC_YUV444P);
1552         BC_WindowBase::get_cmodels()->transfer(out.get_rows(), in->get_rows(),
1553                 out.get_y(), out.get_u(), out.get_v(),
1554                 in->get_y(), in->get_u(), in->get_v(),
1555                 0, 0, in->get_w(), in->get_h(),
1556                 0, 0, out.get_w(), out.get_h(),
1557                 in->get_color_model(), out.get_color_model(), 0,
1558                 in->get_bytes_per_line(), ww);
1559         int sz = ww * hh;  uint8_t *yuv = out.get_data(), aimg[sz];
1560         uint8_t *yp = yuv, *up = yuv+sz, *vp = yuv+2*sz, *ap = 0;
1561         if( alpha > 0 ) memset(ap=aimg, alpha, sz);
1562         else if( alpha < 0 ) ap = yp;
1563         fd->display_subtitle(channel->video_stream, 1, 1,
1564                                 yp,up,vp,ap, x,y,ww,hh, 0, secs*1000);
1565         dvb_input->put_src();
1566 }
1567
1568 void Record::
1569 undisplay_vframe()
1570 {
1571         if( !channel ) return;
1572         if( !vdevice || vdevice->in_config->driver != CAPTURE_DVB ) return;
1573         DeviceDVBInput *dvb_input = dvb_device();
1574         if( !dvb_input ) return 1;
1575         zmpeg3_t *fd = dvb_input->get_src();
1576         if( !fd ) return;
1577         fd->delete_subtitle(channel->video_stream, 1, 1);
1578         dvb_input->put_src();
1579 }
1580
1581 #else
1582
1583 void Record::
1584 display_vframe(VFrame *in, int x, int y, int alpha, double secs, double scale)
1585 {
1586         record_monitor->display_vframe(in, x, y, alpha, secs, scale);
1587 }
1588
1589 void Record::
1590 undisplay_vframe()
1591 {
1592         record_monitor->undisplay_vframe();
1593 }
1594
1595 #endif
1596
1597 int Record::
1598 display_channel_info()
1599 {
1600 #ifdef HAVE_DVB
1601         if( !channel ) return 1;
1602         if( !vdevice || vdevice->in_config->driver != CAPTURE_DVB ) return 1;
1603         DeviceDVBInput *dvb_input = dvb_device();
1604         if( !dvb_input ) return 1;
1605         int elem = channel->element;
1606         time_t tt;  time(&tt);
1607         struct tm ttm;  localtime_r(&tt,&ttm);
1608         int result = 1;
1609         char text[BCTEXTLEN];
1610         zmpeg3_t *fd = dvb_input->get_src();
1611         if( !fd ) return 1;
1612         for( int ord=0, i=0; ord<0x80; ) {
1613                 char *cp = text;
1614                 int len = fd->dvb.get_chan_info(elem,ord,i++,cp,BCTEXTLEN-2);
1615                 if( len < 0 ) { ++ord;  i = 0;  continue; }
1616                 struct tm stm = ttm, etm = ttm;
1617                 char wday[4], *bp = cp;  cp += len;
1618                 if( sscanf(bp, "%02d:%02d:%02d-%02d:%02d:%02d",
1619                         &stm.tm_hour, &stm.tm_min, &stm.tm_sec,
1620                         &etm.tm_hour, &etm.tm_min, &etm.tm_sec) != 6 ) continue;
1621                 while( bp<cp && *bp++!='\n' );
1622                 if( sscanf(bp, "(%3s) %04d/%02d/%02d", &wday[0],
1623                         &stm.tm_year, &stm.tm_mon, &stm.tm_mday) != 4 ) continue;
1624                 stm.tm_year -= 1900;  stm.tm_mon -= 1;
1625                 etm.tm_year = stm.tm_year;
1626                 etm.tm_mon = stm.tm_mon;
1627                 etm.tm_mday = stm.tm_mday;
1628                 time_t st = mktime(&stm), et = mktime(&etm);
1629                 if( et < st ) et += 24*3600;
1630                 if( tt < st || tt >= et ) continue;
1631                 int major=0, minor=0;
1632                 fd->dvb.get_channel(elem, major, minor);
1633                 char chan[64];  sprintf(chan, "%3d.%1d", major, minor);
1634                 for( i=0; i<5 && chan[i]!=0; ++i ) *bp++ = chan[i];
1635                 while( bp<cp && *bp++!='\n' );
1636                 int n = 1;
1637                 for( char *lp=bp; bp<cp; ++bp ) {
1638                         if( *bp == '\n' || ((bp-lp)>=60 && *bp==' ') ) {
1639                                 if( ++n >= 10 ) break;
1640                                 *(lp=bp) = '\n';
1641                         }
1642                 }
1643                 *bp = 0;
1644                 while( bp > text && *--bp == '\n' ) *bp = 0;
1645                 result = 0;
1646                 break;
1647         }
1648         dvb_input->put_src();
1649         if( !result )
1650                 display_video_text(20, 20, text,
1651                                 BIGFONT, WHITE, BLACK, 0, 3., 1.);
1652         return result;
1653 #else
1654         return 1;
1655 #endif
1656 }
1657
1658 int Record::
1659 display_channel_schedule()
1660 {
1661 #ifdef HAVE_DVB
1662         if( !channel ) return 1;
1663         if( !vdevice || vdevice->in_config->driver != CAPTURE_DVB ) return 1;
1664         DeviceDVBInput *dvb_input = dvb_device();
1665         if( !dvb_input ) return 1;
1666         int elem = channel->element;
1667         time_t tt;  time(&tt);
1668         struct tm ttm;  localtime_r(&tt,&ttm);
1669         char text[BCTEXTLEN];
1670         zmpeg3_t *fd = dvb_input->get_src();
1671         if( !fd ) return 1;
1672         RecordSchedule channel_schedule;
1673         for( int ord=0, i=0; ord<0x80; ) {
1674                 char *cp = text;
1675                 int len = fd->dvb.get_chan_info(elem,ord,i++,cp,BCTEXTLEN-2);
1676                 if( len < 0 ) { ++ord;  i = 0;  continue; }
1677                 struct tm stm = ttm, etm = ttm;
1678                 char wday[4], *bp = cp;  cp += len;
1679                 if( sscanf(bp, "%02d:%02d:%02d-%02d:%02d:%02d",
1680                         &stm.tm_hour, &stm.tm_min, &stm.tm_sec,
1681                         &etm.tm_hour, &etm.tm_min, &etm.tm_sec) != 6 ) continue;
1682                 while( bp<cp && *bp++!='\n' );
1683                 if( sscanf(bp, "(%3s) %04d/%02d/%02d", &wday[0],
1684                         &stm.tm_year, &stm.tm_mon, &stm.tm_mday) != 4 ) continue;
1685                 stm.tm_year -= 1900;  stm.tm_mon -= 1;
1686                 etm.tm_year = stm.tm_year;
1687                 etm.tm_mon = stm.tm_mon;
1688                 etm.tm_mday = stm.tm_mday;
1689                 time_t st = mktime(&stm), et = mktime(&etm);
1690                 if( et < st ) et += 24*3600;
1691                 if( tt >= et ) continue;
1692                 if( bp > text )*--bp = 0;
1693                 channel_schedule.append(new RecordScheduleItem(st, text));
1694         }
1695         dvb_input->put_src();
1696
1697         channel_schedule.sort_times();
1698         char *cp = text, *ep = cp+sizeof(text)-1;
1699         for( int i=0, n=0; i<channel_schedule.size(); ++i ) {
1700                 RecordScheduleItem *item = channel_schedule.get(i);
1701                 for( char *bp=item->title; cp<ep && *bp!=0; ++bp ) *cp++ = *bp;
1702                 if( cp < ep ) *cp++ = '\n';
1703                 if( ++n >= 12 ) break;
1704         }
1705         *cp = 0;
1706         while( cp > text && *--cp == '\n' ) *cp = 0;
1707
1708         display_video_text(20, 20, text,
1709                                 BIGFONT, WHITE, BLACK, 0, 3., 1.);
1710         return 0;
1711 #else
1712         return 1;
1713 #endif
1714 }
1715
1716 void Record::clear_keybfr()
1717 {
1718         keybfr[0] = 0;
1719         undisplay_vframe();
1720 }
1721
1722 void Record::add_key(int ch)
1723 {
1724         int n = 0;
1725         while( n<(int)sizeof(keybfr)-2 && keybfr[n] ) ++n;
1726         keybfr[n++] = ch;  keybfr[n] = 0;
1727         display_video_text(20, 20, keybfr,
1728                                 BIGFONT, WHITE, BLACK, 0, 3., 2.);
1729 }
1730
1731 int RecordRemoteHandler::remote_process_key(RemoteControl *remote_control, int key)
1732 {
1733         Record *record = remote_control->mwindow_gui->record;
1734         return record->remote_process_key(remote_control, key);
1735 }
1736
1737 int Record::remote_process_key(RemoteControl *remote_control, int key)
1738 {
1739         int ch = key;
1740
1741         switch( key ) {
1742         case KPENTER:
1743                 if( last_key == KPENTER ) {
1744                         set_channel_name(keybfr);
1745                         clear_keybfr();
1746                         break;
1747                 }
1748                 ch = '.';  // fall through
1749         case '0': if( last_key == '0' && ch == '0' ) {
1750                 clear_keybfr();
1751                 break;
1752         }
1753         case '1': case '2': case '3': case '4':
1754         case '5': case '6': case '7': case '8': case '9':
1755                 add_key(ch);
1756                 break;
1757         //case UP: case DOWN: case LEFT: case RIGHT:
1758         //case KPPLAY: case KPBACK: case KPFORW:
1759         case KPRECD:  case 'c': // start capture, mark endpoint
1760                 if( !deletions ) {
1761                         start_commercial_capture();
1762                         if( adevice )
1763                                 set_play_gain(0.075);
1764                 }
1765                 else {
1766                         mark_commercial_capture(DEL_MARK);
1767                         blink_status->update();
1768                 }
1769                 display_cut_icon(10,20);
1770                 break;
1771         case KPSTOP:  case 'd': // end capture, start cutting
1772                 remote_control->set_color(YELLOW);
1773                 stop_commercial_capture(1);
1774                 break;
1775         case KPAUSE:  case 'x': // ignore current commercial
1776                 mark_commercial_capture(DEL_SKIP);
1777                 break;
1778         case KPBACK:  case 'a': // toggle mute audio
1779                 if( !monitor_audio ) { set_mute_gain(1);  set_play_gain(1); }
1780                 set_audio_monitoring(monitor_audio ? 0 : 1);
1781                 break;
1782         case 'm': // toggle metering audio
1783                 set_audio_metering(metering_audio ? 0 : 1);
1784                 break;
1785         case KPPLAY:  case 's': // ignore previous endpoint
1786                 mark_commercial_capture(DEL_OOPS);
1787                 break;
1788         case KPFWRD:  case KPSLASH:
1789                 display_channel_info();
1790                 break;
1791         case KPMAXW:  case KPSTAR:
1792                 display_channel_schedule();
1793                 break;
1794         case KPCHUP:  case KPPLUS:
1795                 channel_up();
1796                 break;
1797         case KPCHDN:  case KPMINUS:
1798                 channel_down();
1799                 break;
1800         case 'f': {
1801                 Canvas *canvas = record_monitor->window->canvas;
1802                 if( !canvas->get_fullscreen() )
1803                         canvas->start_fullscreen();
1804                 else
1805                         canvas->stop_fullscreen();
1806                 break; }
1807         default:
1808                 return -1;
1809         }
1810
1811         last_key = key;
1812         return 1;
1813 }
1814
1815
1816 int Record::start_commercial_capture()
1817 {
1818         if( deletions != 0 ) return 1;
1819         Channel *channel = get_current_channel();
1820         if( !channel ) return 1;
1821         int track = channel->video_stream;
1822         int pid = vdevice->get_video_pid(track);
1823         if( pid < 0 ) return 1;
1824         time_t st;  time(&st);
1825         struct tm stm;  localtime_r(&st, &stm);
1826         char file_path[BCTEXTLEN];
1827         sprintf(file_path,"/tmp/del%04d%02d%02d-%02d%02d%02d.ts",
1828                 stm.tm_year+1900, stm.tm_mon+1, stm.tm_mday,
1829                 stm.tm_hour, stm.tm_min, stm.tm_sec);
1830         commercial_fd = open(file_path,O_RDWR+O_CREAT,0666);
1831         if( commercial_fd < 0 ) return 1;
1832         if( vdevice->start_record(commercial_fd, 0x800000) ) {
1833                 close(commercial_fd);
1834                 commercial_fd = -1;
1835                 return 1;
1836         }
1837         commercial_start_time = st;
1838         printf("del to %s\n", file_path);
1839         deletions = new Deletions(pid, file_path);
1840         mark_commercial_capture(DEL_START);
1841         blink_status->start();
1842         return 0;
1843 }
1844
1845 int Record::mark_commercial_capture(int action)
1846 {
1847         if( deletions == 0 ) return 1;
1848         double time = vdevice->get_timestamp();
1849         printf("dele %f\n", time);
1850         deletions->append(new Dele(time, action));
1851         return 0;
1852 }
1853
1854 void Record::remote_fill_color(int color)
1855 {
1856         mwindow->gui->remote_control->fill_color(color);
1857 }
1858
1859 void Record::set_status_color(int color)
1860 {
1861         status_color = color;
1862         remote_fill_color(status_color);
1863 }
1864
1865 void Record::set_mute_gain(double gain)
1866 {
1867         gain = (mute_gain = gain) * play_gain;
1868         if( adevice ) adevice->set_play_gain(gain);
1869 }
1870
1871 void Record::set_play_gain(double gain)
1872 {
1873         gain = mute_gain * (play_gain = gain);
1874         if( adevice ) adevice->set_play_gain(gain);
1875 }
1876
1877 int Record::stop_commercial_capture(int run_job)
1878 {
1879         if( deletions == 0 ) return 1;
1880         if( run_job ) blink_status->stop();
1881         set_play_gain(1);
1882
1883         vdevice->stop_record();
1884         commercial_start_time = -1;
1885         if( commercial_fd >= 0 ) {
1886                 close(commercial_fd);
1887                 commercial_fd = -1;
1888         }
1889         int result = -1;
1890         if( run_job ) {
1891                 char del_filename[BCTEXTLEN];
1892                 strcpy(del_filename, deletions->file_path());
1893                 strcpy(strrchr(del_filename, '.'),".del");
1894                 if( !deletions->write_dels(del_filename) ) {
1895                         int pid = spawn("cutads %s",del_filename);
1896                         if( pid > 0 ) {
1897                                 cut_pids.append(pid);
1898                                 cutads_status->start_waiting();
1899                                 result = 0;
1900                         }
1901                 }
1902         }
1903         else {
1904                 remove_file(deletions->filepath);
1905         }
1906         delete deletions;  deletions = 0;
1907         return result;
1908 }
1909
1910 int Record::
1911 spawn(const char *fmt, ...)
1912 {
1913         const char *exec_path = File::get_cinlib_path();
1914         char cmd[BCTEXTLEN], *cp = cmd, *ep = cp+sizeof(cmd)-1;
1915         va_list ap;  va_start(ap, fmt);
1916         cp += snprintf(cp, ep-cp, "exec %s/", exec_path);
1917         cp += vsnprintf(cp, ep-cp, fmt, ap);  va_end(ap);
1918         *cp = 0;
1919         pid_t pid = vfork();
1920         if( pid < 0 ) return -1;
1921         if( pid > 0 ) return pid;
1922         char *const argv[4] = { (char*) "/bin/sh", (char*) "-c", cmd, 0 };
1923         execvp(argv[0], &argv[0]);
1924         return -1;
1925 }
1926
1927 int Record::
1928 commercial_jobs()
1929 {
1930         for( int i=0; i<cut_pids.size(); ) {
1931                 int status, pid = cut_pids.get(i);
1932                 if( waitpid(pid, &status, WNOHANG) ) {
1933                         cut_pids.remove(pid);
1934                         continue;
1935                 }
1936                 ++i;
1937         }
1938         return cut_pids.size();
1939 }
1940
1941
1942 RecordCutAdsStatus::
1943 RecordCutAdsStatus(Record *record)
1944  : Thread(1, 0, 0)
1945 {
1946         this->record = record;
1947         wait_lock = new Condition(0,"RecordCutAdsStatus::wait_lock",0);
1948         done = 0;
1949         start();
1950 }
1951
1952 RecordCutAdsStatus::
1953 ~RecordCutAdsStatus()
1954 {
1955         if( running() ) {
1956                 done = 1;
1957                 wait_lock->unlock();
1958                 cancel();
1959                 join();
1960         }
1961         delete wait_lock;
1962 }
1963
1964 void RecordCutAdsStatus::
1965 start_waiting()
1966 {
1967         wait_lock->unlock();
1968 }
1969
1970 void RecordCutAdsStatus::
1971 run()
1972 {
1973         int status, pgrp = getpgrp();
1974         while(!done) {
1975                 wait_lock->lock("RecordCutAdsStatus::run");
1976                 if( done ) break;
1977                 if( !record->commercial_jobs() ) continue;
1978                 record->set_status_color(YELLOW);
1979                 while( !done ) {
1980                         enable_cancel();
1981                         waitpid(-pgrp, &status, 0);
1982                         disable_cancel();
1983                         if( !record->commercial_jobs() ) break;
1984                 }
1985                 record->set_status_color(GREEN);
1986         }
1987 }
1988
1989 void RecordBlinkStatus::
1990 remote_color(int color)
1991 {
1992         record->remote_fill_color(color);
1993 }
1994
1995 void RecordBlinkStatus::
1996 update()
1997 {
1998         timer.update();
1999 }
2000
2001 void RecordBlinkStatus::
2002 start()
2003 {
2004         done = 0;
2005         update();
2006         Thread::start();
2007 }
2008
2009 void RecordBlinkStatus::
2010 stop()
2011 {
2012         done = 1;
2013         if( running() ) {
2014                 cancel();
2015                 join();
2016         }
2017 }
2018
2019 RecordBlinkStatus::
2020 RecordBlinkStatus(Record *record)
2021  : Thread(1, 0, 0)
2022 {
2023         this->record = record;
2024 }
2025
2026 RecordBlinkStatus::
2027 ~RecordBlinkStatus()
2028 {
2029         stop();
2030 }
2031
2032 void RecordBlinkStatus::
2033 run()
2034 {
2035         int color = YELLOW;
2036         while( !done ) {
2037                 remote_color(color);
2038                 enable_cancel();
2039                 usleep(500000);
2040                 disable_cancel();
2041                 color ^= YELLOW ^ BLUE;
2042                 if( timer.get_difference() > 10*60*1000 ) { // 10 minites
2043                         record->stop_commercial_capture(0);
2044                         done = 1;
2045                 }
2046         }
2047         remote_color(record->status_color);
2048 }
2049