add dvd chroma 420pi colormodel, misc fixes
[goodguy/history.git] / cinelerra-5.1 / cinelerra / filempeg.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
5  * 
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * 
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  * 
20  */
21
22 #include "asset.h"
23 #include "bcprogressbox.h"
24 #include "bcsignals.h"
25 #include "bitspopup.h"
26 #include "byteorder.h"
27 #include "clip.h"
28 #include "commercials.h"
29 #include "condition.h"
30 #include "cstrdup.h"
31 #include "edit.h"
32 #include "file.h"
33 #include "filempeg.h"
34 #include "filesystem.h"
35 #include "guicast.h"
36 #include "indexfile.h"
37 #include "interlacemodes.h"
38 #include "indexstate.h"
39 #include "language.h"
40 #include "mainerror.h"
41 #include "mwindow.h"
42 #include "pipe.h"
43 #include "preferences.h"
44 #include "removefile.h"
45 #include "vframe.h"
46 #include "videodevice.inc"
47
48 #include <stdio.h>
49 #include <string.h>
50 #include <unistd.h>
51
52
53 #define HVPEG_EXE "/hveg2enc"
54 #define MJPEG_EXE "/mpeg2enc"
55
56
57 // M JPEG dependancies
58 static double frame_rate_codes[] = 
59 {
60         0,
61         24000.0/1001.0,
62         24.0,
63         25.0,
64         30000.0/1001.0,
65         30.0,
66         50.0,
67         60000.0/1001.0,
68         60.0
69 };
70
71 static double aspect_ratio_codes[] =
72 {
73         0,
74         1.0,
75         1.333,
76         1.777,
77         2.21
78 };
79
80
81
82
83
84
85
86
87 FileMPEG::FileMPEG(Asset *asset, File *file)
88  : FileBase(asset, file)
89 {
90         reset_parameters();
91 // May also be VMPEG or AMPEG if write status.
92         if(asset->format == FILE_UNKNOWN) asset->format = FILE_MPEG;
93         asset->byte_order = 0;
94         next_frame_lock = new Condition(0, "FileMPEG::next_frame_lock");
95         next_frame_done = new Condition(0, "FileMPEG::next_frame_done");
96         vcommand_line.set_array_delete();
97 }
98
99 FileMPEG::~FileMPEG()
100 {
101         close_file();
102         delete next_frame_lock;
103         delete next_frame_done;
104         vcommand_line.remove_all_objects();
105 }
106
107 void FileMPEG::get_parameters(BC_WindowBase *parent_window, 
108         Asset *asset, 
109         BC_WindowBase* &format_window,
110         int audio_options,
111         int video_options)
112 {
113         if(audio_options && asset->format == FILE_AMPEG)
114         {
115                 MPEGConfigAudio *window = new MPEGConfigAudio(parent_window, asset);
116                 format_window = window;
117                 window->create_objects();
118                 window->run_window();
119                 delete window;
120         }
121         else
122         if(video_options && asset->format == FILE_VMPEG)
123         {
124                 MPEGConfigVideo *window = new MPEGConfigVideo(parent_window, asset);
125                 format_window = window;
126                 window->create_objects();
127                 window->run_window();
128                 delete window;
129         }
130 }
131
132 int FileMPEG::check_sig(Asset *asset)
133 {
134         return mpeg3_check_sig(asset->path);
135 }
136
137 void FileMPEG::get_info(char *title_path, char *path, char *text, int len)
138 {
139         mpeg3_t *fd;
140         *text = 0;
141
142         int result = 0;
143         int zio_access = ZIO_UNBUFFERED+ZIO_SINGLE_ACCESS;
144         if( !(fd=mpeg3_zopen(title_path, path, &result,zio_access)) ) result = 1;
145         if( !result ) result = mpeg3_create_title(fd, 0);
146         if( result ) return;
147
148         char *cp = text, *ep = text + len-1;
149         if( mpeg3_has_toc(fd) ) {
150                 cp += snprintf(cp,ep-cp, _("toc path:%s\n"), path);
151                 cp += snprintf(cp,ep-cp, _("title path:\n"));
152                 for( int i=0; i<100; ++i ) {
153                         char *title_path = mpeg3_title_path(fd,i);
154                         if( !title_path ) break;
155                         cp += snprintf(cp,ep-cp, " %2d. %s\n", i+1, title_path);
156                 }
157         }
158         else
159                 cp += snprintf(cp,ep-cp, _("file path:%s\n"), path);
160         int64_t bytes = mpeg3_get_bytes(fd);
161         char string[BCTEXTLEN];
162         sprintf(string,"%ld",bytes);
163         Units::punctuate(string);
164         cp += snprintf(cp,ep-cp, _("size: %s"), string);
165
166         if( mpeg3_is_program_stream(fd) )
167           cp += snprintf(cp,ep-cp, _("  program stream\n"));
168         else if( mpeg3_is_transport_stream(fd) )
169           cp += snprintf(cp,ep-cp, _("  transport stream\n"));
170         else if( mpeg3_is_video_stream(fd) )
171           cp += snprintf(cp,ep-cp, _("  video stream\n"));
172         else if( mpeg3_is_audio_stream(fd) )
173           cp += snprintf(cp,ep-cp, _("  audio stream\n"));
174
175         int64_t sdate = mpeg3_get_source_date(fd);
176         if( !sdate ) {
177                 struct stat64 ostat;
178                 memset(&ostat,0,sizeof(struct stat64));
179                 sdate = stat64(path, &ostat) < 0 ? 0 : ostat.st_mtime;
180         }
181         time_t tm = (time_t)sdate;
182         cp += snprintf(cp,ep-cp, _("date: %s\n"), ctime(&tm));
183
184         int vtrks = mpeg3_total_vstreams(fd);
185         cp += snprintf(cp,ep-cp, _("%d video tracks\n"), vtrks);
186         for( int vtrk=0; vtrk<vtrks; ++vtrk ) {
187                 int cmdl = mpeg3_colormodel(fd, vtrk);
188                 int color_model = bc_colormodel(cmdl);
189                 char *cmodel = MPEGColorModel::cmodel_to_string(color_model);
190                 int width = mpeg3_video_width(fd, vtrk);
191                 int height = mpeg3_video_height(fd, vtrk);
192                 cp += snprintf(cp,ep-cp, _("  v%d %s %dx%d"), vtrk, cmodel, width, height);
193                 double frame_rate = mpeg3_frame_rate(fd, vtrk);
194                 int64_t frames = mpeg3_video_frames(fd, vtrk);
195                 cp += snprintf(cp,ep-cp, _(" (%5.2f), %ld frames"), frame_rate, frames);
196                 if( frame_rate > 0 ) {
197                         double secs = (double)frames / frame_rate;
198                         cp += snprintf(cp,ep-cp, _(" (%0.3f secs)"),secs);
199                 }
200                 *cp++ = '\n';
201         }
202         int atrks = mpeg3_total_astreams(fd);
203         cp += snprintf(cp,ep-cp, _("%d audio tracks\n"), atrks);
204         for( int atrk=0; atrk<atrks; ++atrk) {
205                 const char *format = mpeg3_audio_format(fd, atrk);
206                 cp += snprintf(cp,ep-cp, _(" a%d %s"), atrk, format);
207                 int channels = mpeg3_audio_channels(fd, atrk);
208                 int sample_rate = mpeg3_sample_rate(fd, atrk);
209                 cp += snprintf(cp,ep-cp, _(" ch%d (%d)"), channels, sample_rate);
210                 int64_t samples = mpeg3_audio_samples(fd, atrk);
211                 cp += snprintf(cp,ep-cp, " %ld",samples);
212                 int64_t nudge = mpeg3_get_audio_nudge(fd, atrk);
213                 *cp++ = nudge >= 0 ? '+' : (nudge=-nudge, '-');
214                 cp += snprintf(cp,ep-cp, _("%ld samples"),nudge);
215                 if( sample_rate > 0 ) {
216                         double secs = (double)(samples+nudge) / sample_rate;
217                         cp += snprintf(cp,ep-cp, _(" (%0.3f secs)"),secs);
218                 }
219                 *cp++ = '\n';
220         }
221         int stracks = mpeg3_subtitle_tracks(fd);
222         if( stracks > 0 ) {
223                 cp += snprintf(cp,ep-cp, _("%d subtitles\n"), stracks);
224         }
225         int vts_titles = mpeg3_get_total_vts_titles(fd);
226         if( vts_titles > 0 )
227                 cp += snprintf(cp,ep-cp, _("%d title sets, "), vts_titles);
228         int interleaves = mpeg3_get_total_interleaves(fd);
229         if( interleaves > 0 )
230                 cp += snprintf(cp,ep-cp, _("%d interleaves\n"), interleaves);
231         int vts_title = mpeg3_set_vts_title(fd, -1);
232         int angle = mpeg3_set_angle(fd, -1);
233         int interleave = mpeg3_set_interleave(fd, -1);
234         int program = mpeg3_set_program(fd, -1);
235         cp += snprintf(cp,ep-cp, _("current program %d = title %d, angle %d, interleave %d\n\n"),
236                 program, vts_title, angle, interleave);
237
238         ArrayList<double> cell_times;
239         int cell_no = 0; double cell_time;
240         while( !mpeg3_get_cell_time(fd, cell_no++, &cell_time) ) {
241                 cell_times.append(cell_time);
242         }
243         if( cell_times.size() > 1 ) {
244                 cp += snprintf(cp,ep-cp, _("cell times:"));
245                 for( int i=0; i<cell_times.size(); ++i ) {
246                         if( (i%4) == 0 ) *cp++ = '\n';
247                         cp += snprintf(cp,ep-cp,"  %3d.  %8.3f",i,cell_times.get(i));
248                 }
249                 cp += snprintf(cp,ep-cp, "\n");
250         }
251
252         int elements = mpeg3_dvb_channel_count(fd);
253         if( elements <= 0 ) return;
254         if( !mpeg3_dvb_get_system_time(fd, &sdate) ) {
255                 tm = (time_t)sdate;
256                 cp += snprintf(cp,ep-cp, _("\nsystem time: %s"), ctime_r(&tm,string));
257         }
258         cp += snprintf(cp,ep-cp, _("elements %d\n"), elements);
259
260         for( int n=0; n<elements; ++n ) {
261                 char name[16], enc[8];  int vstream, astream;
262                 int major, minor, total_astreams, total_vstreams;
263                 if( mpeg3_dvb_get_channel(fd,n, &major, &minor) ||
264                     mpeg3_dvb_get_station_id(fd,n,&name[0]) ||
265                     mpeg3_dvb_total_vstreams(fd,n,&total_vstreams) ||
266                     mpeg3_dvb_total_astreams(fd,n,&total_astreams) )    continue;
267                 cp += snprintf(cp,ep-cp, " %3d.%-3d %s", major, minor, &name[0]);
268                 for( int vidx=0; vidx<total_vstreams; ++vidx ) {
269                         if( mpeg3_dvb_vstream_number(fd,n,vidx,&vstream) ) continue;
270                         if( vstream < 0 ) continue;
271                         cp += snprintf(cp,ep-cp, " v%d", vstream);
272                 }
273                 for( int aidx=0; aidx<total_astreams; ++aidx ) {
274                         if( mpeg3_dvb_astream_number(fd,n,aidx,&astream,&enc[0]) ) continue;
275                         if( astream < 0 ) continue;
276                         cp += snprintf(cp,ep-cp, "    a%d %s", astream, &enc[0]);
277                         int atrack = 0;
278                         for(int i=0; i<astream; ++i )
279                                 atrack += mpeg3_audio_channels(fd, i);
280                         int channels = mpeg3_audio_channels(fd, astream);
281                         cp += snprintf(cp,ep-cp, " trk %d-%d", atrack+1, atrack+channels);
282                         if( enc[0] ) cp += snprintf(cp,ep-cp," (%s)",enc);
283                 }
284                 cp += snprintf(cp,ep-cp, "\n");
285         }
286
287         for( int n=0; n<elements; ++n ) {
288                 int major, minor;
289                 if( mpeg3_dvb_get_channel(fd,n, &major, &minor) ) continue;
290                 cp += snprintf(cp,ep-cp, "\n**chan %3d.%-3d\n", major, minor);
291                 int len = mpeg3_dvb_get_chan_info(fd, n, -1, 0, cp, 1023);
292                 if( len < 0 ) len = snprintf(cp,ep-cp,_("no info"));
293                 cp += len;  *cp++ = '*';  *cp++ = '*';  *cp++ = '\n';
294                 for( int ord=0; ord<0x80; ++ord ) {
295                         for( int i=0; (len=mpeg3_dvb_get_chan_info(fd,n,ord,i,cp,1023)) >= 0; ++i ) {
296                                 char *bp = cp;  cp += len;
297                                 for( int k=2; --k>=0; ) {  // skip 2 lines
298                                         while( bp<cp && *bp++!='\n' );
299                                 }
300                                 for( char *lp=bp; bp<cp; ++bp ) {  // add new lines
301                                         if( *bp == '\n' || ((bp-lp)>=60 && *bp==' ') )
302                                                 *(lp=bp) = '\n';
303                                 }
304                                 *cp++ = '\n';  *cp = 0;  // trailing new line
305                         }
306                 }
307         }
308
309         *cp = 0;
310         mpeg3_close(fd);
311         return;
312 }
313
314 int FileMPEG::get_audio_for_video(int vstream, int astream, int64_t &channel_mask)
315 {
316         channel_mask = 0;
317         if( !fd ) return -1;
318         int elements = mpeg3_dvb_channel_count(fd);
319         if( elements <= 0 ) return -1;
320
321         int pidx = -1;
322         int total_astreams = 0, total_vstreams = 0;
323         for( int n=0; pidx<0 && n<elements; ++n ) {
324                 total_astreams = total_vstreams = 0;
325                 if( mpeg3_dvb_total_vstreams(fd,n,&total_vstreams) ||
326                     mpeg3_dvb_total_astreams(fd,n,&total_astreams) ) continue;
327                 if( !total_vstreams || !total_astreams ) continue;
328                 for( int i=0; pidx<0 && i<total_vstreams; ++i ) {
329                         int vstrm = -1;
330                         if( mpeg3_dvb_vstream_number(fd,n,i,&vstrm) ) continue;
331                         if( vstrm == vstream ) pidx = n;
332                 }
333         }
334         if( pidx < 0 ) return -1;
335         int ret = -1;
336         int64_t channels = 0;
337         for( int i=0; i<total_astreams; ++i ) {
338                 int astrm = -1;
339                 if( mpeg3_dvb_astream_number(fd,pidx,i,&astrm,0) ) continue;
340                 if( astrm < 0 ) continue;
341                 if( ret < 0 ) ret = astrm;
342                 if( astream > 0 ) { --astream;  continue; }
343                 int atrack = 0;
344                 for(int i=0; i<astrm; ++i )
345                         atrack += mpeg3_audio_channels(fd, i);
346                 int64_t mask = (1 << mpeg3_audio_channels(fd, astrm)) - 1;
347                 channels |= mask << atrack;
348                 if( !astream ) break;
349         }
350         channel_mask = channels;
351         return ret;
352 }
353
354 int FileMPEG::reset_parameters_derived()
355 {
356         wrote_header = 0;
357         mjpeg_out = 0;
358         mjpeg_eof = 0;
359         mjpeg_error = 0;
360         recd_fd = -1;
361         fd = 0;
362         video_out = 0;
363         prev_track = 0;
364         temp_frame = 0;
365         twolame_temp = 0;
366         twolame_out = 0;
367         twolame_allocation = 0;
368         twolame_result = 0;
369         twofp = 0;
370         twopts = 0;
371         lame_temp[0] = 0;
372         lame_temp[1] = 0;
373         lame_allocation = 0;
374         lame_global = 0;
375         lame_output = 0;
376         lame_output_allocation = 0;
377         lame_fd = 0;
378         lame_started = 0;
379         return 0;
380 }
381
382
383 int FileMPEG::open_file(int rd, int wr)
384 {
385         int result = 0;
386
387         if(rd) {
388                 fd = 0;
389                 char toc_name[BCTEXTLEN];
390                 result = file->preferences->get_asset_file_path(asset, toc_name);
391                 if( result >= 0 ) {
392                         int error = 0;
393 // if toc exists, use it otherwise just probe file
394                         char *path = !result ? toc_name : asset->path;
395                         fd = mpeg3_open_title(asset->path, path, &error);
396                         if( !fd ) {
397                                 switch( error ) {
398                                 case zmpeg3_t::ERR_INVALID_TOC_VERSION:
399                                         eprintf(_("Couldn't open %s: invalid table of contents version.\n"),asset->path);
400                                         result = 1;
401                                         break;
402                                 case zmpeg3_t::ERR_TOC_DATE_MISMATCH:
403                                         eprintf(_("Couldn't open %s: table of contents out of date.\n"),asset->path);
404                                         result = 1;
405                                         break;
406                                 default:
407                                         eprintf(_("Couldn't open %s: table of contents corrupt.\n"),asset->path);
408                                         result = -1;
409                                         break;
410                                 }
411                                 if( result > 0 ) {
412                                         eprintf(_("Rebuilding the table of contents\n"));
413                                 }
414
415                         }
416                         else {
417                                 if( mpeg3_has_toc(fd) )
418                                         result = 0;
419                                 else if( mpeg3_total_vstreams(fd) || mpeg3_total_astreams(fd) )
420                                         result = 1;
421                                 else {
422                                         eprintf(_("Couldn't open %s: no audio or video.\n"),asset->path);
423                                         result = -1;
424                                 }
425                         }
426                 }
427
428                 if( result > 0 ) {
429                         if( fd ) { mpeg3_close(fd);  fd = 0; }
430                         result = create_toc(toc_name);
431                 }
432
433                 if( !result ) {
434                         mpeg3_set_cpus(fd, file->cpus < 4 ? file->cpus : 4);
435                         file->current_program = mpeg3_set_program(fd, -1);
436                         if( asset->program < 0 )
437                                 asset->program = file->current_program;
438
439                         asset->audio_data = mpeg3_has_audio(fd);
440                         if(asset->audio_data) {
441                                 asset->channels = 0;
442                                 for(int i = 0; i < mpeg3_total_astreams(fd); i++) {
443                                         asset->channels += mpeg3_audio_channels(fd, i);
444                                 }
445                                 if(!asset->sample_rate)
446                                         asset->sample_rate = mpeg3_sample_rate(fd, 0);
447                                 asset->audio_length = mpeg3_audio_samples(fd, 0);
448                                 if( !asset->channels || !asset->sample_rate )
449                                         result = 1;
450                         }
451
452                         asset->video_data = mpeg3_has_video(fd);
453                         if( !result && asset->video_data ) {
454 //TODO: this is not as easy as just looking at headers.
455 //most interlaced media is rendered as FRM, not TOP/BOT in coding ext hdrs.
456 //currently, just using the assetedit menu to set the required result as needed.
457 //                              if( asset->interlace_mode == BC_ILACE_MODE_UNDETECTED )
458 //                                      asset->interlace_mode = mpeg3_detect_interlace(fd, 0);
459                                 if( !asset->layers ) {
460                                         asset->layers = mpeg3_total_vstreams(fd);
461                                 }
462                                 asset->actual_width = mpeg3_video_width(fd, 0);
463                                 if( !asset->width )
464                                         asset->width = asset->actual_width;
465                                 asset->actual_height = mpeg3_video_height(fd, 0);
466                                 if( !asset->height )
467                                         asset->height = asset->actual_height;
468                                 if( !asset->video_length )
469                                         asset->video_length = mpeg3_video_frames(fd, 0);
470                                 if( !asset->vmpeg_cmodel )
471                                         asset->vmpeg_cmodel = bc_colormodel(mpeg3_colormodel(fd, 0));
472                                 if( !asset->frame_rate )
473                                         asset->frame_rate = mpeg3_frame_rate(fd, 0);
474                         }
475                 }
476                 if( result ) {
477                         eprintf(_("Couldn't open %s: failed.\n"), asset->path);
478                 }
479         }
480         
481         if( !result && wr && asset->format == FILE_VMPEG ) {
482 // Heroine Virtual encoder
483 //  this one is cinelerra-x.x.x/mpeg2enc
484                 if(asset->vmpeg_cmodel == BC_YUV422P)
485                 {
486                         char bitrate_string[BCTEXTLEN];
487                         char quant_string[BCTEXTLEN];
488                         char iframe_string[BCTEXTLEN];
489
490                         sprintf(bitrate_string, "%d", asset->vmpeg_bitrate);
491                         sprintf(quant_string, "%d", asset->vmpeg_quantization);
492                         sprintf(iframe_string, "%d", asset->vmpeg_iframe_distance);
493
494 // Construct command line
495                         if(!result)
496                         {
497                                 const char *exec_path = File::get_cinlib_path();
498                                 sprintf(mjpeg_command, "%s/%s", exec_path, HVPEG_EXE);
499                                 append_vcommand_line(mjpeg_command);
500
501                                 if(asset->aspect_ratio > 0)
502                                 {
503                                         append_vcommand_line("-a");
504 // Square pixels
505                                         if(EQUIV((double)asset->width / asset->height,
506                                                 asset->aspect_ratio))
507                                                 append_vcommand_line("1");
508                                         else
509                                         if(EQUIV(asset->aspect_ratio, 1.333))
510                                                 append_vcommand_line("2");
511                                         else
512                                         if(EQUIV(asset->aspect_ratio, 1.777))
513                                                 append_vcommand_line("3");
514                                         else
515                                         if(EQUIV(asset->aspect_ratio, 2.11))
516                                                 append_vcommand_line("4");
517                                 }
518
519                                 append_vcommand_line(asset->vmpeg_derivative == 1 ? "-1" : "");
520                                 append_vcommand_line(asset->vmpeg_cmodel == BC_YUV422P ? "-422" : "");
521                                 if(asset->vmpeg_fix_bitrate)
522                                 {
523                                         append_vcommand_line("-b");
524                                         append_vcommand_line(bitrate_string);
525                                 }
526                                 else
527                                 {
528                                         append_vcommand_line("-q");
529                                         append_vcommand_line(quant_string);
530                                 }
531                                 append_vcommand_line("-n");
532                                 append_vcommand_line(iframe_string);
533                                 append_vcommand_line(asset->vmpeg_progressive ? "-p" : "");
534                                 append_vcommand_line(asset->vmpeg_denoise ? "-d" : "");
535                                 append_vcommand_line(file->cpus <= 1 ? "-u" : "");
536                                 append_vcommand_line(asset->vmpeg_seq_codes ? "-g" : "");
537                                 append_vcommand_line(asset->path);
538
539                                 video_out = new FileMPEGVideo(this);
540                                 video_out->start();
541                         }
542                 }
543                 else
544 // mjpegtools encoder
545 //  this one is cinelerra-x.x.x/thirdparty/mjpegtools/mpeg2enc
546                 {
547                         const char *exec_path = File::get_cinlib_path();
548                         sprintf(mjpeg_command, "%s/%s -v 0 ", exec_path, MJPEG_EXE);
549
550 // Must disable interlacing if MPEG-1
551                         switch (asset->vmpeg_preset)
552                         {
553                                 case 0: asset->vmpeg_progressive = 1; break;
554                                 case 1: asset->vmpeg_progressive = 1; break;
555                                 case 2: asset->vmpeg_progressive = 1; break;
556                         }
557
558                         char string[BCTEXTLEN];
559 // The current usage of mpeg2enc requires bitrate of 0 when quantization is fixed and
560 // quantization of 1 when bitrate is fixed.  Perfectly intuitive.
561                         if(asset->vmpeg_fix_bitrate)
562                         {
563                                 sprintf(string, " -b %d -q 1", asset->vmpeg_bitrate / 1000);
564                         }
565                         else
566                         {
567                                 sprintf(string, " -b 0 -q %d", asset->vmpeg_quantization);
568                         }
569                         strcat(mjpeg_command, string);
570
571
572
573
574
575
576 // Aspect ratio
577                         int aspect_ratio_code = -1;
578                         if(asset->aspect_ratio > 0)
579                         {
580                                 int ncodes = sizeof(aspect_ratio_codes) / sizeof(double);
581                                 for(int i = 1; i < ncodes; i++)
582                                 {
583                                         if(EQUIV(aspect_ratio_codes[i], asset->aspect_ratio))
584                                         {
585                                                 aspect_ratio_code = i;
586                                                 break;
587                                         }
588                                 }
589                         }
590
591
592 // Square pixels
593                         if(EQUIV((double)asset->width / asset->height, asset->aspect_ratio))
594                                 aspect_ratio_code = 1;
595                         
596                         if(aspect_ratio_code < 0)
597                         {
598                                 eprintf(_("Unsupported aspect ratio %f\n"), asset->aspect_ratio);
599                                 aspect_ratio_code = 2;
600                         }
601                         sprintf(string, " -a %d", aspect_ratio_code);
602                         strcat(mjpeg_command, string);
603
604
605
606
607
608
609 // Frame rate
610                         int frame_rate_code = -1;
611                         int ncodes = sizeof(frame_rate_codes) / sizeof(double);
612                         for(int i = 1; i < ncodes; ++i)
613                         {
614                                 if(EQUIV(asset->frame_rate, frame_rate_codes[i]))
615                                 {
616                                         frame_rate_code = i;
617                                         break;
618                                 }
619                         }
620                         if(frame_rate_code < 0)
621                         {
622                                 frame_rate_code = 4;
623                                 eprintf(_("Unsupported frame rate %f\n"), asset->frame_rate);
624                         }
625                         sprintf(string, " -F %d", frame_rate_code);
626                         strcat(mjpeg_command, string);
627
628
629
630
631
632                         strcat(mjpeg_command, 
633                                 asset->vmpeg_progressive ? " -I 0" : " -I 1");
634                         
635
636
637                         sprintf(string, " -M %d", file->cpus);
638                         strcat(mjpeg_command, string);
639
640
641                         if(!asset->vmpeg_progressive)
642                         {
643                                 strcat(mjpeg_command, asset->vmpeg_field_order ? " -z b" : " -z t");
644                         }
645
646
647                         sprintf(string, " -f %d", asset->vmpeg_preset);
648                         strcat(mjpeg_command, string);
649
650
651                         sprintf(string, " -g %d -G %d", asset->vmpeg_iframe_distance, asset->vmpeg_iframe_distance);
652                         strcat(mjpeg_command, string);
653
654
655                         if(asset->vmpeg_seq_codes) strcat(mjpeg_command, " -s");
656
657
658                         sprintf(string, " -R %d", CLAMP(asset->vmpeg_pframe_distance, 0, 2));
659                         strcat(mjpeg_command, string);
660
661                         sprintf(string, " -o '%s'", asset->path);
662                         strcat(mjpeg_command, string);
663
664
665
666                         printf("FileMPEG::open_file: Running %s\n", mjpeg_command);
667                         if(!(mjpeg_out = popen(mjpeg_command, "w")))
668                         {
669                                 perror("FileMPEG::open_file");
670                                 eprintf(_("Error while opening \"%s\" for writing\n%m\n"), mjpeg_command);
671                                 return 1;
672                         }
673
674                         video_out = new FileMPEGVideo(this);
675                         video_out->start();
676                 }
677         }
678         else if( !result && wr && asset->format == FILE_AMPEG) {
679                 //char encoder_string[BCTEXTLEN]; encoder_string[0] = 0;
680 //printf("FileMPEG::open_file 1 %d\n", asset->ampeg_derivative);
681
682                 if(asset->ampeg_derivative == 2)
683                 {
684                         twofp = fopen(asset->path, "w" );
685                         if( !twofp ) return 1;
686                         twopts = twolame_init();
687                         int channels = asset->channels >= 2 ? 2 : 1;
688                         twolame_set_num_channels(twopts, channels);
689                         twolame_set_in_samplerate(twopts, asset->sample_rate);
690                         twolame_set_mode(twopts, channels >= 2 ?
691                                 TWOLAME_JOINT_STEREO : TWOLAME_MONO);
692                         twolame_set_bitrate(twopts, asset->ampeg_bitrate);
693                         twolame_init_params(twopts);
694                 }
695                 else
696                 if(asset->ampeg_derivative == 3)
697                 {
698                         lame_global = lame_init();
699 //                      lame_set_brate(lame_global, asset->ampeg_bitrate / 1000);
700                         lame_set_brate(lame_global, asset->ampeg_bitrate);
701                         lame_set_quality(lame_global, 0);
702                         lame_set_in_samplerate(lame_global, 
703                                 asset->sample_rate);
704                         lame_set_num_channels(lame_global,
705                                 asset->channels);
706                         if((result = lame_init_params(lame_global)) < 0)
707                         {
708                                 eprintf(_("encode: lame_init_params returned %d\n"), result);
709                                 lame_close(lame_global);
710                                 lame_global = 0;
711                         }
712                         else
713                         if(!(lame_fd = fopen(asset->path, "w")))
714                         {
715                                 perror("FileMPEG::open_file");
716                                 eprintf(_("Error while opening \"%s\" for writing\n%m\n"), asset->path);
717                                 lame_close(lame_global);
718                                 lame_global = 0;
719                                 result = 1;
720                         }
721                 }
722                 else
723                 {
724                         eprintf(_("ampeg_derivative=%d\n"), asset->ampeg_derivative);
725                         result = 1;
726                 }
727         }
728
729 // Transport stream for DVB capture
730         if( !result && !rd && !wr && asset->format == FILE_MPEG ) {
731                 if( (recd_fd = open(asset->path, O_CREAT+O_TRUNC+O_WRONLY,
732                         S_IRUSR+S_IWUSR + S_IRGRP+S_IWGRP)) < 0 ) {
733                         perror("FileMPEG::open_file");
734                         eprintf(_("Error while opening \"%s\" for writing\n%m\n"), asset->path);
735                         result = 1;
736                 }
737         }
738
739
740 //asset->dump();
741         return result;
742 }
743
744
745
746
747
748 int FileMPEG::set_skimming(int track, int skim, skim_fn fn, void *vp)
749 {
750         return !fn ? mpeg3_set_thumbnail_callback(fd, track, 0, 0, 0, 0) :
751                 mpeg3_set_thumbnail_callback(fd, track, skim, 1, fn, vp);
752 }
753
754 int FileMPEG::skimming(void *vp, int track)
755 {
756         File *file = (File *)vp;
757         FileMPEG *mpeg = (FileMPEG *)file->file;
758         return mpeg->skim_result = mpeg->skim_callback(mpeg->skim_data, track);
759 }
760
761 int FileMPEG::skim_video(int track, void *vp, skim_fn fn)
762 {
763         skim_callback = fn;  skim_data = vp;
764         mpeg3_set_thumbnail_callback(fd, track, 1, 1, skimming, (void*)file);
765         skim_result = -1;
766         while( skim_result < 0 && !mpeg3_end_of_video(fd, track) )
767                 mpeg3_drop_frames(fd, 1, track);
768         mpeg3_set_thumbnail_callback(fd, track, 0, 0, 0, 0);
769         return skim_result;
770 }
771
772
773
774 int FileMPEG::toc_nail(void *vp, int track)
775 {
776         File *file = (File *)vp;
777         FileMPEG *mpeg = (FileMPEG *)file->file;
778         int64_t framenum; uint8_t *tdat; int mw, mh;
779         if( mpeg->get_thumbnail(track, framenum, tdat, mw, mh) ) return 1;
780         int pid, width, height;  double framerate;
781         if( mpeg->get_video_info(track, pid, framerate, width, height) ) return 1;
782         if( pid < 0 || framerate <= 0 ) return 1;
783         double position = framenum / framerate;
784 //printf("t%d/%03x f"_LD", %dx%d %dx%d\n",track,pid,framenum,mw,mh,width,height);
785         MWindow::commercials->get_frame(file, pid, position, tdat, mw, mh, width, height);
786         return 0;
787 }
788
789
790 int FileMPEG::create_toc(char *toc_path)
791 {
792 // delete any existing toc files
793         char toc_file[BCTEXTLEN];
794         strcpy(toc_file, toc_path);
795         remove(toc_file);
796         char *bp = strrchr(toc_file, '/');
797         if( !bp ) bp = toc_file;
798         char *sfx = strrchr(bp,'.');
799         if( sfx ) {
800                 strcpy(sfx+1,"toc");
801                 remove(toc_file);
802         }
803
804         int64_t total_bytes = 0, last_bytes = -1;
805         fd = mpeg3_start_toc(asset->path, toc_file,
806                                 file->current_program, &total_bytes);
807         if( !fd ) {
808                 eprintf(_("cant start toc/idx for file: %s\n"), asset->path);
809                 return 1;
810         }
811
812 // File needs a table of contents.
813         struct timeval new_time, prev_time, start_time, current_time;
814         gettimeofday(&prev_time, 0);  gettimeofday(&start_time, 0);
815         if( file->preferences->scan_commercials ) {
816                 set_skimming(-1, 1, toc_nail, file);
817                 if( MWindow::commercials->resetDb() != 0 )
818                         eprintf(_("cant access commercials database"));
819         }
820 // This gets around the fact that MWindowGUI may be locked.
821         char progress_title[BCTEXTLEN];
822         sprintf(progress_title, _("Creating %s\n"), toc_file);
823         BC_ProgressBox progress(-1, -1, progress_title, total_bytes);
824         progress.start();
825
826         int result = 0;
827         while( !result ) {
828                 int64_t bytes_processed = 0;
829                 if( mpeg3_do_toc(fd, &bytes_processed) ) break;
830
831                 if( bytes_processed >= total_bytes ) break;
832                 if( bytes_processed == last_bytes ) {
833                         eprintf(_("toc scan stopped before eof"));
834                         break;
835                 }
836                 last_bytes = bytes_processed;
837
838                 gettimeofday(&new_time, 0);
839                 if( new_time.tv_sec - prev_time.tv_sec >= 1 ) {
840                         gettimeofday(&current_time, 0);
841                         int64_t elapsed_seconds = current_time.tv_sec - start_time.tv_sec;
842                         int64_t total_seconds = !bytes_processed ? 0 :
843                                  elapsed_seconds * total_bytes / bytes_processed;
844                         int64_t eta = total_seconds - elapsed_seconds;
845                         progress.update(bytes_processed, 1);
846                         char string[BCTEXTLEN];
847                         sprintf(string, "%sETA: %jdm%jds",
848                                 progress_title, eta / 60, eta % 60);
849                         progress.update_title(string, 1);
850 //                      fprintf(stderr, "ETA: %dm%ds        \r", 
851 //                              bytes_processed * 100 / total_bytes,
852 //                              eta / 60, eta % 60);
853 //                      fflush(stdout);
854                         prev_time = new_time;
855                 }
856
857                 if( progress.is_cancelled() ) {
858                         result = 1;
859                         break;
860                 }
861         }
862
863         if( file->preferences->scan_commercials ) {
864                 if( !result ) MWindow::commercials->write_ads(asset->path);
865                 MWindow::commercials->closeDb();
866         }
867
868         mpeg3_stop_toc(fd);
869         fd = 0;
870
871         progress.stop_progress();
872
873         if( result ) {
874                 remove_file(toc_file);
875                 return 1;
876         }
877
878 // Reopen file from toc path instead of asset path.
879         int error = 0;
880         fd = mpeg3_open(toc_file, &error);
881         if( !fd ) {
882                 eprintf(_("mpeg3_open failed: %s"), toc_file);
883                 return 1;
884         }
885         return 0;
886 }
887
888 int FileMPEG::get_index(IndexFile *index_file, MainProgressBar *progress_bar)
889 {
890         if( !fd ) return 1;
891         IndexState *index_state = index_file->get_state();
892         index_state->reset_index();
893         index_state->reset_markers();
894
895 // Convert the index tables from tracks to channels.
896         int ntracks = mpeg3_index_tracks(fd);
897         if( !ntracks ) return 1;
898
899         int index_zoom = mpeg3_index_zoom(fd);
900         int64_t offset = 0;
901         for( int i = 0; i < ntracks; ++i ) {
902                 int nch = mpeg3_index_channels(fd, i);
903                 for( int j = 0; j < nch; ++j ) {
904                         float *bfr = (float *)mpeg3_index_data(fd, i, j);
905                         int64_t size = 2*mpeg3_index_size(fd, i);
906                         index_state->add_index_entry(bfr, offset, size);
907                         offset += size;
908                 }
909         }
910
911         FileSystem fs;
912         int64_t file_bytes = fs.get_size(asset->path);
913         char *index_path = index_file->index_filename;
914         return index_state->write_index(index_path, asset, index_zoom, file_bytes);
915 }
916
917
918
919
920
921
922 void FileMPEG::append_vcommand_line(const char *string)
923 {
924         if(string[0])
925         {
926                 char *argv = cstrdup(string);
927                 vcommand_line.append(argv);
928         }
929 }
930
931 int FileMPEG::close_file()
932 {
933         mjpeg_eof = 1;
934         next_frame_lock->unlock();
935
936         if(fd)
937         {
938                 mpeg3_close(fd);
939         }
940
941         if(video_out)
942         {
943 // End of sequence signal
944                 if(file->asset->vmpeg_cmodel == BC_YUV422P)
945                 {
946                         mpeg2enc_set_input_buffers(1, 0, 0, 0);
947                 }
948                 delete video_out;
949                 video_out = 0;
950         }
951
952         vcommand_line.remove_all_objects();
953
954         if(twofp) {
955                 unsigned char opkt[1152*2]; 
956                 int ret = twolame_encode_flush(twopts, opkt, sizeof(opkt));
957                 if( ret > 0 )
958                         fwrite(opkt, 1, ret, twofp);
959                 else if( ret < 0 )
960                         fprintf(stderr, _("twolame error encoding audio: %d\n"), ret);
961                 fclose(twofp);  twofp = 0;
962         }
963         if( twopts ) { twolame_close(&twopts); twopts = 0; }
964
965         if(lame_global)
966                 lame_close(lame_global);
967
968         if(temp_frame) delete temp_frame;
969         if(twolame_temp) delete [] twolame_temp;
970
971         if(lame_temp[0]) delete [] lame_temp[0];
972         if(lame_temp[1]) delete [] lame_temp[1];
973         if(lame_output) delete [] lame_output;
974         if(lame_fd) fclose(lame_fd);
975
976         if(mjpeg_out) pclose(mjpeg_out);
977
978         if( recd_fd >= 0 ) {
979                 close(recd_fd);
980                 recd_fd = -1;
981         }
982
983         reset_parameters();
984
985         FileBase::close_file();
986         return 0;
987 }
988
989 int FileMPEG::get_best_colormodel(Asset *asset, int driver)
990 {
991 //printf("FileMPEG::get_best_colormodel 1\n");
992         switch(driver)
993         {
994                 case PLAYBACK_X11:
995                         return BC_RGB888;
996                 case PLAYBACK_X11_XV:
997                 case PLAYBACK_ASYNCHRONOUS:
998                         return zmpeg3_cmdl(asset->vmpeg_cmodel) > 0 ?
999                                 asset->vmpeg_cmodel : BC_RGB888;
1000                 case PLAYBACK_X11_GL:
1001                         return BC_YUV888;
1002                 case PLAYBACK_LML:
1003                 case PLAYBACK_BUZ:
1004                         return BC_YUV422P;
1005                 case PLAYBACK_DV1394:
1006                 case PLAYBACK_FIREWIRE:
1007                         return BC_YUV422P;
1008                 case VIDEO4LINUX:
1009                 case VIDEO4LINUX2:
1010                         return zmpeg3_cmdl(asset->vmpeg_cmodel) > 0 ?
1011                                 asset->vmpeg_cmodel : BC_RGB888;
1012                 case VIDEO4LINUX2JPEG:
1013                         return BC_COMPRESSED;
1014                 case CAPTURE_DVB:
1015                 case VIDEO4LINUX2MPEG:
1016                         return BC_YUV422P;
1017                 case CAPTURE_JPEG_WEBCAM:
1018                         return BC_COMPRESSED;
1019                 case CAPTURE_YUYV_WEBCAM:
1020                         return BC_YUV422;
1021                 case CAPTURE_BUZ:
1022                 case CAPTURE_LML:
1023                         return BC_YUV422;
1024                 case CAPTURE_FIREWIRE:
1025                 case CAPTURE_IEC61883:
1026                         return BC_YUV422P;
1027         }
1028         eprintf(_("unknown driver %d\n"),driver);
1029         return BC_RGB888;
1030 }
1031
1032 int FileMPEG::colormodel_supported(int colormodel)
1033 {
1034         return colormodel;
1035 }
1036
1037 int FileMPEG::can_copy_from(Asset *asset, int64_t position)
1038 {
1039         return 0;
1040 }
1041
1042 int FileMPEG::set_audio_position(int64_t sample)
1043 {
1044 #if 0
1045         if(!fd) return 1;
1046         
1047         int channel, stream;
1048         to_streamchannel(file->current_channel, stream, channel);
1049
1050 //printf("FileMPEG::set_audio_position %d %d %d\n", sample, mpeg3_get_sample(fd, stream), last_sample);
1051         if(sample != mpeg3_get_sample(fd, stream) &&
1052                 sample != last_sample)
1053         {
1054                 if(sample >= 0 && sample < asset->audio_length)
1055                 {
1056 //printf("FileMPEG::set_audio_position seeking stream %d\n", sample);
1057                         return mpeg3_set_sample(fd, sample, stream);
1058                 }
1059                 else
1060                         return 1;
1061         }
1062 #endif
1063         return 0;
1064 }
1065
1066 int FileMPEG::set_video_position(int64_t pos)
1067 {
1068         if( !fd || pos < 0 || pos >= asset->video_length )
1069                 return 1;
1070 //printf("FileMPEG::set_video_position 1 %jd\n", x);
1071         mpeg3_set_frame(fd, pos, file->current_layer);
1072         return 0;
1073 }
1074
1075 int64_t FileMPEG::get_memory_usage()
1076 {
1077         int64_t result = file->rd && fd ? mpeg3_memory_usage(fd) : 0;
1078 //printf("FileMPEG::get_memory_usage %d  %jd\n", __LINE__, result);
1079         return result;
1080 }
1081
1082 int FileMPEG::set_program(int no)
1083 {
1084         return fd ? mpeg3_set_program(fd, no) : -1;
1085 }
1086
1087 int FileMPEG::get_cell_time(int no, double &time)
1088 {
1089         return fd ? mpeg3_get_cell_time(fd, no, &time) : -1;
1090 }
1091
1092 int FileMPEG::get_system_time(int64_t &tm)
1093 {
1094         return fd ? mpeg3_dvb_get_system_time(fd, &tm) : -1;
1095 }
1096
1097 int FileMPEG::get_video_pid(int track)
1098 {
1099         return fd ? mpeg3_video_pid(fd, track) : -1;
1100 }
1101
1102 int FileMPEG::get_video_info(int track, int &pid,
1103                 double &framerate, int &width, int &height, char *title)
1104 {
1105         if( !fd ) return -1;
1106         pid = mpeg3_video_pid(fd, track);
1107         framerate = mpeg3_frame_rate(fd, track);
1108         width = mpeg3_video_width(fd, track);
1109         height = mpeg3_video_height(fd, track);
1110         if( !title ) return 0;
1111         *title = 0;
1112
1113         int elements = mpeg3_dvb_channel_count(fd);
1114         for( int n=0; n<elements; ++n ) {
1115                 int major, minor, total_vstreams, vstream, vidx;
1116                 if( mpeg3_dvb_get_channel(fd,n, &major, &minor) ||
1117                     mpeg3_dvb_total_vstreams(fd,n,&total_vstreams) ) continue;
1118                 for( vidx=0; vidx<total_vstreams; ++vidx ) {
1119                         if( mpeg3_dvb_vstream_number(fd,n,vidx,&vstream) ) continue;
1120                         if( vstream < 0 ) continue;
1121                         if( vstream == track ) {
1122                                 sprintf(title, "%3d.%-3d", major, minor);
1123                                 return 0;
1124                         }
1125                 }
1126         }
1127         return 0;
1128 }
1129
1130 int FileMPEG::select_video_stream(Asset *asset, int vstream)
1131 {
1132         if( !fd ) return -1;
1133         asset->width = mpeg3_video_width(fd, vstream);
1134         asset->height = mpeg3_video_height(fd, vstream);
1135         asset->video_length = mpeg3_video_frames(fd, vstream);
1136         asset->frame_rate = mpeg3_frame_rate(fd, vstream);
1137         return 0;
1138 }
1139
1140 int FileMPEG::select_audio_stream(Asset *asset, int astream)
1141 {
1142         if( !fd ) return -1;
1143         asset->sample_rate = mpeg3_sample_rate(fd, astream);
1144         asset->audio_length = mpeg3_audio_samples(fd, astream);
1145         return 0;
1146 }
1147
1148 int FileMPEG::get_thumbnail(int stream,
1149         int64_t &position, unsigned char *&thumbnail, int &ww, int &hh)
1150 {
1151         return !fd ? -1 :
1152                 mpeg3_get_thumbnail(fd, stream, &position, &thumbnail, &ww, &hh);
1153 }
1154
1155 int FileMPEG::write_samples(double **buffer, int64_t len)
1156 {
1157         int result = 0;
1158
1159 //printf("FileMPEG::write_samples 1\n");
1160         if(asset->ampeg_derivative == 2) {
1161 // Convert to int16
1162                 int channels = MIN(asset->channels, 2);
1163                 int64_t audio_size = len * channels * 2;
1164                 if(twolame_allocation < audio_size) {
1165                         if(twolame_temp) delete [] twolame_temp;
1166                         twolame_temp = new unsigned char[audio_size];
1167                         twolame_allocation = audio_size;
1168                         if(twolame_out) delete [] twolame_out;
1169                         twolame_out = new unsigned char[audio_size + 1152];
1170                 }
1171
1172                 for(int i = 0; i < channels; i++) {
1173                         int16_t *output = ((int16_t*)twolame_temp) + i;
1174                         double *input = buffer[i];
1175                         for(int j = 0; j < len; j++) {
1176                                 int sample = (int)(*input * 0x7fff);
1177                                 *output = (int16_t)(CLIP(sample, -0x8000, 0x7fff));
1178                                 output += channels;
1179                                 input++;
1180                         }
1181                 }
1182                 int ret = twolame_encode_buffer_interleaved(twopts,
1183                                 (int16_t*)twolame_temp, len,
1184                                 twolame_out, twolame_allocation+1152);
1185                 if( ret > 0 )
1186                         fwrite(twolame_out, 1, ret, twofp);
1187                 else if( ret < 0 )
1188                         fprintf(stderr, _("twolame error encoding audio: %d\n"), ret);
1189         }
1190         else
1191         if(asset->ampeg_derivative == 3)
1192         {
1193                 int channels = MIN(asset->channels, 2);
1194                 int64_t audio_size = len * channels;
1195                 if(!lame_global) return 1;
1196                 if(!lame_fd) return 1;
1197                 if(lame_allocation < audio_size)
1198                 {
1199                         if(lame_temp[0]) delete [] lame_temp[0];
1200                         if(lame_temp[1]) delete [] lame_temp[1];
1201                         lame_temp[0] = new float[audio_size];
1202                         lame_temp[1] = new float[audio_size];
1203                         lame_allocation = audio_size;
1204                 }
1205
1206                 if(lame_output_allocation < audio_size * 4)
1207                 {
1208                         if(lame_output) delete [] lame_output;
1209                         lame_output_allocation = audio_size * 4;
1210                         lame_output = new char[lame_output_allocation];
1211                 }
1212
1213                 for(int i = 0; i < channels; i++)
1214                 {
1215                         float *output = lame_temp[i];
1216                         double *input = buffer[i];
1217                         for(int j = 0; j < len; j++)
1218                         {
1219                                 *output++ = *input++ * (float)32768;
1220                         }
1221                 }
1222
1223                 result = lame_encode_buffer_float(lame_global,
1224                         lame_temp[0],
1225                         (channels > 1) ? lame_temp[1] : lame_temp[0],
1226                         len,
1227                         (unsigned char*)lame_output,
1228                         lame_output_allocation);
1229                 if(result > 0)
1230                 {
1231                         char *real_output = lame_output;
1232                         int bytes = result;
1233                         if(!lame_started)
1234                         {
1235                                 for(int i = 0; i < bytes; i++)
1236                                         if(lame_output[i])
1237                                         {
1238                                                 real_output = &lame_output[i];
1239                                                 lame_started = 1;
1240                                                 bytes -= i;
1241                                                 break;
1242                                         }
1243                         }
1244                         if(bytes > 0 && lame_started)
1245                         {
1246                                 result = !fwrite(real_output, 1, bytes, lame_fd);
1247                                 if(result) {
1248                                         perror("FileMPEG::write_samples");
1249                                         eprintf(_("write failed: %m"));
1250                                 }
1251                         }
1252                         else
1253                                 result = 0;
1254                 }
1255                 else
1256                         result = 1;
1257         }
1258
1259         return result;
1260 }
1261
1262 int FileMPEG::write_frames(VFrame ***frames, int len)
1263 {
1264         int result = 0;
1265
1266         if(video_out)
1267         {
1268                 int temp_w = (int)((asset->width + 15) / 16) * 16;
1269                 int temp_h;
1270
1271                 int output_cmodel = asset->vmpeg_cmodel;
1272 // verify colormodel supported in MPEG output
1273                 switch( output_cmodel ) {
1274                 case BC_YUV420P:
1275                         if( file->preferences->dvd_yuv420p_interlace &&
1276                             ( asset->interlace_mode == BC_ILACE_MODE_TOP_FIRST ||
1277                               asset->interlace_mode == BC_ILACE_MODE_BOTTOM_FIRST ) )
1278                                 output_cmodel = BC_YUV420PI;
1279                 case BC_YUV422P:
1280                         break;
1281                 default:
1282                         return 1;
1283                 }
1284                 
1285 // Height depends on progressiveness
1286                 if(asset->vmpeg_progressive || asset->vmpeg_derivative == 1)
1287                         temp_h = (int)((asset->height + 15) / 16) * 16;
1288                 else
1289                         temp_h = (int)((asset->height + 31) / 32) * 32;
1290
1291 //printf("FileMPEG::write_frames 1\n");
1292                 
1293 // Only 1 layer is supported in MPEG output
1294                 for(int i = 0; i < 1; i++)
1295                 {
1296                         for(int j = 0; j < len && !result; j++)
1297                         {
1298                                 VFrame *frame = frames[i][j];
1299                                 
1300                                 
1301                                 
1302                                 if(asset->vmpeg_cmodel == BC_YUV422P)
1303                                 {
1304                                         if(frame->get_w() == temp_w &&
1305                                                 frame->get_h() == temp_h &&
1306                                                 frame->get_color_model() == output_cmodel)
1307                                         {
1308                                                 mpeg2enc_set_input_buffers(0, 
1309                                                         (char*)frame->get_y(),
1310                                                         (char*)frame->get_u(),
1311                                                         (char*)frame->get_v());
1312                                         }
1313                                         else
1314                                         {
1315                                                 if(temp_frame &&
1316                                                         (temp_frame->get_w() != temp_w ||
1317                                                         temp_frame->get_h() != temp_h ||
1318                                                         temp_frame->get_color_model() || output_cmodel))
1319                                                 {
1320                                                         delete temp_frame;
1321                                                         temp_frame = 0;
1322                                                 }
1323
1324
1325                                                 if(!temp_frame)
1326                                                 {
1327                                                         temp_frame = new VFrame(0, 
1328                                                                 -1,
1329                                                                 temp_w, 
1330                                                                 temp_h, 
1331                                                                 output_cmodel,
1332                                                                 -1);
1333                                                 }
1334
1335                                                 BC_CModels::transfer(temp_frame->get_rows(), 
1336                                                         frame->get_rows(),
1337                                                         temp_frame->get_y(),
1338                                                         temp_frame->get_u(),
1339                                                         temp_frame->get_v(),
1340                                                         frame->get_y(),
1341                                                         frame->get_u(),
1342                                                         frame->get_v(),
1343                                                         0,
1344                                                         0,
1345                                                         frame->get_w(),
1346                                                         frame->get_h(),
1347                                                         0,
1348                                                         0,
1349                                                         temp_frame->get_w(),
1350                                                         temp_frame->get_h(),
1351                                                         frame->get_color_model(), 
1352                                                         temp_frame->get_color_model(),
1353                                                         0, 
1354                                                         frame->get_w(),
1355                                                         temp_frame->get_w());
1356
1357                                                 mpeg2enc_set_input_buffers(0, 
1358                                                         (char*)temp_frame->get_y(),
1359                                                         (char*)temp_frame->get_u(),
1360                                                         (char*)temp_frame->get_v());
1361                                         }
1362                                 }
1363                                 else
1364                                 {
1365 // MJPEG uses the same dimensions as the input
1366 //printf("FileMPEG::write_frames %d\n", __LINE__);sleep(1);
1367                                         if(frame->get_color_model() == output_cmodel)
1368                                         {
1369                                                 mjpeg_y = frame->get_y();
1370                                                 mjpeg_u = frame->get_u();
1371                                                 mjpeg_v = frame->get_v();
1372                                         }
1373                                         else
1374                                         {
1375 //printf("FileMPEG::write_frames %d\n", __LINE__);sleep(1);
1376                                                 if(!temp_frame)
1377                                                 {
1378                                                         temp_frame = new VFrame(0, 
1379                                                                 -1,
1380                                                                 asset->width, 
1381                                                                 asset->height, 
1382                                                                 output_cmodel,
1383                                                                 -1);
1384                                                 }
1385
1386 // printf("FileMPEG::write_frames %d temp_frame=%p %p %p %p frame=%p %p %p %p color_model=%p %p\n", 
1387 // __LINE__,
1388 // temp_frame,
1389 // temp_frame->get_w(),
1390 // temp_frame->get_h(),
1391 // frame,
1392 // frame->get_w(),
1393 // frame->get_h(),
1394 // temp_frame->get_color_model(),
1395 // frame->get_color_model()); sleep(1);
1396                                                 temp_frame->transfer_from(frame);
1397 //printf("FileMPEG::write_frames %d\n", __LINE__);sleep(1);
1398
1399                                                 mjpeg_y = temp_frame->get_y();
1400                                                 mjpeg_u = temp_frame->get_u();
1401                                                 mjpeg_v = temp_frame->get_v();
1402                                         }
1403
1404
1405
1406
1407                                         next_frame_lock->unlock();
1408                                         next_frame_done->lock("FileMPEG::write_frames");
1409                                         if(mjpeg_error) result = 1;
1410                                 }
1411
1412
1413
1414
1415
1416                         }
1417                 }
1418         }
1419
1420
1421
1422         return result;
1423 }
1424
1425 int FileMPEG::zmpeg3_cmdl(int colormodel)
1426 {   
1427         switch( colormodel ) {
1428         case BC_BGR888:       return zmpeg3_t::cmdl_BGR888;
1429         case BC_BGR8888:      return zmpeg3_t::cmdl_BGRA8888;
1430         case BC_RGB565:       return zmpeg3_t::cmdl_RGB565;
1431         case BC_RGB888:       return zmpeg3_t::cmdl_RGB888;
1432         case BC_RGBA8888:     return zmpeg3_t::cmdl_RGBA8888;
1433         case BC_RGBA16161616: return zmpeg3_t::cmdl_RGBA16161616;
1434         case BC_YUV420P:      return zmpeg3_t::cmdl_YUV420P;
1435         case BC_YUV422P:      return zmpeg3_t::cmdl_YUV422P;
1436         case BC_YUV422:       return zmpeg3_t::cmdl_YUYV;
1437         case BC_YUV888:       return zmpeg3_t::cmdl_YUV888;
1438         case BC_YUVA8888:     return zmpeg3_t::cmdl_YUVA8888;
1439         }
1440         return -1;
1441 }   
1442
1443 int FileMPEG::bc_colormodel(int cmdl)
1444 {
1445         switch( cmdl ) {
1446         case zmpeg3_t::cmdl_BGR888:       return BC_BGR888;
1447         case zmpeg3_t::cmdl_BGRA8888:     return BC_BGR8888;
1448         case zmpeg3_t::cmdl_RGB565:       return BC_RGB565;
1449         case zmpeg3_t::cmdl_RGB888:       return BC_RGB888;
1450         case zmpeg3_t::cmdl_RGBA8888:     return BC_RGBA8888;
1451         case zmpeg3_t::cmdl_RGBA16161616: return BC_RGBA16161616;
1452         case zmpeg3_t::cmdl_YUV420P:      return BC_YUV420P;
1453         case zmpeg3_t::cmdl_YUV422P:      return BC_YUV422P;
1454         case zmpeg3_t::cmdl_YUYV:         return BC_YUV422;
1455         case zmpeg3_t::cmdl_YUV888:       return BC_YUV888;
1456         case zmpeg3_t::cmdl_YUVA8888:     return BC_YUVA8888;
1457         }
1458         return -1;
1459 }
1460
1461 const char *FileMPEG::zmpeg3_cmdl_name(int cmdl)
1462 {
1463 # define CMDL(nm) #nm
1464   static const char *cmdl_name[] = {
1465     CMDL(BGR888),
1466     CMDL(BGRA8888),
1467     CMDL(RGB565),
1468     CMDL(RGB888),
1469     CMDL(RGBA8888),
1470     CMDL(RGBA16161616),
1471     CMDL(UNKNOWN),
1472     CMDL(601_BGR888),
1473     CMDL(601_BGRA8888),
1474     CMDL(601_RGB888),
1475     CMDL(601_RGBA8888),
1476     CMDL(601_RGB565),
1477     CMDL(YUV420P),
1478     CMDL(YUV422P),
1479     CMDL(601_YUV420P),
1480     CMDL(601_YUV422P),
1481     CMDL(UYVY),
1482     CMDL(YUYV),
1483     CMDL(601_UYVY),
1484     CMDL(601_YUYV),
1485     CMDL(YUV888),
1486     CMDL(YUVA8888),
1487     CMDL(601_YUV888),
1488     CMDL(601_YUVA8888),
1489   };
1490   return cmdl>=0 && cmdl<lengthof(cmdl_name) ? cmdl_name[cmdl] : cmdl_name[6];
1491 }
1492
1493
1494 int FileMPEG::read_frame(VFrame *frame)
1495 {
1496         if(!fd) return 1;
1497         int result = 0;
1498         int width = mpeg3_video_width(fd,file->current_layer);
1499         int height = mpeg3_video_height(fd,file->current_layer);
1500         int stream_cmdl = mpeg3_colormodel(fd,file->current_layer);
1501         int stream_color_model = bc_colormodel(stream_cmdl);
1502         int frame_color_model = frame->get_color_model();
1503         int frame_cmdl = asset->interlace_mode == BC_ILACE_MODE_NOTINTERLACED ?
1504                 zmpeg3_cmdl(frame_color_model) : -1;
1505         mpeg3_show_subtitle(fd, file->current_layer, file->playback_subtitle);
1506
1507         switch( frame_color_model ) { // check for direct copy
1508         case BC_YUV420P:
1509                 if( frame_cmdl < 0 ) break;
1510         case BC_YUV422P:
1511                 if( stream_color_model == frame_color_model &&
1512                         width == frame->get_w() && height == frame->get_h() ) {
1513                         mpeg3_read_yuvframe(fd,
1514                                 (char*)frame->get_y(),
1515                                 (char*)frame->get_u(),
1516                                 (char*)frame->get_v(),
1517                                 0, 0, width, height,
1518                                 file->current_layer);
1519                         return result;
1520                 }
1521         }
1522
1523         if( frame_cmdl >= 0 ) {        // supported by read_frame
1524                 // cant rely on frame->get_rows(), format may not support it
1525                 int uvs = 0;
1526                 switch( frame_color_model ) {
1527                 case BC_YUV420P: uvs = 2;  break;
1528                 case BC_YUV422P: uvs = 1;  break;
1529                 }
1530                 //int w = frame->get_w();
1531                 int h = frame->get_h();
1532                 int bpl = frame->get_bytes_per_line();
1533                 int uvw = !uvs ? 0 : bpl / 2;
1534                 int uvh = !uvs ? 0 : h / uvs;
1535                 uint8_t *rows[h + 2*uvh], *rp;
1536                 int n = 0;
1537                 if( (rp=frame->get_y()) ) {
1538                         for( int i=0; i<h; ++i, rp+=bpl ) rows[n++] = rp;
1539                         rp = frame->get_u();
1540                         for( int i=0; i<uvh; ++i, rp+=uvw ) rows[n++] = rp;
1541                         rp = frame->get_v();
1542                         for( int i=0; i<uvh; ++i, rp+=uvw ) rows[n++] = rp;
1543                 }
1544                 else {
1545                         rp = frame->get_data();  uvh *= 2;
1546                         for( int i=0; i<h; ++i, rp+=bpl ) rows[n++] = rp;
1547                         for( int i=0; i<uvh; ++i, rp+=uvw ) rows[n++] = rp;
1548                 }
1549
1550                 mpeg3_read_frame(fd, 
1551                                 rows,                /* start of each output row */
1552                                 0, 0, width, height, /* input box */
1553                                 frame->get_w(),      /* Dimensions of output_rows */
1554                                 frame->get_h(), 
1555                                 frame_cmdl,
1556                                 file->current_layer);
1557                 return result;
1558         }
1559
1560         char *y, *u, *v;
1561         mpeg3_read_yuvframe_ptr(fd, &y, &u, &v, file->current_layer);
1562         if( y && u && v ) {
1563                 if( stream_color_model == BC_YUV420P &&
1564                     file->preferences->dvd_yuv420p_interlace && (
1565                         asset->interlace_mode == BC_ILACE_MODE_TOP_FIRST ||
1566                         asset->interlace_mode == BC_ILACE_MODE_BOTTOM_FIRST ) )
1567                                 stream_color_model = BC_YUV420PI;
1568                 BC_CModels::transfer(frame->get_rows(), 0,
1569                         frame->get_y(), frame->get_u(), frame->get_v(),
1570                         (unsigned char*)y, (unsigned char*)u, (unsigned char*)v,
1571                         0,0, width,height,  0,0, frame->get_w(),frame->get_h(),
1572                         stream_color_model, frame_color_model, 0, width, frame->get_w());
1573         }
1574
1575         return result;
1576 }
1577
1578
1579 void FileMPEG::to_streamchannel(int channel, int &stream_out, int &channel_out)
1580 {
1581         int total_astreams = mpeg3_total_astreams(fd);
1582         for(stream_out = 0; stream_out < total_astreams; ++stream_out )
1583         {
1584                 int stream_channels = mpeg3_audio_channels(fd, stream_out);
1585                 if( channel < stream_channels ) break;
1586                 channel -= stream_channels;
1587         }
1588         channel_out = channel;
1589 }
1590
1591 int FileMPEG::read_samples(double *buffer, int64_t len)
1592 {
1593         if(!fd) return 0;
1594         if(len < 0) return 0;
1595
1596 // Translate pure channel to a stream and a channel in the mpeg stream
1597         int stream, channel;
1598         to_streamchannel(file->current_channel, stream, channel);
1599
1600 //printf("FileMPEG::read_samples 1 current_sample=%jd len=%jd channel=%d\n", file->current_sample, len, channel);
1601
1602         mpeg3_set_sample(fd, 
1603                 file->current_sample,
1604                 stream);
1605         mpeg3_read_audio_d(fd, 
1606                 buffer, /* Pointer to pre-allocated buffer of doubles */
1607                 channel,          /* Channel to decode */
1608                 len,         /* Number of samples to decode */
1609                 stream);          /* Stream containing the channel */
1610
1611 //      last_sample = file->current_sample;
1612         return 0;
1613 }
1614
1615
1616
1617
1618
1619
1620 FileMPEGVideo::FileMPEGVideo(FileMPEG *file)
1621  : Thread(1, 0, 0)
1622 {
1623         this->file = file;
1624
1625
1626         if(file->asset->vmpeg_cmodel == BC_YUV422P)
1627         {
1628                 mpeg2enc_init_buffers();
1629                 mpeg2enc_set_w(file->asset->width);
1630                 mpeg2enc_set_h(file->asset->height);
1631                 mpeg2enc_set_rate(file->asset->frame_rate);
1632         }
1633 }
1634
1635 FileMPEGVideo::~FileMPEGVideo()
1636 {
1637         Thread::join();
1638 }
1639
1640 void FileMPEGVideo::run()
1641 {
1642         if(file->asset->vmpeg_cmodel == BC_YUV422P)
1643         {
1644                 printf("FileMPEGVideo::run ");
1645                 for(int i = 0; i < file->vcommand_line.total; i++)
1646                 printf("%s ", file->vcommand_line.values[i]);
1647                 printf("\n");
1648                 mpeg2enc(file->vcommand_line.total, file->vcommand_line.values);
1649         }
1650         else
1651         {
1652                 while(1)
1653                 {
1654 //printf("FileMPEGVideo::run %d\n", __LINE__);
1655                         file->next_frame_lock->lock("FileMPEGVideo::run");
1656 //printf("FileMPEGVideo::run %d\n", __LINE__);
1657                         if(file->mjpeg_eof)
1658                         {
1659                                 file->next_frame_done->unlock();
1660                                 break;
1661                         }
1662
1663
1664
1665 //printf("FileMPEGVideo::run %d\n", __LINE__);
1666 // YUV4 sequence header
1667                         if(!file->wrote_header)
1668                         {
1669                                 file->wrote_header = 1;
1670
1671                                 char interlace_string[BCTEXTLEN];
1672                                 if(!file->asset->vmpeg_progressive)
1673                                 {
1674                                         sprintf(interlace_string, file->asset->vmpeg_field_order ? "b" : "t");
1675                                 }
1676                                 else
1677                                 {
1678                                         sprintf(interlace_string, "p");
1679                                 }
1680                                 double aspect_ratio = file->asset->aspect_ratio >= 0 ?
1681                                         file->asset->aspect_ratio : 1.0;
1682 //printf("FileMPEGVideo::run %d\n", __LINE__);
1683                                 fprintf(file->mjpeg_out, "YUV4MPEG2 W%d H%d F%d:%d I%s A%d:%d C%s\n",
1684                                         file->asset->width, file->asset->height,
1685                                         (int)(file->asset->frame_rate * 1001),
1686                                         1001, interlace_string,
1687                                         (int)(aspect_ratio * 1000), 1000,
1688                                         "420mpeg2");
1689 //printf("FileMPEGVideo::run %d\n", __LINE__);
1690                         }
1691
1692 // YUV4 frame header
1693 //printf("FileMPEGVideo::run %d\n", __LINE__);
1694                         fprintf(file->mjpeg_out, "FRAME\n");
1695
1696 // YUV data
1697 //printf("FileMPEGVideo::run %d\n", __LINE__);
1698                         if(!fwrite(file->mjpeg_y, file->asset->width * file->asset->height, 1, file->mjpeg_out))
1699                                 file->mjpeg_error = 1;
1700 //printf("FileMPEGVideo::run %d\n", __LINE__);
1701                         if(!fwrite(file->mjpeg_u, file->asset->width * file->asset->height / 4, 1, file->mjpeg_out))
1702                                 file->mjpeg_error = 1;
1703 //printf("FileMPEGVideo::run %d\n", __LINE__);
1704                         if(!fwrite(file->mjpeg_v, file->asset->width * file->asset->height / 4, 1, file->mjpeg_out))
1705                                 file->mjpeg_error = 1;
1706 //printf("FileMPEGVideo::run %d\n", __LINE__);
1707                         fflush(file->mjpeg_out);
1708
1709 //printf("FileMPEGVideo::run %d\n", __LINE__);
1710                         file->next_frame_done->unlock();
1711 //printf("FileMPEGVideo::run %d\n", __LINE__);
1712                 }
1713                 pclose(file->mjpeg_out);
1714                 file->mjpeg_out = 0;
1715         }
1716 }
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729 MPEGConfigAudio::MPEGConfigAudio(BC_WindowBase *parent_window, Asset *asset)
1730  : BC_Window(_(PROGRAM_NAME ": Audio Compression"),
1731         parent_window->get_abs_cursor_x(1),
1732         parent_window->get_abs_cursor_y(1),
1733         310,
1734         120,
1735         -1,
1736         -1,
1737         0,
1738         0,
1739         1)
1740 {
1741         this->parent_window = parent_window;
1742         this->asset = asset;
1743 }
1744
1745 MPEGConfigAudio::~MPEGConfigAudio()
1746 {
1747 }
1748
1749 void MPEGConfigAudio::create_objects()
1750 {
1751         int x = 10, y = 10;
1752         int x1 = 150;
1753         MPEGLayer *layer;
1754
1755         lock_window("MPEGConfigAudio::create_objects");
1756         if(asset->format == FILE_MPEG)
1757         {
1758                 add_subwindow(new BC_Title(x, y, _("No options for MPEG transport stream.")));
1759                 unlock_window();
1760                 return;
1761         }
1762
1763
1764         add_tool(new BC_Title(x, y, _("Layer:")));
1765         add_tool(layer = new MPEGLayer(x1, y, this));
1766         layer->create_objects();
1767
1768         y += 30;
1769         add_tool(new BC_Title(x, y, _("Kbits per second:")));
1770         add_tool(bitrate = new MPEGABitrate(x1, y, this));
1771         bitrate->create_objects();
1772
1773
1774         add_subwindow(new BC_OKButton(this));
1775         show_window(1);
1776         unlock_window();
1777 }
1778
1779 int MPEGConfigAudio::close_event()
1780 {
1781         set_done(0);
1782         return 1;
1783 }
1784
1785
1786
1787
1788
1789
1790
1791 MPEGLayer::MPEGLayer(int x, int y, MPEGConfigAudio *gui)
1792  : BC_PopupMenu(x, y, 100, layer_to_string(gui->asset->ampeg_derivative))
1793 {
1794         this->gui = gui;
1795 }
1796
1797 void MPEGLayer::create_objects()
1798 {
1799         add_item(new BC_MenuItem(layer_to_string(2)));
1800         add_item(new BC_MenuItem(layer_to_string(3)));
1801 }
1802
1803 int MPEGLayer::handle_event()
1804 {
1805         gui->asset->ampeg_derivative = string_to_layer(get_text());
1806         gui->bitrate->set_layer(gui->asset->ampeg_derivative);
1807         return 1;
1808 };
1809
1810 int MPEGLayer::string_to_layer(char *string)
1811 {
1812         if(!strcasecmp(layer_to_string(2), string))
1813                 return 2;
1814         if(!strcasecmp(layer_to_string(3), string))
1815                 return 3;
1816
1817         return 2;
1818 }
1819
1820 char* MPEGLayer::layer_to_string(int layer)
1821 {
1822         switch(layer)
1823         {
1824                 case 2:
1825                         return _("II");
1826                         break;
1827
1828                 case 3:
1829                         return _("III");
1830                         break;
1831
1832                 default:
1833                         return _("II");
1834                         break;
1835         }
1836 }
1837
1838
1839
1840
1841
1842
1843
1844 MPEGABitrate::MPEGABitrate(int x, int y, MPEGConfigAudio *gui)
1845  : BC_PopupMenu(x,
1846         y,
1847         100,
1848         bitrate_to_string(gui->string, gui->asset->ampeg_bitrate))
1849 {
1850         this->gui = gui;
1851 }
1852
1853 void MPEGABitrate::create_objects()
1854 {
1855         set_layer(gui->asset->ampeg_derivative);
1856 }
1857
1858 void MPEGABitrate::set_layer(int layer)
1859 {
1860         while(total_items()) del_item(0);
1861
1862         if(layer == 2)
1863         {
1864                 add_item(new BC_MenuItem("160"));
1865                 add_item(new BC_MenuItem("192"));
1866                 add_item(new BC_MenuItem("224"));
1867                 add_item(new BC_MenuItem("256"));
1868                 add_item(new BC_MenuItem("320"));
1869                 add_item(new BC_MenuItem("384"));
1870         }
1871         else
1872         {
1873                 add_item(new BC_MenuItem("8"));
1874                 add_item(new BC_MenuItem("16"));
1875                 add_item(new BC_MenuItem("24"));
1876                 add_item(new BC_MenuItem("32"));
1877                 add_item(new BC_MenuItem("40"));
1878                 add_item(new BC_MenuItem("48"));
1879                 add_item(new BC_MenuItem("56"));
1880                 add_item(new BC_MenuItem("64"));
1881                 add_item(new BC_MenuItem("80"));
1882                 add_item(new BC_MenuItem("96"));
1883                 add_item(new BC_MenuItem("112"));
1884                 add_item(new BC_MenuItem("128"));
1885                 add_item(new BC_MenuItem("144"));
1886                 add_item(new BC_MenuItem("160"));
1887                 add_item(new BC_MenuItem("192"));
1888                 add_item(new BC_MenuItem("224"));
1889                 add_item(new BC_MenuItem("256"));
1890                 add_item(new BC_MenuItem("320"));
1891         }
1892 }
1893
1894 int MPEGABitrate::handle_event()
1895 {
1896         gui->asset->ampeg_bitrate = string_to_bitrate(get_text());
1897         return 1;
1898 };
1899
1900 int MPEGABitrate::string_to_bitrate(char *string)
1901 {
1902         return atol(string);
1903 }
1904
1905
1906 char* MPEGABitrate::bitrate_to_string(char *string, int bitrate)
1907 {
1908         sprintf(string, "%d", bitrate);
1909         return string;
1910 }
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920 MPEGConfigVideo::MPEGConfigVideo(BC_WindowBase *parent_window,
1921         Asset *asset)
1922  : BC_Window(_(PROGRAM_NAME ": Video Compression"),
1923         parent_window->get_abs_cursor_x(1),
1924         parent_window->get_abs_cursor_y(1),
1925         500,
1926         400,
1927         -1,
1928         -1,
1929         0,
1930         0,
1931         1)
1932 {
1933         this->parent_window = parent_window;
1934         this->asset = asset;
1935         reset_cmodel();
1936 }
1937
1938 MPEGConfigVideo::~MPEGConfigVideo()
1939 {
1940 }
1941
1942 void MPEGConfigVideo::create_objects()
1943 {
1944         int x = 10, y = 10;
1945         int x1 = x + 150;
1946         //int x2 = x + 300;
1947
1948         lock_window("MPEGConfigVideo::create_objects");
1949         if(asset->format == FILE_MPEG)
1950         {
1951                 add_subwindow(new BC_Title(x, y, _("No options for MPEG transport stream.")));
1952                 unlock_window();
1953                 return;
1954         }
1955
1956         add_subwindow(new BC_Title(x, y, _("Color model:")));
1957         add_subwindow(cmodel = new MPEGColorModel(x1, y, this));
1958         cmodel->create_objects();
1959         y += 30;
1960
1961         update_cmodel_objs();
1962
1963         add_subwindow(new BC_OKButton(this));
1964         show_window(1);
1965         unlock_window();
1966 }
1967
1968 int MPEGConfigVideo::close_event()
1969 {
1970         set_done(0);
1971         return 1;
1972 }
1973
1974
1975 void MPEGConfigVideo::delete_cmodel_objs()
1976 {
1977         delete preset;
1978         delete derivative;
1979         delete bitrate;
1980         delete fixed_bitrate;
1981         delete quant;
1982         delete fixed_quant;
1983         delete iframe_distance;
1984         delete pframe_distance;
1985         delete top_field_first;
1986         delete progressive;
1987         delete denoise;
1988         delete seq_codes;
1989         titles.remove_all_objects();
1990         reset_cmodel();
1991 }
1992
1993 void MPEGConfigVideo::reset_cmodel()
1994 {
1995         preset = 0;
1996         derivative = 0;
1997         bitrate = 0;
1998         fixed_bitrate = 0;
1999         quant = 0;
2000         fixed_quant = 0;
2001         iframe_distance = 0;
2002         pframe_distance = 0;
2003         top_field_first = 0;
2004         progressive = 0;
2005         denoise = 0;
2006         seq_codes = 0;
2007 }
2008
2009 void MPEGConfigVideo::update_cmodel_objs()
2010 {
2011         BC_Title *title;
2012         int x = 10;
2013         int y = 40;
2014         int x1 = x + 150;
2015         int x2 = x + 280;
2016
2017         delete_cmodel_objs();
2018
2019         if(asset->vmpeg_cmodel == BC_YUV420P)
2020         {
2021                 add_subwindow(title = new BC_Title(x, y + 5, _("Format Preset:")));
2022                 titles.append(title);
2023                 add_subwindow(preset = new MPEGPreset(x1, y, this));
2024                 preset->create_objects();
2025                 y += 30;
2026         }
2027
2028         add_subwindow(title = new BC_Title(x, y + 5, _("Derivative:")));
2029         titles.append(title);
2030         add_subwindow(derivative = new MPEGDerivative(x1, y, this));
2031         derivative->create_objects();
2032         y += 30;
2033
2034         add_subwindow(title = new BC_Title(x, y + 5, _("Bitrate:")));
2035         titles.append(title);
2036         add_subwindow(bitrate = new MPEGBitrate(x1, y, this));
2037         add_subwindow(fixed_bitrate = new MPEGFixedBitrate(x2, y, this));
2038         y += 30;
2039
2040         add_subwindow(title = new BC_Title(x, y, _("Quantization:")));
2041         titles.append(title);
2042         quant = new MPEGQuant(x1, y, this);
2043         quant->create_objects();
2044         add_subwindow(fixed_quant = new MPEGFixedQuant(x2, y, this));
2045         y += 30;
2046
2047         add_subwindow(title = new BC_Title(x, y, _("I frame distance:")));
2048         titles.append(title);
2049         iframe_distance = new MPEGIFrameDistance(x1, y, this);
2050         iframe_distance->create_objects();
2051         y += 30;
2052
2053         if(asset->vmpeg_cmodel == BC_YUV420P)
2054         {
2055                 add_subwindow(title = new BC_Title(x, y, _("P frame distance:")));
2056                 titles.append(title);
2057                 pframe_distance = new MPEGPFrameDistance(x1, y, this);
2058                 pframe_distance->create_objects();
2059                 y += 30;
2060
2061                 add_subwindow(top_field_first = new BC_CheckBox(x, y, &asset->vmpeg_field_order, _("Bottom field first")));
2062                 y += 30;
2063         }
2064
2065         add_subwindow(progressive = new BC_CheckBox(x, y, &asset->vmpeg_progressive, _("Progressive frames")));
2066         y += 30;
2067         add_subwindow(denoise = new BC_CheckBox(x, y, &asset->vmpeg_denoise, _("Denoise")));
2068         y += 30;
2069         add_subwindow(seq_codes = new BC_CheckBox(x, y, &asset->vmpeg_seq_codes, _("Sequence start codes in every GOP")));
2070
2071 }
2072
2073
2074 MPEGDerivative::MPEGDerivative(int x, int y, MPEGConfigVideo *gui)
2075  : BC_PopupMenu(x, y, 150, derivative_to_string(gui->asset->vmpeg_derivative))
2076 {
2077         this->gui = gui;
2078 }
2079
2080 void MPEGDerivative::create_objects()
2081 {
2082         add_item(new BC_MenuItem(derivative_to_string(1)));
2083         add_item(new BC_MenuItem(derivative_to_string(2)));
2084 }
2085
2086 int MPEGDerivative::handle_event()
2087 {
2088         gui->asset->vmpeg_derivative = string_to_derivative(get_text());
2089         return 1;
2090 };
2091
2092 int MPEGDerivative::string_to_derivative(char *string)
2093 {
2094         if( !strcasecmp(derivative_to_string(1), string) ) return 1;
2095         if( !strcasecmp(derivative_to_string(2), string) ) return 2;
2096         return 1;
2097 }
2098
2099 char* MPEGDerivative::derivative_to_string(int derivative)
2100 {
2101         switch(derivative) {
2102         case 1: return _("MPEG-1");
2103         case 2: return _("MPEG-2");
2104         }
2105         return _("MPEG-1");
2106 }
2107
2108
2109 MPEGPreset::MPEGPreset(int x, int y, MPEGConfigVideo *gui)
2110  : BC_PopupMenu(x, y, 200, value_to_string(gui->asset->vmpeg_preset))
2111 {
2112         this->gui = gui;
2113 }
2114
2115 void MPEGPreset::create_objects()
2116 {
2117         for(int i = 0; i < 14; i++) {
2118                 add_item(new BC_MenuItem(value_to_string(i)));
2119         }
2120 }
2121
2122 int MPEGPreset::handle_event()
2123 {
2124         gui->asset->vmpeg_preset = string_to_value(get_text());
2125         return 1;
2126 }
2127
2128 int MPEGPreset::string_to_value(char *string)
2129 {
2130         for(int i = 0; i < 14; i++) {
2131                 if(!strcasecmp(value_to_string(i), string))
2132                         return i;
2133         }
2134         return 0;
2135 }
2136
2137 char* MPEGPreset::value_to_string(int derivative)
2138 {
2139         switch( derivative ) {
2140         case 0: return _("Generic MPEG-1"); break;
2141         case 1: return _("standard VCD"); break;
2142         case 2: return _("user VCD"); break;
2143         case 3: return _("Generic MPEG-2"); break;
2144         case 4: return _("standard SVCD"); break;
2145         case 5: return _("user SVCD"); break;
2146         case 6: return _("VCD Still sequence"); break;
2147         case 7: return _("SVCD Still sequence"); break;
2148         case 8: return _("DVD NAV"); break;
2149         case 9: return _("DVD"); break;
2150         case 10: return _("ATSC 480i"); break;
2151         case 11: return _("ATSC 480p"); break;
2152         case 12: return _("ATSC 720p"); break;
2153         case 13: return _("ATSC 1080i"); break;
2154         }
2155         return _("Generic MPEG-1");
2156 }
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168 MPEGBitrate::MPEGBitrate(int x, int y, MPEGConfigVideo *gui)
2169  : BC_TextBox(x, y, 100, 1, gui->asset->vmpeg_bitrate)
2170 {
2171         this->gui = gui;
2172 }
2173
2174
2175 int MPEGBitrate::handle_event()
2176 {
2177         gui->asset->vmpeg_bitrate = atol(get_text());
2178         return 1;
2179 };
2180
2181
2182
2183
2184
2185 MPEGQuant::MPEGQuant(int x, int y, MPEGConfigVideo *gui)
2186  : BC_TumbleTextBox(gui,
2187         (int64_t)gui->asset->vmpeg_quantization,
2188         (int64_t)1,
2189         (int64_t)100,
2190         x,
2191         y,
2192         100)
2193 {
2194         this->gui = gui;
2195 }
2196
2197 int MPEGQuant::handle_event()
2198 {
2199         gui->asset->vmpeg_quantization = atol(get_text());
2200         return 1;
2201 };
2202
2203 MPEGFixedBitrate::MPEGFixedBitrate(int x, int y, MPEGConfigVideo *gui)
2204  : BC_Radial(x, y, gui->asset->vmpeg_fix_bitrate, _("Fixed bitrate"))
2205 {
2206         this->gui = gui;
2207 }
2208
2209 int MPEGFixedBitrate::handle_event()
2210 {
2211         update(1);
2212         gui->asset->vmpeg_fix_bitrate = 1;
2213         gui->fixed_quant->update(0);
2214         return 1;
2215 };
2216
2217 MPEGFixedQuant::MPEGFixedQuant(int x, int y, MPEGConfigVideo *gui)
2218  : BC_Radial(x, y, !gui->asset->vmpeg_fix_bitrate, _("Fixed quantization"))
2219 {
2220         this->gui = gui;
2221 }
2222
2223 int MPEGFixedQuant::handle_event()
2224 {
2225         update(1);
2226         gui->asset->vmpeg_fix_bitrate = 0;
2227         gui->fixed_bitrate->update(0);
2228         return 1;
2229 };
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239 MPEGIFrameDistance::MPEGIFrameDistance(int x, int y, MPEGConfigVideo *gui)
2240  : BC_TumbleTextBox(gui,
2241         (int64_t)gui->asset->vmpeg_iframe_distance,
2242         (int64_t)1,
2243         (int64_t)100,
2244         x,
2245         y,
2246         50)
2247 {
2248         this->gui = gui;
2249 }
2250
2251 int MPEGIFrameDistance::handle_event()
2252 {
2253         gui->asset->vmpeg_iframe_distance = atoi(get_text());
2254         return 1;
2255 }
2256
2257
2258
2259
2260
2261
2262
2263 MPEGPFrameDistance::MPEGPFrameDistance(int x, int y, MPEGConfigVideo *gui)
2264  : BC_TumbleTextBox(gui,
2265         (int64_t)gui->asset->vmpeg_pframe_distance,
2266         (int64_t)0,
2267         (int64_t)2,
2268         x,
2269         y,
2270         50)
2271 {
2272         this->gui = gui;
2273 }
2274
2275 int MPEGPFrameDistance::handle_event()
2276 {
2277         gui->asset->vmpeg_pframe_distance = atoi(get_text());
2278         return 1;
2279 }
2280
2281
2282
2283
2284
2285
2286
2287
2288 MPEGColorModel::MPEGColorModel(int x, int y, MPEGConfigVideo *gui)
2289  : BC_PopupMenu(x, y, 150, cmodel_to_string(gui->asset->vmpeg_cmodel))
2290 {
2291         this->gui = gui;
2292 }
2293
2294 void MPEGColorModel::create_objects()
2295 {
2296         add_item(new BC_MenuItem(cmodel_to_string(BC_YUV420P)));
2297         add_item(new BC_MenuItem(cmodel_to_string(BC_YUV422P)));
2298 }
2299
2300 int MPEGColorModel::handle_event()
2301 {
2302         gui->asset->vmpeg_cmodel = string_to_cmodel(get_text());
2303         gui->update_cmodel_objs();
2304         gui->show_window(1);
2305         return 1;
2306 };
2307
2308 int MPEGColorModel::string_to_cmodel(char *string)
2309 {
2310         if(!strcasecmp(cmodel_to_string(BC_YUV420P), string))
2311                 return BC_YUV420P;
2312         if(!strcasecmp(cmodel_to_string(BC_YUV422P), string))
2313                 return BC_YUV422P;
2314         return BC_YUV420P;
2315 }
2316
2317 char* MPEGColorModel::cmodel_to_string(int cmodel)
2318 {
2319         switch(cmodel)
2320         {
2321                 case BC_YUV420P: return _("YUV 4:2:0");
2322                 case BC_YUV422P: return _("YUV 4:2:2");
2323                 default: return _("YUV 4:2:0");
2324         }
2325 }
2326
2327
2328
2329
2330
2331