encode.pl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use IPC::Open3;
  6. use File::Basename;
  7. # Parameters
  8. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--x264opts', 'b-adapt=2:rc-lookahead=50');
  9. my $FORMAT = 'mp4';
  10. my $QUALITY = 20;
  11. my $HD_QUALITY = 20;
  12. my $HD_WIDTH = 1350;
  13. my $MIN_VIDEO_WIDTH = 100;
  14. my $MAX_CROP_DIFF = .1;
  15. my $MAX_DURA_DIFF = 5;
  16. my $HAVE_DTS = 0;
  17. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  18. my $DEBUG = 0;
  19. # Runtime debug mode
  20. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  21. $DEBUG = 1;
  22. }
  23. # Command-line parameters
  24. my ($in_file, $out_file, $title) = @ARGV;
  25. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  26. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  27. }
  28. # Scan for title/track info
  29. my %titles = &scan($in_file);
  30. # Allow external subtitles for single-title files
  31. if (scalar(keys(%titles)) == 1) {
  32. my $srt_file = $in_file;
  33. $srt_file =~ s/\.\w{2,3}$/.srt/;
  34. if (-r $srt_file) {
  35. if ($DEBUG) {
  36. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  37. }
  38. push(@video_params, '--srt-file', $srt_file);
  39. }
  40. }
  41. # Allow encoding of a specific title
  42. if ($title) {
  43. if ($title =~ /^\d+$/ && $title > 0) {
  44. if (!defined($titles{$title})) {
  45. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  46. }
  47. my $selected_title = $titles{$title};
  48. %titles = ();
  49. $titles{$title} = $selected_title;
  50. } elsif ($title =~ /main/i) {
  51. my $max_title = 0;
  52. my $max_duration = 0;
  53. foreach my $title (keys(%titles)) {
  54. if (!$titles{$title}{'duration'}) {
  55. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  56. next;
  57. }
  58. my $new_max = 0;
  59. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  60. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  61. $new_max = 1;
  62. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  63. $new_max = 1;
  64. }
  65. } elsif ($titles{$title}{'duration'} > $max_duration) {
  66. $new_max = 1;
  67. }
  68. if ($new_max) {
  69. $max_duration = $titles{$title}{'duration'};
  70. $max_title = $title;
  71. }
  72. }
  73. my $selected_title = $titles{$max_title};
  74. %titles = ();
  75. $titles{$max_title} = $selected_title;
  76. }
  77. }
  78. # Ensure we have an output file name
  79. # Allow forced use of MKV wrapper if the output file name is provided and ends in .MKV
  80. if (!defined($out_file) || length($out_file) < 1) {
  81. $out_file = $in_file;
  82. } else {
  83. my ($force_format) = $out_file =~ /\.(\w{2,3})$/;
  84. if (lc($force_format) eq 'mkv') {
  85. $FORMAT = 'mkv';
  86. }
  87. }
  88. # Encode each title
  89. foreach my $title (keys(%titles)) {
  90. if ($DEBUG) {
  91. print STDERR 'Setting options for title: ' . $title . "\n";
  92. }
  93. # Parse the title's audio and subtitle tracks
  94. my $scan = $titles{$title};
  95. my @audio = &audioOptions($scan);
  96. my @subs = &subOptions($scan);
  97. # Skip tracks that have no video
  98. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  99. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  100. next;
  101. }
  102. # Skip tracks that have no audio
  103. if (scalar(@{ $scan->{'audio'} }) < 1) {
  104. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  105. next;
  106. }
  107. # Reduce the quality if the image size is particularly large
  108. my $title_quality = $QUALITY;
  109. if ($scan->{'size'}[0] > $HD_WIDTH) {
  110. $title_quality = $HD_QUALITY;
  111. }
  112. # Override unlikely autocrop values
  113. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  114. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  115. {
  116. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  117. my @crop = (0, 0, 0, 0);
  118. $scan->{'crop'} = \@crop;
  119. }
  120. # Require the MKV format whenever we have DTS audio
  121. my $title_format = $FORMAT;
  122. if ($HAVE_DTS) {
  123. $title_format = 'mkv';
  124. }
  125. # Select a file name extension that matches the format
  126. my $title_out_file = $out_file;
  127. $title_out_file =~ s/\.(?:\w{2,3}|dvdmedia)$//i;
  128. if ($title_format eq 'mkv') {
  129. $title_out_file .= '.mkv';
  130. } else {
  131. $title_out_file .= '.m4v';
  132. }
  133. # Force the title number into the output file name if there are multiple titles to be encoded
  134. if (scalar(keys(%titles)) > 1) {
  135. my $title_text = sprintf('%02d', $title);
  136. $title_out_file =~ s/(\.\w{2,3})$/\-${title_text}${1}/;
  137. }
  138. # Sanity check
  139. if (uc($title_out_file) eq uc($in_file)) {
  140. $title_out_file =~ s/(\.\w{2,3})$/-recode${1}/;
  141. }
  142. if (-e $title_out_file) {
  143. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  144. next;
  145. }
  146. # Build the arugment list
  147. my @args = ($HB_EXEC);
  148. push(@args, '--title', $title);
  149. push(@args, '--input', $in_file);
  150. push(@args, '--output', $title_out_file);
  151. push(@args, '--format', $title_format);
  152. push(@args, '--quality', $title_quality);
  153. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  154. push(@args, @video_params);
  155. push(@args, @audio);
  156. push(@args, @subs);
  157. # Run it
  158. if ($DEBUG) {
  159. print STDERR join(' ', @args) . "\n";
  160. }
  161. my $child_out = '';
  162. my $child_in = '';
  163. my $pid = open3($child_in, $child_out, $child_out, @args);
  164. close($child_in);
  165. while (<$child_out>) {
  166. if ($DEBUG) {
  167. print STDERR $_;
  168. }
  169. }
  170. waitpid($pid, 0);
  171. close($child_out);
  172. # Provide the new file name if requested
  173. if ($ENV{'RECODE_OUTFILE'}) {
  174. print $title_out_file;
  175. }
  176. }
  177. # Cleanup
  178. exit(0);
  179. sub subOptions($) {
  180. my ($scan) = @_;
  181. # Find English subtitles
  182. my @keep = ();
  183. foreach my $track (@{ $scan->{'subtitle'} }) {
  184. if (my ($lang) = $track->{'description'} =~ /\b(English|Unknown|Closed\s+Captions)\b/i) {
  185. push(@keep, $track->{'index'});
  186. if ($DEBUG) {
  187. print STDERR 'Found ' . $lang . ' subtitle in track ' . $track->{'index'} . "\n";
  188. }
  189. }
  190. }
  191. # Send back the argument string (if any)
  192. if (scalar(@keep) < 1) {
  193. return '';
  194. }
  195. return ('--subtitle', join(',', @keep));
  196. }
  197. sub audioOptions($) {
  198. my ($scan) = @_;
  199. # Type the audio tracks
  200. my $oat = undef();
  201. my $aac = undef();
  202. my $mpg = undef();
  203. my @channels = ();
  204. my @pcm = ();
  205. my @ac3 = ();
  206. my @dts = ();
  207. foreach my $track (@{ $scan->{'audio'} }) {
  208. my ($language, $codec, $chans, $iso) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(([^\)]+)\))?/;
  209. if (!defined($chans)) {
  210. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  211. # Temporarily exit on parsing errors -- at least until we're sure about this new parser
  212. exit(1);
  213. next;
  214. }
  215. if ($chans =~ /(\d+\.\d+)\s+ch/i) {
  216. $chans = $1;
  217. } elsif ($chans =~ /Dolby\s+Surround/i) {
  218. $chans = 3.1;
  219. }
  220. if ($DEBUG) {
  221. print STDERR 'Found audio track: codec => ' . $codec . ', channels => ' . $chans . ', language => ' . $language . ', ISO => ' . $iso . "\n";
  222. }
  223. # Record the number of channels in each track
  224. $channels[ $track->{'index'} ] = $chans;
  225. if ($codec =~ /AC3/i) {
  226. if ($language =~ /\b(Chinese|Espanol|Francais|Japanese|Korean|Portugues|Thai)\b/i) {
  227. if ($DEBUG) {
  228. print STDERR 'Skipping AC3 in track ' . $track->{'index'} . ' due to language: ' . $language . "\n";
  229. }
  230. next;
  231. }
  232. push(@ac3, $track->{'index'});
  233. if ($DEBUG) {
  234. print STDERR 'Found AC3 in track ' . $track->{'index'} . "\n";
  235. }
  236. } elsif ($codec =~ /AAC/i) {
  237. $aac = $track->{'index'};
  238. if ($DEBUG) {
  239. print STDERR 'Found AAC in track ' . $track->{'index'} . "\n";
  240. }
  241. } elsif ($codec =~ /MP3/i || $codec =~ /MPEG/i) {
  242. $mpg = $track->{'index'};
  243. if ($DEBUG) {
  244. print STDERR 'Found MPEG/MP3 in track ' . $track->{'index'} . "\n";
  245. }
  246. } elsif ($codec =~ /PCM_[SF]\d+/i) {
  247. push(@pcm, $track->{'index'});
  248. if ($DEBUG) {
  249. print STDERR 'Found PCM in track ' . $track->{'index'} . "\n";
  250. }
  251. } elsif ($codec =~ /DTS/i) {
  252. if ($codec =~ /DTS\-MA/i) {
  253. if ($DEBUG) {
  254. print STDERR 'Skipping DTS-MA in track ' . $track->{'index'} . " due to poor DTS-MA support in HandBrake\n";
  255. }
  256. next;
  257. }
  258. push(@dts, $track->{'index'});
  259. if ($DEBUG) {
  260. print STDERR 'Found DTS in track ' . $track->{'index'} . "\n";
  261. }
  262. } elsif ($codec =~ /MP2/i) {
  263. $oat = $track->{'index'};
  264. if ($DEBUG) {
  265. print STDERR 'Found other audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  266. }
  267. }
  268. }
  269. # We should sort the different codecs by number of channels
  270. # But so far I've had good luck just taking the first track with the best codec
  271. # Pick a stereo/mixdown plan based on the available track types
  272. my $stereo = undef();
  273. my $mixdown = undef();
  274. if (scalar(@dts) > 0) {
  275. $mixdown = $dts[0];
  276. } elsif (scalar(@ac3) > 0 || scalar(@pcm) > 0) {
  277. if (scalar(@pcm) < 1) {
  278. $mixdown = $ac3[0];
  279. } elsif (scalar(@ac3) < 1) {
  280. $mixdown = $pcm[0];
  281. } elsif ($channels[ $pcm[0] ] >= $channels[ $ac3[0] ]) {
  282. $mixdown = $pcm[0];
  283. }
  284. } elsif (defined($aac) && $aac > 0) {
  285. $stereo = $aac;
  286. } elsif (defined($mpg) && $mpg > 0) {
  287. $stereo = $mpg;
  288. } elsif (defined($oat) && $oat > 0) {
  289. $stereo = $oat;
  290. }
  291. # Sanity check
  292. if (!(defined($mixdown) && $mixdown > 0) && !(defined($stereo) && $stereo > 0)) {
  293. print STDERR basename($0) . ": No usable audio tracks in title\n";
  294. return ();
  295. }
  296. # Stereo/mixdown track first
  297. my @audio_tracks = ();
  298. if (defined($mixdown) && $mixdown > 0) {
  299. if ($DEBUG) {
  300. print STDERR 'Mixing down track (track #' . $mixdown . ") to stereo\n";
  301. }
  302. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  303. push(@audio_tracks, \%track);
  304. } elsif (defined($stereo) && $stereo > 0) {
  305. if ($DEBUG) {
  306. print STDERR 'Using existing stereo track: ' . $stereo . "\n";
  307. }
  308. my %track = ('index' => $stereo, 'encoder' => 'ca_aac');
  309. push(@audio_tracks, \%track);
  310. }
  311. # Always keep DTS if we found it
  312. $HAVE_DTS = 0;
  313. if (scalar(@dts) > 0) {
  314. $HAVE_DTS = 1;
  315. foreach my $dts_track (@dts) {
  316. if ($DEBUG) {
  317. print STDERR 'Keeping DTS passthru track: ' . $dts_track . "\n";
  318. }
  319. my %track = ('index' => $dts_track, 'encoder' => 'copy:dts');
  320. push(@audio_tracks, \%track);
  321. }
  322. }
  323. # Always keep PCM if we found it (but recode to AAC)
  324. foreach my $pcm_track (@pcm) {
  325. if ($DEBUG) {
  326. print STDERR 'Keeping PCM track as AAC: ' . $pcm_track . "\n";
  327. }
  328. my %track = ('index' => $pcm_track, 'encoder' => 'ca_aac');
  329. push(@audio_tracks, \%track);
  330. }
  331. # Always keep AC3 if we found it (and liked it)
  332. foreach my $ac3_track (@ac3) {
  333. if ($DEBUG) {
  334. print STDERR 'Keeping AC3 passthru track: ' . $ac3_track . "\n";
  335. }
  336. my %track = ('index' => $ac3_track, 'encoder' => 'copy:ac3');
  337. push(@audio_tracks, \%track);
  338. }
  339. # Consolidate from the hashes
  340. my @tracks = ();
  341. my @encoders = ();
  342. foreach my $track (@audio_tracks) {
  343. push(@tracks, $track->{'index'});
  344. push(@encoders, $track->{'encoder'});
  345. }
  346. # Send back the argument strings
  347. return ('--audio', join(',', @tracks), '--aencoder', join(',', @encoders));
  348. }
  349. sub scan($) {
  350. my ($in_file) = @_;
  351. # Fork to scan the file
  352. my $child_out = '';
  353. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--title', '0', '--input', $in_file);
  354. # Loop through the output
  355. my $scan;
  356. my %titles = ();
  357. my $inTitle = 0;
  358. my $zone = '';
  359. my $dca_stream = -1;
  360. my %dca_lossless = ();
  361. while (<$child_out>) {
  362. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  363. if ($DEBUG) {
  364. print STDERR 'Found ' . $1 . " titles in source\n";
  365. }
  366. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  367. my $stream = $1;
  368. my $desc = $2;
  369. $dca_stream = -1;
  370. if ($desc =~ /Audio\:\s+dca/) {
  371. $dca_stream = $stream;
  372. }
  373. } elsif ($dca_stream >= 0 && m/^\s+title\s*\:\s+(.*)/) {
  374. if ($1 =~ /Lossless/i) {
  375. $dca_lossless{$dca_stream} = 1;
  376. if ($DEBUG) {
  377. print STDERR 'Found DTS Lossless audio in stream: ' . $dca_stream . "\n";
  378. }
  379. }
  380. $dca_stream = -1;
  381. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  382. # Save the current title (if any)
  383. if ($inTitle) {
  384. $titles{$inTitle} = $scan;
  385. }
  386. # Grab the new title number
  387. $inTitle = $1;
  388. # Init the data collectors
  389. my @audio = ();
  390. my @crop = ();
  391. my @subtitle = ();
  392. my @size = ();
  393. my %tmp = (
  394. 'audio' => \@audio,
  395. 'crop' => \@crop,
  396. 'subtitle' => \@subtitle,
  397. 'size' => \@size,
  398. 'duration' => 0,
  399. 'aspect' => 0
  400. );
  401. $scan = \%tmp;
  402. if ($DEBUG) {
  403. print STDERR 'Found data for title ' . $1 . "\n";
  404. }
  405. } elsif ($inTitle) {
  406. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  407. push(@{ $scan->{'size'} }, $1, $2);
  408. if ($DEBUG) {
  409. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  410. }
  411. if (/\s+display aspect\: (\d*\.\d+)/) {
  412. $scan->{'aspect'} = $1;
  413. if ($DEBUG) {
  414. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  415. }
  416. }
  417. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  418. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  419. if ($DEBUG) {
  420. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  421. }
  422. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  423. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  424. if ($DEBUG) {
  425. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  426. }
  427. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  428. $zone = 'audio';
  429. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  430. my %track = ('index' => $1, 'description' => $2);
  431. if ($dca_lossless{ $track{'index'} }) {
  432. $track{'description'} =~ s/\(DTS\)/\(DTS-MA\)/;
  433. }
  434. push(@{ $scan->{'audio'} }, \%track);
  435. if ($DEBUG) {
  436. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  437. }
  438. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  439. $zone = 'subtitle';
  440. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  441. my %track = ('index' => $1, 'description' => $2);
  442. push(@{ $scan->{'subtitle'} }, \%track);
  443. if ($DEBUG) {
  444. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  445. }
  446. }
  447. }
  448. }
  449. # Save the last title (if any)
  450. if ($inTitle) {
  451. $titles{$inTitle} = $scan;
  452. }
  453. # Cleanup the scan process
  454. waitpid($pid, 0);
  455. close($child_out);
  456. # Sanity check
  457. if (scalar(keys(%titles)) < 1) {
  458. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  459. }
  460. # Return
  461. return %titles;
  462. }