encode.pl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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', '--encopts', 'b-adapt=2:rc-lookahead=50', '--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ca_aac', '--mixdown', 'dpl2', '--ab', '192');
  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 @CODEC_ORDER = ('DTS-HD', 'DTS', 'PCM', 'AC3', 'AAC', 'OTHER');
  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. # Select a file name extension that matches the format
  121. my $title_out_file = $out_file;
  122. $title_out_file =~ s/\.(?:\w{2,3}|dvdmedia)$//i;
  123. if ($FORMAT eq 'mkv') {
  124. $title_out_file .= '.mkv';
  125. } else {
  126. $title_out_file .= '.m4v';
  127. }
  128. # Force the title number into the output file name if there are multiple titles to be encoded
  129. if (scalar(keys(%titles)) > 1) {
  130. my $title_text = sprintf('%02d', $title);
  131. $title_out_file =~ s/(\.\w{2,3})$/\-${title_text}${1}/;
  132. }
  133. # Sanity check
  134. if (uc($title_out_file) eq uc($in_file)) {
  135. $title_out_file =~ s/(\.\w{2,3})$/-recode${1}/;
  136. }
  137. if (-e $title_out_file) {
  138. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  139. next;
  140. }
  141. # Build the arugment list
  142. my @args = ($HB_EXEC);
  143. push(@args, '--title', $title);
  144. push(@args, '--input', $in_file);
  145. push(@args, '--output', $title_out_file);
  146. push(@args, '--format', $FORMAT);
  147. push(@args, '--quality', $title_quality);
  148. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  149. push(@args, @video_params);
  150. push(@args, @audio);
  151. push(@args, @subs);
  152. # Run it
  153. if ($DEBUG) {
  154. print STDERR join(' ', @args) . "\n";
  155. }
  156. my $child_out = '';
  157. my $child_in = '';
  158. my $pid = open3($child_in, $child_out, $child_out, @args);
  159. close($child_in);
  160. while (<$child_out>) {
  161. if ($DEBUG) {
  162. print STDERR $_;
  163. }
  164. }
  165. waitpid($pid, 0);
  166. close($child_out);
  167. # Provide the new file name if requested
  168. if ($ENV{'RECODE_OUTFILE'}) {
  169. print $title_out_file;
  170. }
  171. }
  172. # Cleanup
  173. exit(0);
  174. sub subOptions($) {
  175. my ($scan) = @_;
  176. # Find English subtitles
  177. my @keep = ();
  178. foreach my $track (@{ $scan->{'subtitle'} }) {
  179. if (my ($lang) = $track->{'description'} =~ /\b(English|Unknown|Closed\s+Captions)\b/i) {
  180. push(@keep, $track->{'index'});
  181. if ($DEBUG) {
  182. print STDERR 'Found ' . $lang . ' subtitle in track ' . $track->{'index'} . "\n";
  183. }
  184. }
  185. }
  186. # Send back the argument string (if any)
  187. if (scalar(@keep) < 1) {
  188. return '';
  189. }
  190. return ('--subtitle', join(',', @keep));
  191. }
  192. sub audioOptions($) {
  193. my ($scan) = @_;
  194. # Type the audio tracks
  195. my %tracks = ();
  196. foreach my $track (@{ $scan->{'audio'} }) {
  197. my ($language, $codec, $note, $channels, $iso) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?/;
  198. if (!defined($channels)) {
  199. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  200. # Temporarily exit on parsing errors -- at least until we're sure about this new parser
  201. #next;
  202. exit(1);
  203. }
  204. # Decode the channels string to a number
  205. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  206. $channels = $1;
  207. } elsif ($channels =~ /Dolby\s+Surround/i) {
  208. $channels = 3.1;
  209. }
  210. # Standardize the codec
  211. foreach my $code (@CODEC_ORDER) {
  212. my $metacode = quotemeta($code);
  213. if ($codec =~ /${metacode}/i) {
  214. $codec = $code;
  215. last;
  216. } elsif ($code eq 'OTHER') {
  217. if (!($codec =~ /MP3/i || $codec =~ /MPEG/i)) {
  218. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  219. }
  220. $codec = $code;
  221. }
  222. }
  223. # Push all parsed data into the array
  224. my %data = ('language' => $language, 'codec' => $codec, 'channels' => $channels, 'iso' => $iso, 'note' => $note);
  225. $tracks{ $track->{'index'} } = \%data;
  226. # Print what we found
  227. if ($DEBUG) {
  228. print STDERR 'Found audio track: ';
  229. my $first = 1;
  230. foreach my $key (keys(%data)) {
  231. if ($data{$key}) {
  232. if ($first) {
  233. $first = 0;
  234. } else {
  235. print STDERR ', ';
  236. }
  237. print STDERR $key . ' => ' . $data{$key};
  238. }
  239. }
  240. print STDERR "\n";
  241. }
  242. }
  243. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  244. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  245. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  246. my $mixdown = undef();
  247. my %bestByCodec = ();
  248. my $bestCodec = undef();
  249. my $mostChannels = 0;
  250. foreach my $codec (@CODEC_ORDER) {
  251. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  252. if (defined($bestByCodec{$codec}) && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'})) {
  253. $bestCodec = $codec;
  254. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  255. }
  256. }
  257. foreach my $codec (@CODEC_ORDER) {
  258. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  259. $mixdown = $bestByCodec{$codec};
  260. last;
  261. }
  262. }
  263. # Sanity check
  264. if (!defined($mixdown) || $mixdown < 1) {
  265. print STDERR basename($0) . ": No usable audio tracks in title\n";
  266. return;
  267. }
  268. # Mixdown track first
  269. my @audio_tracks = ();
  270. if (defined($mixdown) && $mixdown > 0) {
  271. if ($DEBUG) {
  272. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  273. if ($tracks{$mixdown}->{'channels'} > 2) {
  274. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  275. }
  276. }
  277. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  278. push(@audio_tracks, \%track);
  279. }
  280. # Passthru DTS-MA, DTS, AC3, and AAC
  281. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  282. foreach my $index (keys(%tracks)) {
  283. if ($mixdown == $index && $tracks{$index}->{'codec'} eq 'OTHER' && $tracks{$index}->{'channels'} <= 2) {
  284. if ($DEBUG) {
  285. print STDERR 'Skipping recode of track ' . $index . ' since it is already used as the default track and contains only ' . $tracks{$index}->{'channels'} . " channels\n";
  286. }
  287. next;
  288. } else {
  289. my %track = ('index' => $index, 'encoder' => 'copy');
  290. push(@audio_tracks, \%track);
  291. }
  292. }
  293. # Consolidate from the hashes
  294. my @output_tracks = ();
  295. my @output_encoders = ();
  296. foreach my $track (@audio_tracks) {
  297. push(@output_tracks, $track->{'index'});
  298. push(@output_encoders, $track->{'encoder'});
  299. }
  300. # Send back the argument strings
  301. return ('--audio', join(',', @output_tracks), '--aencoder', join(',', @output_encoders));
  302. }
  303. sub scan($) {
  304. my ($in_file) = @_;
  305. # Fork to scan the file
  306. my $child_out = '';
  307. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--title', '0', '--input', $in_file);
  308. # Loop through the output
  309. my $scan;
  310. my %titles = ();
  311. my $inTitle = 0;
  312. my $zone = '';
  313. my $dca_stream = -1;
  314. my %dca_lossless = ();
  315. while (<$child_out>) {
  316. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  317. if ($DEBUG) {
  318. print STDERR 'Found ' . $1 . " titles in source\n";
  319. }
  320. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  321. my $stream = $1;
  322. my $desc = $2;
  323. $dca_stream = -1;
  324. if ($desc =~ /Audio\:\s+dca/) {
  325. $dca_stream = $stream;
  326. }
  327. } elsif ($dca_stream >= 0 && m/^\s+title\s*\:\s+(.*)/) {
  328. if ($1 =~ /Lossless/i) {
  329. $dca_lossless{$dca_stream} = 1;
  330. if ($DEBUG) {
  331. print STDERR 'Found DTS Lossless audio in stream: ' . $dca_stream . "\n";
  332. }
  333. }
  334. $dca_stream = -1;
  335. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  336. # Save the current title (if any)
  337. if ($inTitle) {
  338. $titles{$inTitle} = $scan;
  339. }
  340. # Grab the new title number
  341. $inTitle = $1;
  342. # Init the data collectors
  343. my @audio = ();
  344. my @crop = ();
  345. my @subtitle = ();
  346. my @size = ();
  347. my %tmp = (
  348. 'audio' => \@audio,
  349. 'crop' => \@crop,
  350. 'subtitle' => \@subtitle,
  351. 'size' => \@size,
  352. 'duration' => 0,
  353. 'aspect' => 0
  354. );
  355. $scan = \%tmp;
  356. if ($DEBUG) {
  357. print STDERR 'Found data for title ' . $1 . "\n";
  358. }
  359. } elsif ($inTitle) {
  360. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  361. push(@{ $scan->{'size'} }, $1, $2);
  362. if ($DEBUG) {
  363. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  364. }
  365. if (/\s+display aspect\: (\d*\.\d+)/) {
  366. $scan->{'aspect'} = $1;
  367. if ($DEBUG) {
  368. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  369. }
  370. }
  371. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  372. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  373. if ($DEBUG) {
  374. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  375. }
  376. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  377. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  378. if ($DEBUG) {
  379. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  380. }
  381. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  382. $zone = 'audio';
  383. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  384. my %track = ('index' => $1, 'description' => $2);
  385. if ($dca_lossless{ $track{'index'} }) {
  386. $track{'description'} =~ s/\(DTS\)/\(DTS-MA\)/;
  387. }
  388. push(@{ $scan->{'audio'} }, \%track);
  389. if ($DEBUG) {
  390. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  391. }
  392. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  393. $zone = 'subtitle';
  394. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  395. my %track = ('index' => $1, 'description' => $2);
  396. push(@{ $scan->{'subtitle'} }, \%track);
  397. if ($DEBUG) {
  398. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  399. }
  400. }
  401. }
  402. }
  403. # Save the last title (if any)
  404. if ($inTitle) {
  405. $titles{$inTitle} = $scan;
  406. }
  407. # Cleanup the scan process
  408. waitpid($pid, 0);
  409. close($child_out);
  410. # Sanity check
  411. if (scalar(keys(%titles)) < 1) {
  412. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  413. }
  414. # Return
  415. return %titles;
  416. }
  417. sub findBestAudioTrack($$) {
  418. my ($tracks, $codec) = @_;
  419. my $best = undef();
  420. my $bestChannels = 0;
  421. for my $index (keys(%{$tracks})) {
  422. my $track = $tracks->{$index};
  423. # Skip tracks not in the specified codec
  424. if ($track->{'codec'} ne $codec) {
  425. next;
  426. }
  427. # Skip foreign langugae tracks
  428. if ($track->{'language'} =~ /\b(Chinese|Espanol|Francais|Japanese|Korean|Portugues|Thai)\b/i) {
  429. if ($DEBUG) {
  430. print STDERR 'Skipping audio track ' . $index . ' due to language: ' . $track->{'language'} . "\n";
  431. }
  432. next;
  433. }
  434. if (!defined($best) || $track->{'channels'} > $bestChannels) {
  435. $best = $index;
  436. $bestChannels = $track->{'channels'};
  437. }
  438. }
  439. return $best;
  440. }