rework batchrender, renderfarm improvements, ffmpeg audio quality, a few fixes
[goodguy/history.git] / cinelerra-5.1 / cinelerra / fileffmpeg.C
1
2 #include <stdio.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <string.h>
7 // work around for __STDC_CONSTANT_MACROS
8 #include <lzma.h>
9
10 #include "asset.h"
11 #include "bcwindowbase.h"
12 #include "bitspopup.h"
13 #include "ctype.h"
14 #include "ffmpeg.h"
15 #include "filebase.h"
16 #include "file.h"
17 #include "fileffmpeg.h"
18 #include "filesystem.h"
19 #include "indexfile.h"
20 #include "language.h"
21 #include "mainerror.h"
22 #include "mainprogress.h"
23 #include "mutex.h"
24 #include "preferences.h"
25 #include "videodevice.inc"
26
27 FileFFMPEG::FileFFMPEG(Asset *asset, File *file)
28   : FileBase(asset, file)
29 {
30         ff = 0;
31         if(asset->format == FILE_UNKNOWN)
32                 asset->format = FILE_FFMPEG;
33 }
34
35 FileFFMPEG::~FileFFMPEG()
36 {
37         delete ff;
38 }
39
40
41 FFMpegConfigNum::FFMpegConfigNum(BC_Window *window,
42                 int x, int y, char *title_text, int *output)
43  : BC_TumbleTextBox(window, *output, -1, INT_MAX, 100, y, 100)
44 {
45         this->window = window;
46         this->x = x;  this->y = y;
47         this->title_text = title_text;
48         this->output = output;
49 }
50
51 FFMpegConfigNum::~FFMpegConfigNum()
52 {
53 }
54
55 void FFMpegConfigNum::create_objects()
56 {
57         window->add_subwindow(title = new BC_Title(x, y, title_text));
58         BC_TumbleTextBox::create_objects();
59 }
60
61 int FFMpegConfigNum::update_param(const char *param, const char *opts)
62 {
63         char value[BCTEXTLEN];
64         if( !FileFFMPEG::get_ff_option(param, opts, value) ) {
65                 if( (*output = atoi(value)) < 0 ) {
66                         disable(1);
67                         return 0;
68                 }
69         }
70         BC_TumbleTextBox::update((int64_t)*output);
71         enable();
72         return 1;
73 }
74
75 int FFMpegConfigNum::handle_event()
76 {
77         *output = atoi(get_text());
78         return 1;
79 }
80
81 FFMpegAudioNum::FFMpegAudioNum(BC_Window *window,
82                 int x, int y, char *title_text, int *output)
83  : FFMpegConfigNum(window, x, y, title_text, output)
84 {
85 }
86
87 int FFMpegAudioBitrate::handle_event()
88 {
89         int ret = FFMpegAudioNum::handle_event();
90         Asset *asset = window()->asset;
91         if( asset->ff_audio_bitrate > 0 )
92                 window()->quality->disable();
93         else if( !window()->quality->get_textbox()->is_hidden() )
94                 window()->quality->enable();
95         return ret;
96 }
97
98 int FFMpegAudioQuality::handle_event()
99 {
100         int ret = FFMpegAudioNum::handle_event();
101         Asset *asset = window()->asset;
102         if( asset->ff_audio_quality >= 0 )
103                 window()->bitrate->disable();
104         else if( !window()->bitrate->get_textbox()->is_hidden() )
105                 window()->bitrate->enable();
106         return ret;
107 }
108
109 FFMpegVideoNum::FFMpegVideoNum(BC_Window *window,
110                 int x, int y, char *title_text, int *output)
111  : FFMpegConfigNum(window, x, y, title_text, output)
112 {
113 }
114
115 int FFMpegVideoBitrate::handle_event()
116 {
117         int ret = FFMpegVideoNum::handle_event();
118         Asset *asset = window()->asset;
119         if( asset->ff_video_bitrate > 0 )
120                 window()->quality->disable();
121         else if( !window()->quality->get_textbox()->is_hidden() )
122                 window()->quality->enable();
123         return ret;
124 }
125
126 int FFMpegVideoQuality::handle_event()
127 {
128         int ret = FFMpegVideoNum::handle_event();
129         Asset *asset = window()->asset;
130         if( asset->ff_video_quality >= 0 )
131                 window()->bitrate->disable();
132         else if( !window()->bitrate->get_textbox()->is_hidden() )
133                 window()->bitrate->enable();
134         return ret;
135 }
136
137 void FileFFMPEG::set_parameters(char *cp, int len, const char *bp)
138 {
139         char *ep = cp + len-2, ch = 0;
140         while( cp < ep && *bp != 0 ) { ch = *bp++; *cp++ = ch; }
141         if( ch != '\n' ) *cp++ = '\n';
142         *cp = 0;
143 }
144
145 void FileFFMPEG::get_parameters(BC_WindowBase *parent_window,
146                 Asset *asset, BC_WindowBase *&format_window,
147                 int audio_options, int video_options)
148 {
149         if(audio_options) {
150                 FFMPEGConfigAudio *window = new FFMPEGConfigAudio(parent_window, asset);
151                 format_window = window;
152                 window->create_objects();
153                 if( !window->run_window() )
154                         set_parameters(asset->ff_audio_options, sizeof(asset->ff_audio_options),
155                                  window->audio_options->get_text());
156                 delete window;
157         }
158         else if(video_options) {
159                 FFMPEGConfigVideo *window = new FFMPEGConfigVideo(parent_window, asset);
160                 format_window = window;
161                 window->create_objects();
162                 if( !window->run_window() )
163                         set_parameters(asset->ff_video_options, sizeof(asset->ff_video_options),
164                                  window->video_options->get_text());
165                 delete window;
166         }
167 }
168
169 int FileFFMPEG::check_sig(Asset *asset)
170 {
171         char *ptr = strstr(asset->path, ".pcm");
172         if( ptr ) return 0;
173         ptr = strstr(asset->path, ".raw");
174         if( ptr ) return 0;
175
176         FFMPEG ffmpeg(0);
177         int ret = !ffmpeg.init_decoder(asset->path) &&
178                 !ffmpeg.open_decoder() ? 1 : 0;
179         return ret;
180 }
181
182 void FileFFMPEG::get_info(char *path, char *text, int len)
183 {
184         char *cp = text;
185         FFMPEG ffmpeg(0);
186         cp += sprintf(cp, _("file path: %s\n"), path);
187         struct stat st;
188         int ret = 0;
189         if( stat(path, &st) < 0 ) {
190                 cp += sprintf(cp, _(" err: %s\n"), strerror(errno));
191                 ret = 1;
192         }
193         else {
194                 cp += sprintf(cp, _("  %jd bytes\n"), st.st_size);
195         }
196         if( !ret ) ret = ffmpeg.init_decoder(path);
197         if( !ret ) ret = ffmpeg.open_decoder();
198         if( !ret ) {
199                 cp += sprintf(cp, _("info:\n"));
200                 ffmpeg.info(cp, len-(cp-text));
201         }
202         else
203                 sprintf(cp, _("== open failed\n"));
204 }
205
206 int FileFFMPEG::get_video_info(int track, int &pid, double &framerate,
207                 int &width, int &height, char *title)
208 {
209         if( !ff ) return -1;
210         pid = ff->ff_video_pid(track);
211         framerate = ff->ff_frame_rate(track);
212         width = ff->ff_video_width(track);
213         height = ff->ff_video_height(track);
214         if( title ) *title = 0;
215         return 0;
216 }
217
218 int FileFFMPEG::get_audio_for_video(int vstream, int astream, int64_t &channel_mask)
219 {
220         if( !ff ) return 1;
221         return ff->ff_audio_for_video(vstream, astream, channel_mask);
222 }
223
224 int FileFFMPEG::select_video_stream(Asset *asset, int vstream)
225 {
226         if( !ff || !asset->video_data ) return 1;
227         asset->width = ff->ff_video_width(vstream);
228         asset->height = ff->ff_video_height(vstream);
229         if( (asset->video_length = ff->ff_video_frames(vstream)) < 2 )
230                 asset->video_length = asset->video_length < 0 ? 0 : -1;
231         asset->frame_rate = ff->ff_frame_rate(vstream);
232         return 0;
233 }
234
235 int FileFFMPEG::select_audio_stream(Asset *asset, int astream)
236 {
237         if( !ff || !asset->audio_data ) return 1;
238         asset->sample_rate = ff->ff_sample_rate(astream);
239         asset->audio_length = ff->ff_audio_samples(astream);
240         return 0;
241 }
242
243 int FileFFMPEG::open_file(int rd, int wr)
244 {
245         int result = 0;
246         if( ff ) return 1;
247         ff = new FFMPEG(this);
248
249         if( rd ) {
250                 result = ff->init_decoder(asset->path);
251                 if( !result ) result = ff->open_decoder();
252                 if( !result ) {
253                         int audio_channels = ff->ff_total_audio_channels();
254                         if( audio_channels > 0 ) {
255                                 asset->audio_data = 1;
256                                 asset->channels = audio_channels;
257                                 asset->sample_rate = ff->ff_sample_rate(0);
258                                 asset->audio_length = ff->ff_audio_samples(0);
259                                 strcpy(asset->acodec, ff->ff_audio_format(0));
260                         }
261                         int video_layers = ff->ff_total_video_layers();
262                         if( video_layers > 0 ) {
263                                 asset->video_data = 1;
264                                 if( !asset->layers ) asset->layers = video_layers;
265                                 asset->actual_width = ff->ff_video_width(0);
266                                 asset->actual_height = ff->ff_video_height(0);
267                                 if( !asset->width ) asset->width = asset->actual_width;
268                                 if( !asset->height ) asset->height = asset->actual_height;
269                                 if( !asset->video_length &&
270                                     (asset->video_length = ff->ff_video_frames(0)) < 2 )
271                                         asset->video_length = asset->video_length < 0 ? 0 : -1;
272                                 if( !asset->frame_rate ) asset->frame_rate = ff->ff_frame_rate(0);
273                                 strcpy(asset->vcodec, ff->ff_video_format(0));
274                         }
275                         IndexState *index_state = asset->index_state;
276                         index_state->read_markers(file->preferences->index_directory, asset->path);
277                 }
278         }
279         else if( wr ) {
280                 result = ff->init_encoder(asset->path);
281                 // must be in this order or dvdauthor will fail
282                 if( !result && asset->video_data )
283                         result = ff->open_encoder("video", asset->vcodec);
284                 if( !result && asset->audio_data )
285                         result = ff->open_encoder("audio", asset->acodec);
286         }
287         return result;
288 }
289
290 int FileFFMPEG::close_file()
291 {
292         delete ff;
293         ff = 0;
294         return 0;
295 }
296
297
298 int FileFFMPEG::write_samples(double **buffer, int64_t len)
299 {
300         if( !ff || len < 0 ) return -1;
301         int stream = 0;
302         int ret = ff->encode(stream, buffer, len);
303         return ret;
304 }
305
306 int FileFFMPEG::write_frames(VFrame ***frames, int len)
307 {
308         if( !ff ) return -1;
309         int ret = 0, layer = 0;
310         for(int i = 0; i < 1; i++) {
311                 for(int j = 0; j < len && !ret; j++) {
312                         VFrame *frame = frames[i][j];
313                         ret = ff->encode(layer, frame);
314                 }
315         }
316         return ret;
317 }
318
319
320 int FileFFMPEG::read_samples(double *buffer, int64_t len)
321 {
322         if( !ff || len < 0 ) return -1;
323         int ch = file->current_channel;
324         int64_t pos = file->current_sample;
325         int ret = ff->decode(ch, pos, buffer, len);
326         if( ret > 0 ) return 0;
327         memset(buffer,0,len*sizeof(*buffer));
328         return -1;
329 }
330
331 int FileFFMPEG::read_frame(VFrame *frame)
332 {
333         if( !ff ) return -1;
334         int layer = file->current_layer;
335         int64_t pos = asset->video_length >= 0 ? file->current_frame : 0;
336         int ret = ff->decode(layer, pos, frame);
337         frame->set_status(ret);
338         if( ret >= 0 ) return 0;
339         frame->clear_frame();
340         return -1;
341 }
342
343
344 int64_t FileFFMPEG::get_memory_usage()
345 {
346         return 0;
347 }
348
349 int FileFFMPEG::colormodel_supported(int colormodel)
350 {
351         return colormodel;
352 }
353
354
355 int FileFFMPEG::get_best_colormodel(int driver, int vstream)
356 {
357         if( vstream < 0 ) vstream = 0;
358         int is_mpeg = !ff ? 0 : ff->ff_video_mpeg_color_range(vstream);
359
360         switch(driver) {
361         case PLAYBACK_X11:
362         case PLAYBACK_X11_GL: return is_mpeg ? BC_YUV888 : BC_RGB888;
363         case PLAYBACK_X11_XV: return BC_YUV420P;
364         }
365
366         return BC_RGB888;
367 }
368
369 int FileFFMPEG::get_best_colormodel(Asset *asset, int driver)
370 {
371         switch(driver) {
372 // the direct X11 color model requires scaling in the codec
373         case SCREENCAPTURE:
374         case PLAYBACK_X11:
375         case PLAYBACK_X11_GL: return BC_RGB888;
376         case PLAYBACK_X11_XV: return BC_YUV420P;
377         }
378
379         return BC_YUV420P;
380 }
381
382 int FileFFMPEG::can_render(const char *fformat, const char *type)
383 {
384         FileSystem fs;
385         char option_path[BCTEXTLEN];
386         FFMPEG::set_option_path(option_path, type);
387         fs.update(option_path);
388         int total_files = fs.total_files();
389         for( int i=0; i<total_files; ++i ) {
390                 const char *name = fs.get_entry(i)->get_name();
391                 const char *ext = strrchr(name,'.');
392                 if( !ext ) continue;
393                 if( !strcmp(fformat, ++ext) ) return 1;
394         }
395         return 0;
396 }
397
398 int FileFFMPEG::get_ff_option(const char *nm, const char *options, char *value)
399 {
400         for( const char *cp=options; *cp!=0; ) {
401                 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
402                 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
403                 if( *cp ) ++cp;
404                 *bp = 0;
405                 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
406                 char key[BCSTRLEN], val[BCTEXTLEN];
407                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
408                 if( !strcmp(key, nm) ) {
409                         strcpy(value, val);
410                         return 0;
411                 }
412         }
413         return 1;
414 }
415
416 //======
417
418 FFMPEGConfigAudio::FFMPEGConfigAudio(BC_WindowBase *parent_window, Asset *asset)
419  : BC_Window(_(PROGRAM_NAME ": Audio Preset"),
420         parent_window->get_abs_cursor_x(1),
421         parent_window->get_abs_cursor_y(1),
422         420, 420)
423 {
424         this->parent_window = parent_window;
425         this->asset = asset;
426         preset_popup = 0;
427
428         bitrate = 0;
429         audio_options = 0;
430         ff_options_dialog = 0;
431 }
432
433 FFMPEGConfigAudio::~FFMPEGConfigAudio()
434 {
435         delete ff_options_dialog;
436         lock_window("FFMPEGConfigAudio::~FFMPEGConfigAudio");
437         delete preset_popup;
438         presets.remove_all_objects();
439         unlock_window();
440 }
441
442 void FFMPEGConfigAudio::create_objects()
443 {
444         int x = 10, y = 10;
445         lock_window("FFMPEGConfigAudio::create_objects");
446
447         FileSystem fs;
448         char option_path[BCTEXTLEN];
449         FFMPEG::set_option_path(option_path, "audio");
450         fs.update(option_path);
451         int total_files = fs.total_files();
452         for(int i = 0; i < total_files; i++) {
453                 const char *name = fs.get_entry(i)->get_name();
454                 if( asset->fformat[0] != 0 ) {
455                         const char *ext = strrchr(name,'.');
456                         if( !ext ) continue;
457                         if( strcmp(asset->fformat, ++ext) ) continue;
458                 }
459                 presets.append(new BC_ListBoxItem(name));
460         }
461
462         if( asset->acodec[0] ) {
463                 int k = presets.size();
464                 while( --k >= 0 && strcmp(asset->acodec, presets[k]->get_text()) );
465                 if( k < 0 ) asset->acodec[0] = 0;
466         }
467
468         if( !asset->acodec[0] && presets.size() > 0 )
469                 strcpy(asset->acodec, presets[0]->get_text());
470
471         add_tool(new BC_Title(x, y, _("Preset:")));
472         y += 25;
473         preset_popup = new FFMPEGConfigAudioPopup(this, x, y);
474         preset_popup->create_objects();
475
476         y += 50;
477         bitrate = new FFMpegAudioBitrate(this, x, y, _("Bitrate:"), &asset->ff_audio_bitrate);
478         bitrate->create_objects();
479         bitrate->set_increment(1000);
480         bitrate->set_boundaries((int64_t)0, (int64_t)INT_MAX);
481         y += bitrate->get_h() + 5;
482         quality = new FFMpegAudioQuality(this, x, y, _("Quality:"), &asset->ff_audio_quality);
483         quality->create_objects();
484         quality->set_increment(1);
485         quality->set_boundaries((int64_t)-1, (int64_t)51);
486
487         y += quality->get_h() + 10;
488         BC_Title *title = new BC_Title(x, y, _("Audio Options:"));
489         add_subwindow(title);
490
491         ff_options_dialog = new FFOptionsAudioDialog(this);
492         int x1 = x + title->get_w() + 8;
493         add_subwindow(new FFOptionsViewAudio(this, x1, y, _("view")));
494
495         y += 25;
496         if( !asset->ff_audio_options[0] && asset->acodec[0] ) {
497                 FFMPEG::set_option_path(option_path, "audio/%s", asset->acodec);
498                 FFMPEG::load_options(option_path, asset->ff_audio_options,
499                          sizeof(asset->ff_audio_options));
500         }
501
502         audio_options = new FFAudioOptions(this, x, y, get_w()-x-20, 10,
503                  sizeof(asset->ff_audio_options)-1, asset->ff_audio_options);
504         audio_options->create_objects();
505         add_subwindow(new BC_OKButton(this));
506         add_subwindow(new BC_CancelButton(this));
507         show_window(1);
508
509         bitrate->update_param("cin_bitrate", asset->ff_audio_options);
510         quality->update_param("cin_quality", asset->ff_audio_options);
511
512         if( asset->ff_audio_bitrate > 0 ) quality->disable();
513         else if( asset->ff_audio_quality >= 0 ) bitrate->disable();
514
515         unlock_window();
516 }
517
518 int FFMPEGConfigAudio::close_event()
519 {
520         set_done(1);
521         return 1;
522 }
523
524 FFAudioOptions::FFAudioOptions(FFMPEGConfigAudio *audio_popup,
525         int x, int y, int w, int rows, int size, char *text)
526  : BC_ScrollTextBox(audio_popup, x, y, w, rows, text, size)
527 {
528         this->audio_popup = audio_popup;
529 }
530
531
532 FFMPEGConfigAudioPopup::FFMPEGConfigAudioPopup(FFMPEGConfigAudio *popup, int x, int y)
533  : BC_PopupTextBox(popup, &popup->presets, popup->asset->acodec, x, y, 300, 300)
534 {
535         this->popup = popup;
536 }
537
538 int FFMPEGConfigAudioPopup::handle_event()
539 {
540         strcpy(popup->asset->acodec, get_text());
541         Asset *asset = popup->asset;
542         asset->ff_audio_bitrate = 0;
543         char option_path[BCTEXTLEN];
544         FFMPEG::set_option_path(option_path, "audio/%s", asset->acodec);
545         FFMPEG::load_options(option_path, asset->ff_audio_options,
546                          sizeof(asset->ff_audio_options));
547         popup->audio_options->update(asset->ff_audio_options);
548         popup->audio_options->set_text_row(0);
549
550         popup->bitrate->update_param("cin_bitrate", asset->ff_audio_options);
551         popup->quality->update_param("cin_quality", asset->ff_audio_options);
552         return 1;
553 }
554
555
556 FFMPEGConfigAudioToggle::FFMPEGConfigAudioToggle(FFMPEGConfigAudio *popup,
557         char *title_text, int x, int y, int *output)
558  : BC_CheckBox(x, y, *output, title_text)
559 {
560         this->popup = popup;
561         this->output = output;
562 }
563 int FFMPEGConfigAudioToggle::handle_event()
564 {
565         *output = get_value();
566         return 1;
567 }
568
569 //======
570
571 FFMPEGConfigVideo::FFMPEGConfigVideo(BC_WindowBase *parent_window, Asset *asset)
572  : BC_Window(_(PROGRAM_NAME ": Video Preset"),
573         parent_window->get_abs_cursor_x(1),
574         parent_window->get_abs_cursor_y(1),
575         420, 420)
576 {
577         this->parent_window = parent_window;
578         this->asset = asset;
579         preset_popup = 0;
580
581         bitrate = 0;
582         quality = 0;
583         video_options = 0;
584 }
585
586 FFMPEGConfigVideo::~FFMPEGConfigVideo()
587 {
588         delete ff_options_dialog;
589         lock_window("FFMPEGConfigVideo::~FFMPEGConfigVideo");
590         if(preset_popup) delete preset_popup;
591         presets.remove_all_objects();
592         unlock_window();
593 }
594
595 void FFMPEGConfigVideo::create_objects()
596 {
597         int x = 10, y = 10;
598         lock_window("FFMPEGConfigVideo::create_objects");
599
600         add_subwindow(new BC_Title(x, y, _("Compression:")));
601         y += 25;
602
603         FileSystem fs;
604         char option_path[BCTEXTLEN];
605         FFMPEG::set_option_path(option_path, "video");
606         fs.update(option_path);
607         int total_files = fs.total_files();
608         for(int i = 0; i < total_files; i++) {
609                 const char *name = fs.get_entry(i)->get_name();
610                 if( asset->fformat[0] != 0 ) {
611                         const char *ext = strrchr(name,'.');
612                         if( !ext ) continue;
613                         if( strcmp(asset->fformat, ++ext) ) continue;
614                 }
615                 presets.append(new BC_ListBoxItem(name));
616         }
617
618         if( asset->vcodec[0] ) {
619                 int k = presets.size();
620                 while( --k >= 0 && strcmp(asset->vcodec, presets[k]->get_text()) );
621                 if( k < 0 ) asset->vcodec[0] = 0;
622         }
623
624         if( !asset->vcodec[0] && presets.size() > 0 )
625                 strcpy(asset->vcodec, presets[0]->get_text());
626
627         preset_popup = new FFMPEGConfigVideoPopup(this, x, y);
628         preset_popup->create_objects();
629
630         if( asset->ff_video_bitrate > 0 && asset->ff_video_quality >= 0 ) {
631                 asset->ff_video_bitrate = 0;  asset->ff_video_quality = -1;
632         }
633
634         y += 50;
635         bitrate = new FFMpegVideoBitrate(this, x, y, _("Bitrate:"), &asset->ff_video_bitrate);
636         bitrate->create_objects();
637         bitrate->set_increment(100000);
638         bitrate->set_boundaries((int64_t)0, (int64_t)INT_MAX);
639         y += bitrate->get_h() + 5;
640         quality = new FFMpegVideoQuality(this, x, y, _("Quality:"), &asset->ff_video_quality);
641         quality->create_objects();
642         quality->set_increment(1);
643         quality->set_boundaries((int64_t)-1, (int64_t)51);
644
645         y += quality->get_h() + 10;
646         BC_Title *title = new BC_Title(x, y, _("Video Options:"));
647         add_subwindow(title);
648
649         ff_options_dialog = new FFOptionsVideoDialog(this);
650         int x1 = x + title->get_w() + 8;
651         add_subwindow(new FFOptionsViewVideo(this, x1, y, _("view")));
652
653         y += 25;
654         if( !asset->ff_video_options[0] && asset->vcodec[0] ) {
655                 FFMPEG::set_option_path(option_path, "video/%s", asset->vcodec);
656                 FFMPEG::load_options(option_path, asset->ff_video_options,
657                          sizeof(asset->ff_video_options));
658         }
659
660         video_options = new FFVideoOptions(this, x, y, get_w()-x-20, 10,
661                  sizeof(asset->ff_video_options)-1, asset->ff_video_options);
662         video_options->create_objects();
663         add_subwindow(new BC_OKButton(this));
664         add_subwindow(new BC_CancelButton(this));
665         show_window(1);
666
667         bitrate->update_param("cin_bitrate", asset->ff_video_options);
668         quality->update_param("cin_quality", asset->ff_video_options);
669
670         if( asset->ff_video_bitrate > 0 ) quality->disable();
671         else if( asset->ff_video_quality >= 0 ) bitrate->disable();
672         unlock_window();
673 }
674
675 int FFMPEGConfigVideo::close_event()
676 {
677         set_done(1);
678         return 1;
679 }
680
681 FFVideoOptions::FFVideoOptions(FFMPEGConfigVideo *video_popup,
682         int x, int y, int w, int rows, int size, char *text)
683  : BC_ScrollTextBox(video_popup, x, y, w, rows, text, size)
684 {
685         this->video_popup = video_popup;
686 }
687
688
689 FFMPEGConfigVideoPopup::FFMPEGConfigVideoPopup(FFMPEGConfigVideo *popup, int x, int y)
690  : BC_PopupTextBox(popup, &popup->presets, popup->asset->vcodec, x, y, 300, 300)
691 {
692         this->popup = popup;
693 }
694
695 int FFMPEGConfigVideoPopup::handle_event()
696 {
697         strcpy(popup->asset->vcodec, get_text());
698         Asset *asset = popup->asset;
699         char option_path[BCTEXTLEN];
700         asset->ff_video_bitrate = 0;  asset->ff_video_quality = -1;
701         FFMPEG::set_option_path(option_path, "video/%s", asset->vcodec);
702         FFMPEG::load_options(option_path, asset->ff_video_options,
703                          sizeof(asset->ff_video_options));
704         popup->video_options->update(asset->ff_video_options);
705         popup->video_options->set_text_row(0);
706
707         popup->bitrate->update_param("cin_bitrate", asset->ff_video_options);
708         popup->quality->update_param("cin_quality", asset->ff_video_options);
709         return 1;
710 }
711
712
713 FFMPEGConfigVideoToggle::FFMPEGConfigVideoToggle(FFMPEGConfigVideo *popup,
714         char *title_text, int x, int y, int *output)
715  : BC_CheckBox(x, y, *output, title_text)
716 {
717         this->popup = popup;
718         this->output = output;
719 }
720 int FFMPEGConfigVideoToggle::handle_event()
721 {
722         *output = get_value();
723         return 1;
724 }
725
726 FFMPEGScanProgress::FFMPEGScanProgress(IndexFile *index_file, MainProgressBar *progress_bar,
727                 const char *title, int64_t length, int64_t *position, int *canceled)
728  : Thread(1, 0, 0)
729 {
730         this->index_file = index_file;
731         this->progress_bar = progress_bar;
732         strcpy(this->progress_title, title);
733         this->length = length;
734         this->position = position;
735         this->canceled = canceled;
736         done = 0;
737         start();
738 }
739
740 FFMPEGScanProgress::~FFMPEGScanProgress()
741 {
742         done = 1;
743         cancel();
744         join();
745 }
746
747 void FFMPEGScanProgress::run()
748 {
749         while( !done ) {
750                 if( progress_bar->update(*position) ) {
751                         *canceled = done = 1;
752                         break;
753                 }
754                 index_file->redraw_edits(0);
755                 usleep(500000);
756         }
757 }
758
759 int FileFFMPEG::get_index(IndexFile *index_file, MainProgressBar *progress_bar)
760 {
761         if( !ff ) return -1;
762         if( !file->preferences->ffmpeg_marker_indexes ) return 1;
763
764         IndexState *index_state = index_file->get_state();
765         if( index_state->index_status != INDEX_NOTTESTED ) return 0;
766         index_state->reset_index();
767         index_state->reset_markers();
768         index_state->index_status = INDEX_BUILDING;
769
770         for( int aidx=0; aidx<ff->ffaudio.size(); ++aidx ) {
771                 FFAudioStream *aud = ff->ffaudio[aidx];
772                 index_state->add_audio_stream(aud->channels, aud->length);
773         }
774
775         FileSystem fs;
776         int64_t file_bytes = fs.get_size(ff->fmt_ctx->filename);
777         char *index_path = index_file->index_filename;
778
779         int canceled = 0;
780         int64_t scan_position = 0;
781         FFMPEGScanProgress *scan_progress = 0;
782         if( progress_bar ) {
783                 char progress_title[BCTEXTLEN];
784                 sprintf(progress_title, _("Creating %s\n"), index_path);
785                 progress_bar->update_title(progress_title, 1);
786                 progress_bar->update_length(file_bytes);
787                 scan_progress = new FFMPEGScanProgress(index_file,
788                                 progress_bar, progress_title, file_bytes,
789                                 &scan_position, &canceled);
790         }
791
792         index_state->index_bytes = file_bytes;
793         index_state->init_scan(file->preferences->index_size);
794
795         if( ff->scan(index_state, &scan_position, &canceled) || canceled ) {
796                 index_state->reset_index();
797                 index_state->reset_markers();
798                 canceled = 1;
799         }
800
801         delete scan_progress;
802         if( canceled ) return 1;
803
804         index_state->marker_status = MARKERS_READY;
805         return index_state->create_index(index_path, asset);
806 }
807
808
809 FFOptions_OptPanel::
810 FFOptions_OptPanel(FFOptionsWindow *fwin, int x, int y, int w, int h)
811  : BC_ListBox(x, y, w, h, LISTBOX_TEXT), opts(items[0]), vals(items[1])
812 {
813         this->fwin = fwin;
814         update();  // init col/wid/columns
815 }
816
817 FFOptions_OptPanel::
818 ~FFOptions_OptPanel()
819 {
820 }
821
822 void FFOptions_OptPanel::create_objects()
823 {
824         const char *cols[] = { _("option"), _("value"), };
825         const int col1_w = 150;
826         int wids[] = { col1_w, get_w()-col1_w };
827         BC_ListBox::update(&items[0], &cols[0], &wids[0], sizeof(items)/sizeof(items[0]));
828 }
829
830 int FFOptions_OptPanel::update()
831 {
832         opts.remove_all();
833         vals.remove_all();
834         FFOptions &options = fwin->options;
835         for( int i=0; i<options.size(); ++i ) {
836                 FFOptions_Opt *opt = options[i];
837                 opts.append(opt->item_name);
838                 vals.append(opt->item_value);
839         }
840         draw_items(1);
841         return 0;
842 }
843
844 int FFOptions_OptPanel::cursor_leave_event()
845 {
846         hide_tooltip();
847         return 0;
848 }
849
850
851 FFOptions_OptName::FFOptions_OptName(FFOptions_Opt *opt, const char *nm)
852 {
853         this->opt = opt;
854         set_text(nm);
855 }
856
857 FFOptions_OptName::~FFOptions_OptName()
858 {
859 }
860
861 FFOptions_OptValue::FFOptions_OptValue(FFOptions_Opt *opt)
862 {
863         this->opt = opt;
864 }
865
866
867 void FFOptions_OptValue::update()
868 {
869         if( !opt ) return;
870         char val[BCTEXTLEN];  val[0] = 0;
871         opt->get(val, sizeof(val));
872         update(val);
873 }
874
875 void FFOptions_OptValue::update(const char *v)
876 {
877         set_text(v);
878 }
879
880 FFOptions_Opt::FFOptions_Opt(FFOptions *options, const AVOption *opt, const char *nm)
881 {
882         this->options = options;
883         this->opt = opt;
884         item_name = new FFOptions_OptName(this, nm);
885         item_value = new FFOptions_OptValue(this);
886 }
887
888 FFOptions_Opt::~FFOptions_Opt()
889 {
890         delete item_name;
891         delete item_value;
892 }
893
894 char *FFOptions_Opt::get(char *vp, int sz)
895 {
896         char *cp = vp;
897         *cp = 0;
898         if( !opt ) return cp;
899
900         void *obj = (void *)options->obj;
901         uint8_t *bp = 0;
902         if( av_opt_get(obj, opt->name, 0, &bp) >= 0 && bp != 0 ) {
903                 const char *val = (const char *)bp;
904                 if( opt->unit && *val ) {
905                         int id = atoi(val);
906                         const char *uid = unit_name(id);
907                         if( uid ) val = uid;
908                 }
909                 cp = sz >= 0 ? strncpy(vp,val,sz) : strcpy(vp, val);
910                 if( sz > 0 ) vp[sz-1] = 0;
911                 av_freep(&bp);
912         }
913
914         return cp;
915 }
916
917 void FFOptions_Opt::set(const char *val)
918 {
919         void *obj = (void *)options->obj;
920         if( !obj || !opt ) return;
921         av_opt_set(obj, opt->name, val, 0);
922 }
923
924
925 FFOptionsKindItem::FFOptionsKindItem(FFOptionsKind *kind, const char *text, int idx)
926  : BC_MenuItem(text)
927 {
928         this->kind = kind;
929         this->idx = idx;
930 }
931
932 FFOptionsKindItem::~FFOptionsKindItem()
933 {
934 }
935
936 int FFOptionsKindItem::handle_event()
937 {
938         FFOptionsWindow *fwin = kind->fwin;
939         FFOptions &options = fwin->options;
940         options.initialize(fwin, idx);
941         fwin->draw();
942         return 1;
943 }
944
945 const char *FFOptionsKind::kinds[] = {
946         N_("codec"),    // FF_KIND_CODEC
947         N_("ffmpeg"),   // FF_KIND_FFMPEG
948 };
949
950 FFOptionsKind::
951 FFOptionsKind(FFOptionsWindow *fwin, int x, int y, int w)
952  : BC_PopupMenu(x, y, w-calculate_w(0), "")
953 {
954         this->fwin = fwin;
955 }
956
957 FFOptionsKind::
958 ~FFOptionsKind()
959 {
960 }
961
962 void FFOptionsKind::create_objects()
963 {
964         for( int i=0; i<(int)(sizeof(kinds)/sizeof(kinds[0])); ++i )
965                 add_item(new FFOptionsKindItem(this, _(kinds[i]), i));
966 }
967
968 int FFOptionsKind::handle_event()
969 {
970         return 1;
971 }
972
973 void FFOptionsKind::set(int k)
974 {
975         this->kind = k;
976         set_text(_(kinds[k]));
977 }
978
979 FFOptionsText::
980 FFOptionsText(FFOptionsWindow *fwin, int x, int y, int w)
981  : BC_TextBox(x, y, w, 1, (char *)"")
982 {
983         this->fwin = fwin;
984 }
985
986 FFOptionsText::
987 ~FFOptionsText()
988 {
989 }
990
991 int FFOptionsText::handle_event()
992 {
993         return 0;
994 }
995
996 FFOptionsUnits::
997 FFOptionsUnits(FFOptionsWindow *fwin, int x, int y, int w)
998  : BC_PopupMenu(x, y, w, "")
999 {
1000         this->fwin = fwin;
1001 }
1002
1003 FFOptionsUnits::
1004 ~FFOptionsUnits()
1005 {
1006 }
1007
1008 int FFOptionsUnits::handle_event()
1009 {
1010         const char *text = get_text();
1011         if( text && fwin->selected ) {
1012                 fwin->selected->set(text);
1013                 fwin->selected->item_value->update();
1014                 av_dict_set(&fwin->dialog->ff_opts,
1015                         fwin->selected->item_name->get_text(),
1016                         fwin->selected->item_value->get_text(), 0);
1017                 fwin->draw();
1018         }
1019         return 1;
1020 }
1021
1022 FFOptionsApply::
1023 FFOptionsApply(FFOptionsWindow *fwin, int x, int y)
1024  : BC_GenericButton(x, y, _("Apply"))
1025 {
1026         this->fwin = fwin;
1027 }
1028
1029 FFOptionsApply::
1030 ~FFOptionsApply()
1031 {
1032 }
1033
1034 int FFOptionsApply::handle_event()
1035 {
1036         const char *text = fwin->text->get_text();
1037         if( text && fwin->selected ) {
1038                 fwin->selected->set(text);
1039                 fwin->selected->item_value->update();
1040                 av_dict_set(&fwin->dialog->ff_opts,
1041                         fwin->selected->item_name->get_text(),
1042                         fwin->selected->item_value->get_text(), 0);
1043                 fwin->draw();
1044         }
1045         return 1;
1046 }
1047
1048 FFOptions::FFOptions()
1049 {
1050         avctx = 0;
1051         obj = 0;
1052 }
1053
1054 FFOptions::~FFOptions()
1055 {
1056         remove_all_objects();
1057         avcodec_free_context(&avctx);
1058 }
1059
1060 int FFOptions::cmpr(const void *a, const void *b)
1061 {
1062         FFOptions_Opt *ap = *(FFOptions_Opt **)a;
1063         FFOptions_Opt *bp = *(FFOptions_Opt **)b;
1064         const char *vap = ap->item_name->get_text();
1065         const char *vbp = bp->item_name->get_text();
1066         return strcmp(vap, vbp);
1067 }
1068
1069 void FFOptions::initialize(FFOptionsWindow *win, int kind)
1070 {
1071         remove_all_objects();
1072         this->win = win;
1073         win->selected = 0;
1074         obj = 0;
1075         if( !avctx )
1076                 avctx = avcodec_alloc_context3(win->dialog->codec);
1077
1078         switch( kind ) {
1079         case FF_KIND_CODEC:
1080                 obj = (const void *)avctx->priv_data;
1081                 break;
1082         case FF_KIND_FFMPEG:
1083                 obj = (const void *)avctx;
1084                 break;
1085         }
1086
1087         if( obj ) {
1088                 FFOptions &conf = *this;
1089                 const AVOption *opt = 0;
1090                 while( (opt=av_opt_next(obj, opt)) != 0 ) {
1091                         if( opt->type == AV_OPT_TYPE_CONST ) continue;
1092                         int dupl = 0;
1093                         for( int i=0; !dupl && i<size(); ++i ) {
1094                                 FFOptions_Opt *fopt = conf[i];
1095                                 const AVOption *op = fopt->opt;
1096                                 if( op->offset != opt->offset ) continue;
1097                                 if( op->type != opt->type ) continue;
1098                                 dupl = 1;
1099                                 if( strlen(op->name) < strlen(opt->name) )
1100                                         fopt->opt = opt;
1101                         }
1102                         if( dupl ) continue;
1103                         FFOptions_Opt *fopt = new FFOptions_Opt(this, opt, opt->name);
1104                         append(fopt);
1105                         AVDictionaryEntry *elem = av_dict_get(win->dialog->ff_opts,
1106                                         opt->name, 0, AV_DICT_IGNORE_SUFFIX);
1107                         if( elem && elem->value ) fopt->set(elem->value);
1108                         char val[BCTEXTLEN], *vp = fopt->get(val, sizeof(val));
1109                         fopt->item_value->update(vp);
1110                 }
1111         }
1112
1113         qsort(&values[0],size(),sizeof(values[0]),cmpr);
1114         win->kind->set(kind);
1115         win->panel->update();
1116         win->panel->set_yposition(0);
1117 }
1118
1119 int FFOptions::update()
1120 {
1121         int ret = 0;
1122         FFOptions &conf = *this;
1123
1124         for( int i=0; i<size(); ++i ) {
1125                 FFOptions_Opt *fopt = conf[i];
1126                 char val[BCTEXTLEN], *vp = fopt->get(val, sizeof(val));
1127                 if( !vp || !strcmp(val, fopt->item_value->get_text()) ) continue;
1128                 fopt->item_value->update(val);
1129                 ++ret;
1130         }
1131         return ret;
1132 }
1133
1134 void FFOptions::dump(FILE *fp)
1135 {
1136         if( !obj ) return;
1137         const AVOption *opt = 0;
1138         FFOptions &conf = *this;
1139
1140         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1141                 if( opt->type == AV_OPT_TYPE_CONST ) continue;
1142                 int k = size();
1143                 while( --k >= 0 && strcmp(opt->name, conf[k]->opt->name) );
1144                 if( k < 0 ) continue;
1145                 FFOptions_Opt *fopt = conf[k];
1146                 char val[BCTEXTLEN], *vp = fopt->get(val,sizeof(val));
1147                 fprintf(fp, "  %s:=%s", opt->name, vp);
1148                 if( opt->unit ) {
1149                         char unt[BCTEXTLEN], *up = unt;
1150                         fopt->units(up);
1151                         fprintf(fp, "%s", unt);
1152                 }
1153                 fprintf(fp, "\n");
1154         }
1155 }
1156
1157
1158 void FFOptionsWindow::update(FFOptions_Opt *opt)
1159 {
1160         if( selected != opt ) {
1161                 if( selected ) selected->item_name->set_selected(0);
1162                 selected = opt;
1163                 if( selected ) selected->item_name->set_selected(1);
1164         }
1165         clear_box(0,0, 0,panel->get_y());
1166         char str[BCTEXTLEN], *sp;
1167         *(sp=str) = 0;
1168         if( opt ) opt->types(sp);
1169         type->update(str);
1170         *(sp=str) = 0;
1171         if( opt ) opt->ranges(sp);
1172         range->update(str);
1173         while( units->total_items() ) units->del_item(0);
1174         char unit[BCSTRLEN];  strcpy(unit, "()");
1175         if( opt && opt->opt ) {
1176                 ArrayList<const char *> names;
1177                 int n = 0;
1178                 if( opt->opt->unit ) {
1179                         n = opt->units(names);
1180                         if( n > 0 ) strcpy(unit,opt->opt->unit);
1181                 }
1182                 for( int i=0; i<n; ++i )
1183                         units->add_item(new BC_MenuItem(names[i], 0));
1184         }
1185         units->set_text(unit);
1186         char val[BCTEXTLEN];  val[0] = 0;
1187         if( opt ) opt->get(val, sizeof(val));
1188         text->update(val);
1189
1190         panel->update();
1191 }
1192
1193 void FFOptions_OptPanel::show_tip(const char *tip)
1194 {
1195         if( !tip ) return;
1196         int len = strlen(tip);
1197         if( len > (int)sizeof(tip_text)-1 ) len = sizeof(tip_text)-1;
1198         strncpy(tip_text,tip,len);
1199         tip_text[len] = 0;
1200         int line_limit = 60;
1201         int limit2 = line_limit/2;
1202         int limit4 = line_limit/4-2;
1203         char *cp = tip_text, *dp = cp+len;
1204         int n;  char *bp, *ep, *pp, *sp;
1205         while( cp < dp ) {
1206                 for( ep=cp; ep<dp && *ep!='\n'; ++ep );
1207                 // target about half remaining line, constrain line_limit
1208                 if( (n=(ep-1-cp)/2) < limit2 || n > line_limit )
1209                         n = line_limit;
1210                 // search for last punct, last space before line_limit
1211                 for( bp=cp, pp=sp=0; --n>=0 && cp<ep; ++cp ) {
1212                         if( ispunct(*cp) && isspace(*(cp+1)) ) pp = cp;
1213                         else if( isspace(*cp) ) sp = cp;
1214                 }
1215                 // line not empty
1216                 if( cp < ep ) {
1217                         // first, after punctuation
1218                         if( pp && pp-bp >= limit4 )
1219                                 cp = pp+1;
1220                         // then, on spaces
1221                         else if( sp ) {
1222                                 cp = sp;
1223                         }
1224                         // last, on next space
1225                         else {
1226                                 while( cp<dp && !isspace(*cp) ) ++cp;
1227                         }
1228                         // add new line
1229                         if( !*cp ) break;
1230                         *cp++ = '\n';
1231                 }
1232         }
1233         fwin->panel->set_tooltip(tip_text);
1234         fwin->panel->show_tooltip();
1235 }
1236
1237 int FFOptions_OptPanel::selection_changed()
1238 {
1239         FFOptions_Opt *opt = 0;
1240         BC_ListBoxItem *item = get_selection(0, 0);
1241         if( item ) {
1242                 FFOptions_OptName *opt_name = (FFOptions_OptName *)item;
1243                 opt = opt_name->opt;
1244         }
1245         fwin->update(opt);
1246         if( opt ) show_tip(opt->tip());
1247         return 1;
1248 }
1249
1250
1251 int FFOptions_Opt::types(char *rp)
1252 {
1253         const char *cp = "";
1254         if( opt ) switch (opt->type) {
1255         case AV_OPT_TYPE_FLAGS: cp = N_("<flags>");  break;
1256         case AV_OPT_TYPE_INT: cp = N_("<int>"); break;
1257         case AV_OPT_TYPE_INT64: cp = N_("<int64>"); break;
1258         case AV_OPT_TYPE_DOUBLE: cp = N_("<double>"); break;
1259         case AV_OPT_TYPE_FLOAT: cp = N_("<float>"); break;
1260         case AV_OPT_TYPE_STRING: cp = N_("<string>"); break;
1261         case AV_OPT_TYPE_RATIONAL: cp = N_("<rational>"); break;
1262         case AV_OPT_TYPE_BINARY: cp = N_("<binary>"); break;
1263         case AV_OPT_TYPE_IMAGE_SIZE: cp = N_("<image_size>"); break;
1264         case AV_OPT_TYPE_VIDEO_RATE: cp = N_("<video_rate>"); break;
1265         case AV_OPT_TYPE_PIXEL_FMT: cp = N_("<pix_fmt>"); break;
1266         case AV_OPT_TYPE_SAMPLE_FMT: cp = N_("<sample_fmt>"); break;
1267         case AV_OPT_TYPE_DURATION: cp = N_("<duration>"); break;
1268         case AV_OPT_TYPE_COLOR: cp = N_("<color>"); break;
1269         case AV_OPT_TYPE_CHANNEL_LAYOUT: cp = N_("<channel_layout>");  break;
1270         case AV_OPT_TYPE_BOOL: cp = N_("<bool>");  break;
1271         default: cp = N_("<undef>");  break;
1272         }
1273         return sprintf(rp, "%s", _(cp));
1274 }
1275 int FFOptions_Opt::scalar(double d, char *rp)
1276 {
1277         const char *cp = 0;
1278              if( d == INT_MAX ) cp = "INT_MAX";
1279         else if( d == INT_MIN ) cp = "INT_MIN";
1280         else if( d == UINT32_MAX ) cp = "UINT32_MAX";
1281         else if( d == (double)INT64_MAX ) cp = "I64_MAX";
1282         else if( d == INT64_MIN ) cp = "I64_MIN";
1283         else if( d == FLT_MAX ) cp = "FLT_MAX";
1284         else if( d == FLT_MIN ) cp = "FLT_MIN";
1285         else if( d == -FLT_MAX ) cp = "-FLT_MAX";
1286         else if( d == -FLT_MIN ) cp = "-FLT_MIN";
1287         else if( d == DBL_MAX ) cp = "DBL_MAX";
1288         else if( d == DBL_MIN ) cp = "DBL_MIN";
1289         else if( d == -DBL_MAX ) cp = "-DBL_MAX";
1290         else if( d == -DBL_MIN ) cp = "-DBL_MIN";
1291         else if( d == 0 ) cp = signbit(d) ? "-0" : "0";
1292         else if( isnan(d) ) cp = signbit(d) ? "-NAN" : "NAN";
1293         else if( isinf(d) ) cp = signbit(d) ? "-INF" : "INF";
1294         else return sprintf(rp, "%g", d);
1295         return sprintf(rp, "%s", cp);
1296 }
1297
1298 int FFOptions_Opt::ranges(char *rp)
1299 {
1300         if( !opt ) return 0;
1301         void *obj = (void *)options->obj;
1302         if( !obj ) return 0;
1303
1304         switch (opt->type) {
1305         case AV_OPT_TYPE_INT:
1306         case AV_OPT_TYPE_INT64:
1307         case AV_OPT_TYPE_DOUBLE:
1308         case AV_OPT_TYPE_FLOAT: break;
1309         default: return 0;;
1310         }
1311         AVOptionRanges *r = 0;
1312         char *cp = rp;
1313         if( av_opt_query_ranges(&r, obj, opt->name, AV_OPT_SEARCH_FAKE_OBJ) < 0 ) return 0;
1314         for( int i=0; i<r->nb_ranges; ++i ) {
1315                 cp += sprintf(cp, " (");  cp += scalar(r->range[i]->value_min, cp);
1316                 cp += sprintf(cp, "..");  cp += scalar(r->range[i]->value_max, cp);
1317                 cp += sprintf(cp, ")");
1318         }
1319         av_opt_freep_ranges(&r);
1320         return cp - rp;
1321 }
1322
1323 int FFOptions_Opt::units(ArrayList<const char *> &names)
1324 {
1325         if( !opt || !opt->unit ) return 0;
1326         const void *obj = options->obj;
1327         if( !obj ) return 0;
1328
1329         ArrayList<const AVOption *> opts;
1330         const AVOption *opt = NULL;
1331         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1332                 if( !opt->unit ) continue;
1333                 if( opt->type != AV_OPT_TYPE_CONST ) continue;
1334                 if( strcmp(this->opt->unit, opt->unit) ) continue;
1335                 int i = opts.size();
1336                 while( --i >= 0 ) {
1337                         if( opts[i]->default_val.i64 != opt->default_val.i64 ) continue;
1338                         if( strlen(opts[i]->name) < strlen(opt->name) ) opts[i] = opt;
1339                         break;
1340                 }
1341                 if( i >= 0 ) continue;
1342                 opts.append(opt);
1343         }
1344
1345         for( int i=0; i<opts.size(); ++i )
1346                 names.append(opts[i]->name);
1347
1348         return names.size();
1349 }
1350
1351 int FFOptions_Opt::units(char *rp)
1352 {
1353         ArrayList<const char *> names;
1354         int n = units(names);
1355         if( !n ) return 0;
1356         char *cp = rp;
1357         cp += sprintf(cp, " [%s:", this->opt->unit);
1358         for( int i=0; i<n; ++i )
1359                 cp += sprintf(cp, " %s", names[i]);
1360         cp += sprintf(cp, "]:");
1361         return cp - rp;
1362 }
1363
1364 const char *FFOptions_Opt::unit_name(int id)
1365 {
1366         if( !opt || !opt->unit ) return 0;
1367         const void *obj = options->obj;
1368         if( !obj ) return 0;
1369
1370         const char *ret = 0;
1371         const AVOption *opt = NULL;
1372         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1373                 if( !opt->unit ) continue;
1374                 if( opt->type != AV_OPT_TYPE_CONST ) continue;
1375                 if( strcmp(this->opt->unit, opt->unit) ) continue;
1376                 if( opt->default_val.i64 != id ) continue;
1377                 if( !ret ) { ret = opt->name;  continue; }
1378                 if( strlen(ret) < strlen(opt->name) ) ret = opt->name;
1379         }
1380
1381         return ret;
1382 }
1383
1384 const char *FFOptions_Opt::tip()
1385 {
1386         return !opt ? 0 : opt->help;
1387 }
1388
1389
1390 FFOptionsWindow::FFOptionsWindow(FFOptionsDialog *dialog)
1391  : BC_Window(_(PROGRAM_NAME ": Options"), 60, 30, 640, 400)
1392 {
1393         this->dialog = dialog;
1394         this->selected = 0;
1395 }
1396
1397 FFOptionsWindow::~FFOptionsWindow()
1398 {
1399 }
1400
1401 void FFOptionsWindow::create_objects()
1402 {
1403         BC_Title *title;
1404         int x0 = 10, y0 = 10;
1405         int x = x0, y = y0;
1406         add_subwindow(title = new BC_Title(x, y, _("Format: ")));
1407         x += title->get_w();
1408         add_subwindow(new BC_Title(x, y, dialog->format_name));
1409         x = x0 + 150;
1410         add_subwindow(title = new BC_Title(x, y, _("Codec: ")));
1411         x += title->get_w();
1412         add_subwindow(new BC_Title(x, y, dialog->codec_name));
1413
1414         x = x0;  y += title->get_h() + 10;  y0 = y;
1415         add_subwindow(title = new BC_Title(x, y, _("Type: ")));
1416         x += title->get_w() + 8;
1417         add_subwindow(type = new BC_Title(x, y, (char *)""));
1418         x = x0 + 150;
1419         add_subwindow(title = new BC_Title(x, y, _("Range: ")));
1420         x += title->get_w() + 8;
1421         add_subwindow(range = new BC_Title(x, y, (char *)""));
1422
1423         x = x0;  y += title->get_h() + 10;
1424         add_subwindow(units = new FFOptionsUnits(this, x, y, 120));
1425         x += units->get_w() + 8;
1426         int x1 = get_w() - BC_GenericButton::calculate_w(this, _("Apply")) - 8;
1427         add_subwindow(text = new FFOptionsText(this, x, y, x1-x - 8));
1428         add_subwindow(apply = new FFOptionsApply(this, x1, y));
1429         y += units->get_h() + 10;
1430         add_subwindow(kind = new FFOptionsKind(this, x1, y0, apply->get_w()));
1431         kind->create_objects();
1432         const char *kind_text = _("Kind:");
1433         x1 -= BC_Title::calculate_w(this, kind_text) + 8;
1434         add_subwindow(kind_title = new BC_Title(x1, y0, kind_text));
1435         y0 = y;
1436
1437         panel_x = x0;  panel_y = y0;
1438         panel_w = get_w()-10 - panel_x;
1439         panel_h = get_h()-10 - panel_y - BC_OKButton::calculate_h();
1440         panel = new FFOptions_OptPanel(this, panel_x, panel_y, panel_w, panel_h);
1441         add_subwindow(panel);
1442         add_subwindow(new BC_OKButton(this));
1443         add_subwindow(new BC_CancelButton(this));
1444         panel->create_objects();
1445         options.initialize(this, FF_KIND_CODEC);
1446         draw();
1447         show_window(1);
1448 }
1449
1450 void FFOptionsWindow::draw()
1451 {
1452         update(selected);
1453 }
1454
1455 int FFOptionsWindow::resize_event(int w, int h)
1456 {
1457         int x1 = w - 8 - kind->get_w();
1458         int y = kind->get_y();
1459         kind->reposition_window(x1, y);
1460         x1 -= kind_title->get_w() + 8;
1461         kind_title->reposition_window(x1,y);
1462         x1 = get_w() - apply->get_w() - 8;
1463         int y1 = units->get_y();
1464         apply->reposition_window(x1, y1);
1465         int x0 = units->get_x() + units->get_w() + 8;
1466         int y0 = units->get_y();
1467         text->reposition_window(x0,y0, x1-x0-8);
1468         panel_w = get_w()-10 - panel_x;
1469         panel_h = get_h()-10 - panel_y;
1470         panel->reposition_window(panel_x,panel_y, panel_w, panel_h);
1471         return 1;
1472 }
1473
1474 FFOptionsDialog::FFOptionsDialog()
1475  : BC_DialogThread()
1476 {
1477         this->options_window = 0;
1478         this->codec_name = 0;
1479         this->codec = 0;
1480         this->ff_opts = 0;
1481         this->ff_len = 0;
1482 }
1483
1484 FFOptionsDialog::~FFOptionsDialog()
1485 {
1486         close_window();
1487         delete [] codec_name;
1488 }
1489
1490 void FFOptionsDialog::load_options(const char *bp, int len)
1491 {
1492         char line[BCTEXTLEN];
1493         char key[BCSTRLEN], val[BCTEXTLEN];
1494         const char *dp = bp + len-1;
1495         int no = 0;
1496         while( bp < dp && *bp != 0 ) {
1497                 ++no;
1498                 char *cp = line, *ep = cp+sizeof(line)-1;
1499                 while( *bp && cp<ep && (*cp=*bp++)!='\n' ) ++cp;
1500                 *cp = 0;
1501                 if( line[0] == '#' ) {
1502                         sprintf(key,"#%d", no);
1503                         av_dict_set(&ff_opts, key, line, 0);
1504                         continue;
1505                 }
1506                 if( line[0] == '\n' ) continue;
1507                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1508                 av_dict_set(&ff_opts, key, val, 0);
1509         }
1510 }
1511
1512 void FFOptionsDialog::store_options(char *cp, int len)
1513 {
1514         char *ep = cp + len-1;
1515         AVDictionaryEntry *elem = 0;
1516         while( (elem=av_dict_get(ff_opts, "", elem, AV_DICT_IGNORE_SUFFIX)) != 0 ) {
1517                 if( elem->key[0] == '#' ) {
1518                         cp += snprintf(cp,ep-cp, "%s\n", elem->value);
1519                         continue;
1520                 }
1521                 cp += snprintf(cp,ep-cp, "%s=%s\n", elem->key, elem->value);
1522         }
1523         *cp = 0;
1524 }
1525
1526 void FFOptionsDialog::start(const char *format_name, const char *codec_name,
1527         AVCodec *codec, const char *options, int len)
1528 {
1529         if( options_window ) {
1530                 options_window->lock_window("FFOptionsDialog::start");
1531                 options_window->raise_window();
1532                 options_window->unlock_window();
1533                 return;
1534         }
1535
1536         this->format_name = cstrdup(format_name);
1537         this->codec_name = cstrdup(codec_name);
1538         this->codec = codec;
1539         this->ff_opts = 0;
1540         this->ff_len = len;
1541         load_options(options, len);
1542
1543         BC_DialogThread::start();
1544 }
1545
1546 BC_Window* FFOptionsDialog::new_gui()
1547 {
1548         options_window = new FFOptionsWindow(this);
1549         options_window->create_objects();
1550         return options_window;
1551 }
1552
1553 void FFOptionsDialog::handle_done_event(int result)
1554 {
1555         if( !result ) {
1556                 char options[ff_len];
1557                 store_options(options, ff_len);
1558                 update_options(options);
1559         }
1560         options_window = 0;
1561         delete [] format_name; format_name = 0;
1562         delete [] codec_name;  codec_name = 0;
1563         av_dict_free(&ff_opts);
1564 }
1565
1566 FFOptionsAudioDialog::FFOptionsAudioDialog(FFMPEGConfigAudio *aud_config)
1567 {
1568         this->aud_config = aud_config;
1569 }
1570
1571 FFOptionsAudioDialog::~FFOptionsAudioDialog()
1572 {
1573         close_window();
1574 }
1575
1576 void FFOptionsAudioDialog::update_options(const char *options)
1577 {
1578         aud_config->audio_options->update(options);
1579 }
1580
1581 FFOptionsVideoDialog::FFOptionsVideoDialog(FFMPEGConfigVideo *vid_config)
1582 {
1583         this->vid_config = vid_config;
1584 }
1585
1586 FFOptionsVideoDialog::~FFOptionsVideoDialog()
1587 {
1588         close_window();
1589 }
1590
1591 void FFOptionsVideoDialog::update_options(const char *options)
1592 {
1593         vid_config->video_options->update(options);
1594 }
1595
1596
1597 FFOptionsViewAudio::FFOptionsViewAudio(FFMPEGConfigAudio *aud_config, int x, int y, const char *text)
1598  : BC_GenericButton(x, y, text)
1599 {
1600         this->aud_config = aud_config;
1601 }
1602
1603 FFOptionsViewAudio::~FFOptionsViewAudio()
1604 {
1605 }
1606
1607 int FFOptionsViewAudio::handle_event()
1608 {
1609         char audio_format[BCSTRLEN]; audio_format[0] = 0;
1610         char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1611         AVCodec *codec = 0;
1612         Asset *asset = aud_config->asset;
1613         const char *name = asset->acodec;
1614         if( !FFMPEG::get_format(audio_format, "audio", name) &&
1615             !FFMPEG::get_codec(audio_codec, "audio", name) )
1616                 codec = avcodec_find_encoder_by_name(audio_codec);
1617         if( !codec ) {
1618                 eprintf(_("no codec named: %s: %s"), name, audio_codec);
1619                 return 1;
1620         }
1621         aud_config->ff_options_dialog->start(audio_format, audio_codec, codec,
1622                 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1623         return 1;
1624 }
1625
1626 FFOptionsViewVideo::FFOptionsViewVideo(FFMPEGConfigVideo *vid_config, int x, int y, const char *text)
1627  : BC_GenericButton(x, y, text)
1628 {
1629         this->vid_config = vid_config;
1630 }
1631
1632 FFOptionsViewVideo::~FFOptionsViewVideo()
1633 {
1634 }
1635
1636 int FFOptionsViewVideo::handle_event()
1637 {
1638         char video_format[BCSTRLEN]; video_format[0] = 0;
1639         char video_codec[BCSTRLEN]; video_codec[0] = 0;
1640         AVCodec *codec = 0;
1641         Asset *asset = vid_config->asset;
1642         const char *name = asset->vcodec;
1643         if( !FFMPEG::get_format(video_format, "video", name) &&
1644             !FFMPEG::get_codec(video_codec, "video", name) )
1645                 codec = avcodec_find_encoder_by_name(video_codec);
1646         if( !codec ) {
1647                 eprintf(_("no codec named: %s: %s"), name, video_codec);
1648                 return 1;
1649         }
1650         vid_config->ff_options_dialog->start(video_format, video_codec, codec,
1651                 asset->ff_video_options, sizeof(asset->ff_video_options));
1652         return 1;
1653 }
1654