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