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