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