encode.pl 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use POSIX;
  6. use IPC::Open3;
  7. use File::Basename;
  8. # Default configuration
  9. my $FORMAT = 'mp4';
  10. my $AUDIO_BITRATE = 192;
  11. my $QUALITY = 20;
  12. my $HD_QUALITY = 22;
  13. my $AUDIO_COPY = 0;
  14. my $STEREO_ONLY = 0;
  15. my $VIDEO_ONLY = 0;
  16. my $HEIGHT = undef();
  17. my $WIDTH = undef();
  18. my $AUDIO_EXCLUDE_REGEX =
  19. '\b(?:Chinese|Czech|Deutsch|Espanol|Francais|Italiano|Japanese|Korean|Magyar|Polish|Portugues|Russian|Thai|Turkish|Ukrainian)\b';
  20. my $SUB_INCLUDE_REGEX = '\b(?:English|Unknown|Closed\s+Captions)\b';
  21. my $FORCE_MP4 = 0;
  22. my $OUT_DIR = undef();
  23. my $MIXDOWN_CODEC = 'AAC';
  24. my $MIXDOWN_CHANNELS = 2.0;
  25. my $AAC_ENCODER = 'ffaac';
  26. # Applicaton configuration
  27. my $HD_WIDTH = 1350;
  28. my $MIN_VIDEO_WIDTH = 100;
  29. my $MAX_CROP_DIFF = .1;
  30. my $MAX_DURA_DIFF = 5;
  31. my $NO_CROP = 0;
  32. my @CODEC_ORDER = ('DTS-HD', 'FLAC', 'DTS', 'AC3', 'PCM', 'VORBIS', $MIXDOWN_CODEC, 'OTHER');
  33. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  34. my $DEBUG = 0;
  35. # General parameters for HandBrake
  36. my @video_params =
  37. ('--markers', '--optimize', '--detelecine', '--decomb', '--auto-anamorphic', '--encoder', 'x265', '--encoder-preset', 'slow');
  38. my @audio_params = ('--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ffac3');
  39. # Use CoreAudio where available
  40. my ($OS) = POSIX::uname();
  41. if ($OS eq 'Darwin') {
  42. $AAC_ENCODER = 'ca_aac';
  43. }
  44. # Runtime debug mode
  45. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  46. $DEBUG = 1;
  47. }
  48. # Shortcut config
  49. if ($ENV{'MOBILE'}) {
  50. $ENV{'QUALITY'} = 24;
  51. $ENV{'HEIGHT'} = 720;
  52. $ENV{'WIDTH'} = 1280;
  53. $ENV{'AUDIO_BITRATE'} = 128;
  54. $ENV{'STEREO_ONLY'} = 1;
  55. }
  56. # Allow overrides for audio languages
  57. if ($ENV{'AUDIO_EXCLUDE_REGEX'}) {
  58. $AUDIO_EXCLUDE_REGEX = $ENV{'AUDIO_EXCLUDE_REGEX'};
  59. }
  60. # Allow overrides for subtitle languages
  61. if ($ENV{'SUB_INCLUDE_REGEX'}) {
  62. $SUB_INCLUDE_REGEX = $ENV{'SUB_INCLUDE_REGEX'};
  63. }
  64. # Allow copy-only audio transfers (for use in re-encoding)
  65. if ($ENV{'AUDIO_COPY'}) {
  66. $AUDIO_COPY = 1;
  67. }
  68. # Allow AAC-only audio transfers (for use in mobile encoding)
  69. if ($ENV{'STEREO_ONLY'}) {
  70. $STEREO_ONLY = 1;
  71. }
  72. # Allow video-only transfers
  73. if ($ENV{'VIDEO_ONLY'}) {
  74. $VIDEO_ONLY = 1;
  75. }
  76. # Allow MP4-only output format (for use in mobile encoding)
  77. if ($ENV{'FORCE_MP4'}) {
  78. $FORCE_MP4 = 1;
  79. }
  80. # Allow overrides for video quality
  81. if ($ENV{'QUALITY'}) {
  82. $QUALITY = $ENV{'QUALITY'};
  83. $HD_QUALITY = $ENV{'QUALITY'};
  84. }
  85. # Allow overrides for audio bitrate
  86. if ($ENV{'AUDIO_BITRATE'}) {
  87. $AUDIO_BITRATE = $ENV{'AUDIO_BITRATE'};
  88. }
  89. # Use an alternate output directory, if specified
  90. if ($ENV{'OUT_DIR'}) {
  91. $OUT_DIR = $ENV{'OUT_DIR'};
  92. $OUT_DIR =~ s/\/+$//;
  93. }
  94. # Allow overrides for video height and width. The default is "same as source".
  95. if ($ENV{'HEIGHT'}) {
  96. push(@video_params, '--maxHeight', $ENV{'HEIGHT'});
  97. }
  98. if ($ENV{'WIDTH'}) {
  99. push(@video_params, '--maxWidth', $ENV{'WIDTH'});
  100. }
  101. # Disable cropping
  102. if ($ENV{'NO_CROP'}) {
  103. $NO_CROP = 1;
  104. }
  105. # Enable greyscale mode
  106. if ($ENV{'GREYSCALE'}) {
  107. push(@video_params, '--grayscale');
  108. }
  109. # Additional arguments for HandBrake, to allow options not supported directly by this script
  110. # Split on spaces; if you need spaces you'll have to work out something else
  111. if ($ENV{'HANDBRAKE_ARGS'}) {
  112. my @args = split(/\s+/, $ENV{'HANDBRAKE_ARGS'});
  113. push(@video_params, @args);
  114. }
  115. # Command-line parameters
  116. my ($in_file, $out_file, $title) = @ARGV;
  117. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  118. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  119. }
  120. # Sanity checks
  121. if ($AUDIO_COPY && $STEREO_ONLY) {
  122. die(basename($0) . ": AUDIO_COPY and STEREO_ONLY are mutually exclusive\n");
  123. }
  124. if ($VIDEO_ONLY && ($AUDIO_COPY || $STEREO_ONLY)) {
  125. die(basename($0) . ": VIDEO_ONLY and AUDIO_COPY or STEREO_ONLY are mutually exclusive\n");
  126. }
  127. # Scan for title/track info
  128. my %titles = &scan($in_file);
  129. # Allow external subtitles for single-title files
  130. if (scalar(keys(%titles)) == 1) {
  131. my $srt_file = $in_file;
  132. $srt_file =~ s/\.\w{2,4}$/.srt/;
  133. if (!-r $srt_file) {
  134. $srt_file =~ s/\.\w{2,4}$/.ssa/;
  135. }
  136. if (-r $srt_file) {
  137. if ($DEBUG) {
  138. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  139. }
  140. push(@video_params, '--srt-file', $srt_file);
  141. }
  142. }
  143. # Allow encoding of a specific title
  144. if ($title) {
  145. if ($title =~ /^\d+$/ && $title > 0) {
  146. if (!defined($titles{$title})) {
  147. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  148. }
  149. my $selected_title = $titles{$title};
  150. %titles = ();
  151. $titles{$title} = $selected_title;
  152. } elsif ($title =~ /main/i) {
  153. my $max_title = 0;
  154. my $max_duration = 0;
  155. foreach my $title (keys(%titles)) {
  156. if (!$titles{$title}{'duration'}) {
  157. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  158. next;
  159. }
  160. my $new_max = 0;
  161. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  162. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  163. $new_max = 1;
  164. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0]
  165. || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1])
  166. {
  167. $new_max = 1;
  168. }
  169. } elsif ($titles{$title}{'duration'} > $max_duration) {
  170. $new_max = 1;
  171. }
  172. if ($new_max) {
  173. $max_duration = $titles{$title}{'duration'};
  174. $max_title = $title;
  175. }
  176. }
  177. my $selected_title = $titles{$max_title};
  178. %titles = ();
  179. $titles{$max_title} = $selected_title;
  180. }
  181. }
  182. # Ensure we have an output file name
  183. # Force MKV output if the output file name is provided and ends in .MKV
  184. if (!defined($out_file) || length($out_file) < 1) {
  185. $out_file = $in_file;
  186. } else {
  187. my ($force_format) = $out_file =~ /\.(\w{2,4})$/;
  188. if (defined($force_format) && lc($force_format) eq 'mkv') {
  189. $FORMAT = 'mkv';
  190. }
  191. }
  192. # Override the output directory, if requested
  193. if ($OUT_DIR) {
  194. $out_file = $OUT_DIR . '/' . basename($out_file);
  195. }
  196. # Keep copies of our defaults so we can reset between tracks
  197. my $format_default = $FORMAT;
  198. # Encode each title
  199. foreach my $title (keys(%titles)) {
  200. if ($DEBUG) {
  201. print STDERR 'Setting options for title: ' . $title . "\n";
  202. }
  203. # Reset
  204. $FORMAT = $format_default;
  205. # Select a title
  206. my $scan = $titles{$title};
  207. # Skip tracks that have no video
  208. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  209. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  210. next;
  211. }
  212. # Parse subtitle tracks
  213. my @subs = &subOptions($scan);
  214. # Parse audio tracks, unless we're in VIDEO_ONLY mode
  215. my @audio = ();
  216. if (!$VIDEO_ONLY) {
  217. @audio = &audioOptions($scan);
  218. # Skip tracks that have no audio
  219. if (scalar(@{ $scan->{'audio'} }) < 1 || scalar(@audio) < 1) {
  220. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  221. next;
  222. }
  223. # Set the bitrate for transcoded audio tracks
  224. push(@audio, '--ab', $AUDIO_BITRATE);
  225. }
  226. # Set the video quality, using $HD_QUALITY for images larger than $HD_WIDTH (to allow lower quality on HD streams)
  227. my $title_quality = $QUALITY;
  228. if ($scan->{'size'}[0] > $HD_WIDTH) {
  229. $title_quality = $HD_QUALITY;
  230. }
  231. # Detect unlikely autocrop values
  232. my $bad_crop = 0;
  233. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  234. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  235. {
  236. print STDERR basename($0)
  237. . ': Overriding unlikely autocrop values: '
  238. . join(':', @{ $scan->{'crop'} }) . ': '
  239. . $in_file . "\n";
  240. $bad_crop = 1;
  241. }
  242. # Disable cropping (if no crop argument is passed, HB will autocrop, so set 0:0:0:0 explictly)
  243. if ($NO_CROP || $bad_crop) {
  244. my @crop = (0, 0, 0, 0);
  245. $scan->{'crop'} = \@crop;
  246. }
  247. # Force MKV muxing if the output contains PGS subtitles (there's no support in the MP4 muxer)
  248. foreach my $track (values(%{ $scan->{'subtitle_selected'} })) {
  249. if ($track->{'type'} eq 'PGS') {
  250. $FORMAT = 'mkv';
  251. last;
  252. }
  253. }
  254. # Force MKV muxing if the output contains DTS audio (technically MP4 supports it but QuickTime hates it)
  255. foreach my $track (values(%{ $scan->{'audio_selected'} })) {
  256. if ($track->{'codec'} =~ /DTS/i) {
  257. $FORMAT = 'mkv';
  258. last;
  259. }
  260. }
  261. # Select a file name extension that matches the format
  262. my $title_out_file = $out_file;
  263. $title_out_file =~ s/\.(?:\w{2,4}|dvdmedia)$//i;
  264. if ($FORMAT eq 'mkv') {
  265. $title_out_file .= '.mkv';
  266. } else {
  267. $title_out_file .= '.m4v';
  268. }
  269. # Force the title number into the output file name if there are multiple titles to be encoded
  270. if (scalar(keys(%titles)) > 1) {
  271. my $title_text = sprintf('%02d', $title);
  272. $title_out_file =~ s/(\.\w{2,4})$/\-${title_text}${1}/;
  273. }
  274. # Output file
  275. if (uc($title_out_file) eq uc($in_file)) {
  276. $title_out_file =~ s/(\.\w{2,4})$/-recode${1}/;
  277. }
  278. # Build the arugment list
  279. my @args = ($HB_EXEC);
  280. push(@args, '--title', $title);
  281. push(@args, '--input', $in_file);
  282. push(@args, '--output', $title_out_file);
  283. push(@args, '--format', $FORMAT);
  284. push(@args, '--quality', $title_quality);
  285. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  286. push(@args, @video_params);
  287. push(@args, @subs);
  288. # Include audio unless specifically excluded
  289. if (!$VIDEO_ONLY) {
  290. push(@args, @audio_params);
  291. push(@args, @audio);
  292. }
  293. if ($DEBUG) {
  294. print STDERR "\n" . join(' ', @args) . "\n\n";
  295. }
  296. # Sanity check
  297. if (-e $title_out_file) {
  298. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  299. next;
  300. }
  301. # Run it
  302. my $child_out = '';
  303. my $child_in = '';
  304. my $pid = open3($child_in, $child_out, $child_out, @args);
  305. close($child_in);
  306. while (<$child_out>) {
  307. if ($DEBUG) {
  308. print STDERR $_;
  309. }
  310. }
  311. waitpid($pid, 0);
  312. close($child_out);
  313. # Provide the new file name if requested
  314. if ($ENV{'RECODE_OUTFILE'}) {
  315. print $title_out_file;
  316. }
  317. }
  318. # Cleanup
  319. exit(0);
  320. sub subOptions($) {
  321. my ($scan) = @_;
  322. my %tracks = ();
  323. foreach my $track (@{ $scan->{'subtitle'} }) {
  324. my ($language, $note, $iso, $text, $type) = $track->{'description'} =~
  325. /^([^\(]+)(?:\s+\(([^\)]+)\))?\s+\(iso(\d+\-\d+)\:\s+\w\w\w\)\s+\((Text|Bitmap)\)\((CC|VOBSUB|PGS|SSA|TX3G|UTF\-\d+)\)/i;
  326. if (!defined($iso)) {
  327. print STDERR 'Could not parse subtitle description: ' . $track->{'description'} . "\n";
  328. next;
  329. }
  330. # Map text/bitmap into a boolean
  331. if ($text =~ /TEXT/i) {
  332. $text = 1;
  333. } else {
  334. $text = 0;
  335. }
  336. # Standardize the codes
  337. $iso = uc($iso);
  338. $type = uc($type);
  339. # Push all parsed data into an array
  340. my %data = ('language' => $language, 'note' => $note, 'iso' => $iso, 'text' => $text, 'type' => $type);
  341. $tracks{ $track->{'index'} } = \%data;
  342. # Print what we found
  343. if ($DEBUG) {
  344. print STDERR 'Found subtitle track: ';
  345. printHash(\%data);
  346. }
  347. }
  348. # Push the parsed data back up the chain
  349. $scan->{'subtitle_parsed'} = \%tracks;
  350. # Select the subtitle tracks we want to keep
  351. my @keep = ();
  352. foreach my $index (keys(%tracks)) {
  353. # Skip PGS tracks when we're forcing MP4 output (they're not allowed by the muxer)
  354. if ($FORCE_MP4 && $tracks{$index}->{'type'} eq 'PGS') {
  355. next;
  356. }
  357. # Keep tracks in our prefered language, and all text-based subtitles (they're small)
  358. if (isValidSubLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  359. push(@keep, $index);
  360. } elsif ($tracks{$index}->{'text'}) {
  361. push(@keep, $index);
  362. } else {
  363. if ($DEBUG) {
  364. print STDERR 'Skipping subtitle ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  365. }
  366. }
  367. }
  368. # Push the selected tracks back up the chain
  369. my %tmp = ();
  370. foreach my $num (@keep) {
  371. $tmp{$num} = $tracks{$num};
  372. }
  373. $scan->{'subtitle_selected'} = \%tmp;
  374. # Send back the argument string (if any)
  375. if (scalar(@keep) < 1) {
  376. return '';
  377. }
  378. return ('--subtitle', join(',', @keep));
  379. }
  380. sub audioOptions($) {
  381. my ($scan) = @_;
  382. my @retval = ();
  383. # Type the audio tracks
  384. my %tracks = ();
  385. foreach my $track (@{ $scan->{'audio'} }) {
  386. my ($language, $codec, $note, $channels, $iso, $specs) = $track->{'description'} =~
  387. /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?(?:,\s+(.*))?/;
  388. if (!defined($channels)) {
  389. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  390. next;
  391. }
  392. # Decode the channels string to a number
  393. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  394. $channels = $1;
  395. } elsif ($channels =~ /Dolby\s+Surround/i) {
  396. $channels = 3.1;
  397. }
  398. # Standardize the codec
  399. foreach my $code (@CODEC_ORDER) {
  400. my $metacode = quotemeta($code);
  401. if ($codec =~ /${metacode}/i) {
  402. $codec = $code;
  403. last;
  404. } elsif ($code eq 'OTHER') {
  405. if ($codec =~ /MP3/i || $codec =~ /MPEG/i || $codec =~ /MP2/i) {
  406. $codec = $code;
  407. } elsif ($codec eq 'dca') {
  408. print STDERR 'Found incompatible audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  409. $codec = undef();
  410. } else {
  411. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  412. $codec = $code;
  413. }
  414. }
  415. }
  416. # Standardize the specs
  417. my $bitrate = 0;
  418. my $samplerate = 0;
  419. if (!$specs) {
  420. $specs = '';
  421. }
  422. if ($specs =~ /(\d+)bps/) {
  423. $bitrate = $1 / 1000;
  424. } elsif ($specs =~ /(\d+)\s*kb\/s/) {
  425. $bitrate = $1;
  426. }
  427. if ($specs =~ /(\d+)Hz/) {
  428. $samplerate = $1;
  429. }
  430. # Push all parsed data into the array
  431. my %data = (
  432. 'language' => $language,
  433. 'codec' => $codec,
  434. 'channels' => $channels,
  435. 'iso' => $iso,
  436. 'note' => $note,
  437. 'bitrate' => $bitrate,
  438. 'samplerate' => $samplerate,
  439. );
  440. $tracks{ $track->{'index'} } = \%data;
  441. # Print what we found
  442. if ($DEBUG) {
  443. print STDERR 'Found audio track: ';
  444. printHash(\%data);
  445. }
  446. }
  447. # Push the parsed data back up the chain
  448. $scan->{'audio_parsed'} = \%tracks;
  449. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  450. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  451. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  452. my $mixdown = undef();
  453. my %bestByCodec = ();
  454. my $bestCodec = undef();
  455. my $mostChannels = 0;
  456. # Loop point, in case we need to run the selector more than once
  457. SELECT_AUDIO:
  458. foreach my $codec (@CODEC_ORDER) {
  459. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  460. if (defined($bestByCodec{$codec})
  461. && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'}))
  462. {
  463. $bestCodec = $codec;
  464. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  465. }
  466. }
  467. foreach my $codec (@CODEC_ORDER) {
  468. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  469. $mixdown = $bestByCodec{$codec};
  470. last;
  471. }
  472. }
  473. # Sanity check
  474. if (!defined($mixdown) || $mixdown < 1) {
  475. # If we applied an exclude filter, remove it and try again
  476. if ($AUDIO_EXCLUDE_REGEX ne 'ACCEPT_ALL') {
  477. $AUDIO_EXCLUDE_REGEX = 'ACCEPT_ALL';
  478. print STDERR "No usable audio tracks found in title. Removing exclude filter...\n";
  479. goto SELECT_AUDIO;
  480. }
  481. # If we got no audio, give up -- this file is not valid
  482. print STDERR basename($0) . ": No usable audio tracks in title\n";
  483. return;
  484. }
  485. # Clear the mixdown selection if we're copying audio
  486. if ($AUDIO_COPY) {
  487. $mixdown = undef();
  488. }
  489. # Mixdown track first
  490. my @audio_tracks = ();
  491. if (defined($mixdown) && $mixdown > 0) {
  492. if ($DEBUG) {
  493. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  494. if ($tracks{$mixdown}->{'channels'} > 2) {
  495. push(@retval, '--mixdown', 'dpl2');
  496. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  497. }
  498. }
  499. my %track = ('index' => $mixdown, 'encoder' => $AAC_ENCODER);
  500. push(@audio_tracks, \%track);
  501. }
  502. # Keep all other audio tracks, unless STEREO_ONLY is set
  503. if (!$STEREO_ONLY) {
  504. # Passthru DTS-MA, DTS, AC3, and AAC
  505. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  506. foreach my $index (keys(%tracks)) {
  507. if (defined($mixdown) && $mixdown == $index && $tracks{$index}->{'channels'} <= $MIXDOWN_CHANNELS) {
  508. if ($DEBUG) {
  509. print STDERR 'Skipping passthru of track '
  510. . $index
  511. . ' since it is already used as the mixdown track and contains only '
  512. . $tracks{$index}->{'channels'}
  513. . " channels\n";
  514. }
  515. next;
  516. } elsif (!$tracks{$index}->{'codec'}) {
  517. if ($DEBUG) {
  518. print STDERR 'Skipping track ' . $index . " due to invalid codec\n";
  519. }
  520. next;
  521. } elsif (!isValidAudioLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  522. if ($DEBUG) {
  523. print STDERR 'Skipping track ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  524. }
  525. next;
  526. } elsif ($FORCE_MP4 && $tracks{$index}->{'codec'} =~ /DTS/i) {
  527. if ($DEBUG) {
  528. print STDERR 'Skipping track ' . $index . " due to DTS codec and FORCE_MP4 flag\n";
  529. }
  530. next;
  531. } else {
  532. my %track = ('index' => $index, 'encoder' => 'copy');
  533. push(@audio_tracks, \%track);
  534. }
  535. }
  536. }
  537. # Push the selected tracks back up the chain
  538. my %sel = ();
  539. foreach my $track (@audio_tracks) {
  540. # Copy the data, rather than just point to it -- we sometimes need modifications
  541. my $index = $track->{'index'};
  542. my %tmp = %{ $tracks{$index} };
  543. # The mixdown track needs special handling -- it appears twice, and with different settings
  544. if ($track->{'encoder'} ne 'copy' && defined($mixdown) && $mixdown > 0 && $track->{'index'} == $mixdown) {
  545. $index .= '_mixdown';
  546. $tmp{'codec'} = $MIXDOWN_CODEC;
  547. $tmp{'channels'} = $MIXDOWN_CHANNELS;
  548. }
  549. # Collect our (possibly modified) hash
  550. $sel{$index} = \%tmp;
  551. }
  552. $scan->{'audio_selected'} = \%sel;
  553. # Consolidate from the hashes
  554. my @output_tracks = ();
  555. my @output_encoders = ();
  556. foreach my $track (@audio_tracks) {
  557. push(@output_tracks, $track->{'index'});
  558. push(@output_encoders, $track->{'encoder'});
  559. }
  560. # Send back the argument strings
  561. push(@retval, '--audio', join(',', @output_tracks));
  562. push(@retval, '--aencoder', join(',', @output_encoders));
  563. return (@retval);
  564. }
  565. sub scan($) {
  566. my ($in_file) = @_;
  567. # Fork to scan the file
  568. my $child_out = '';
  569. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--previews', '30', '--title', '0', '--input', $in_file);
  570. # Loop through the output
  571. my $scan;
  572. my %titles = ();
  573. my $inTitle = 0;
  574. my $zone = '';
  575. while (<$child_out>) {
  576. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  577. if ($DEBUG) {
  578. print STDERR 'Found ' . $1 . " titles in source\n";
  579. }
  580. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  581. my $stream = $1;
  582. my $desc = $2;
  583. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  584. # Save the current title (if any)
  585. if ($inTitle) {
  586. $titles{$inTitle} = $scan;
  587. }
  588. # Grab the new title number
  589. $inTitle = $1;
  590. # Init the data collectors
  591. my @audio = ();
  592. my @crop = ();
  593. my @subtitle = ();
  594. my @size = ();
  595. my %tmp = (
  596. 'audio' => \@audio,
  597. 'crop' => \@crop,
  598. 'subtitle' => \@subtitle,
  599. 'size' => \@size,
  600. 'duration' => 0,
  601. 'aspect' => 0
  602. );
  603. $scan = \%tmp;
  604. if ($DEBUG) {
  605. print STDERR 'Found data for title ' . $1 . "\n";
  606. }
  607. } elsif ($inTitle) {
  608. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  609. push(@{ $scan->{'size'} }, $1, $2);
  610. if ($DEBUG) {
  611. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  612. }
  613. if (/\s+display aspect\: (\d*\.\d+)/) {
  614. $scan->{'aspect'} = $1;
  615. if ($DEBUG) {
  616. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  617. }
  618. }
  619. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  620. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  621. if ($DEBUG) {
  622. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  623. }
  624. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  625. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  626. if ($DEBUG) {
  627. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  628. }
  629. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  630. $zone = 'audio';
  631. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  632. my %track = ('index' => $1, 'description' => $2);
  633. push(@{ $scan->{'audio'} }, \%track);
  634. if ($DEBUG) {
  635. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  636. }
  637. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  638. $zone = 'subtitle';
  639. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  640. my %track = ('index' => $1, 'description' => $2);
  641. push(@{ $scan->{'subtitle'} }, \%track);
  642. if ($DEBUG) {
  643. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  644. }
  645. }
  646. }
  647. }
  648. # Save the last title (if any)
  649. if ($inTitle) {
  650. $titles{$inTitle} = $scan;
  651. }
  652. # Cleanup the scan process
  653. waitpid($pid, 0);
  654. close($child_out);
  655. # Sanity check
  656. if (scalar(keys(%titles)) < 1) {
  657. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  658. }
  659. # Return
  660. return %titles;
  661. }
  662. sub findBestAudioTrack($$) {
  663. my ($tracks, $codec) = @_;
  664. my $best = undef();
  665. my @available = ();
  666. # Find available tracks
  667. for my $index (keys(%{$tracks})) {
  668. my $track = $tracks->{$index};
  669. # Skip tracks not in the specified codec
  670. if (!$track->{'codec'} || $track->{'codec'} ne $codec) {
  671. next;
  672. }
  673. # Skip foreign language tracks
  674. if (!isValidAudioLanguage($track->{'language'}, $track->{'iso'})) {
  675. next;
  676. }
  677. push(@available, $index);
  678. }
  679. if (scalar(@available) < 1) {
  680. return $best;
  681. }
  682. # Find the tracks with the most channels
  683. {
  684. my @most = ();
  685. my $channels = 0;
  686. foreach my $index (@available) {
  687. my $track = $tracks->{$index};
  688. if ($track->{'channels'} > $channels) {
  689. @most = ($index);
  690. $channels = $track->{'channels'};
  691. } elsif ($track->{'channels'} == $channels) {
  692. push(@most, $index);
  693. }
  694. }
  695. @available = @most;
  696. }
  697. if (scalar(@available) < 1) {
  698. return $best;
  699. }
  700. # Find the tracks with the highest bitrate
  701. {
  702. my @highest = ();
  703. my $bitrate = 0;
  704. foreach my $index (@available) {
  705. my $track = $tracks->{$index};
  706. if ($track->{'bitrate'} > $bitrate) {
  707. @highest = ($index);
  708. $bitrate = $track->{'bitrate'};
  709. } elsif ($track->{'bitrate'} == $bitrate) {
  710. push(@highest, $index);
  711. }
  712. }
  713. @available = @highest;
  714. }
  715. if (scalar(@available) < 1) {
  716. return $best;
  717. }
  718. # Find the track if the lowest index
  719. foreach my $index (@available) {
  720. if (!defined($best) || $index < $best) {
  721. $best = $index;
  722. }
  723. }
  724. return $best;
  725. }
  726. sub isValidSubLanguage($) {
  727. my ($lang, $iso) = @_;
  728. if ($SUB_INCLUDE_REGEX && $lang =~ /${SUB_INCLUDE_REGEX}/i) {
  729. return 1;
  730. }
  731. return 0;
  732. }
  733. sub isValidAudioLanguage($) {
  734. my ($lang, $iso) = @_;
  735. if ($AUDIO_EXCLUDE_REGEX && $lang =~ /${AUDIO_EXCLUDE_REGEX}/i) {
  736. return 0;
  737. }
  738. return 1;
  739. }
  740. sub printHash($) {
  741. my ($data) = @_;
  742. my $first = 1;
  743. foreach my $key (keys(%{$data})) {
  744. if (defined($data->{$key})) {
  745. if ($first) {
  746. $first = 0;
  747. } else {
  748. print STDERR ', ';
  749. }
  750. print STDERR $key . ' => ' . $data->{$key};
  751. }
  752. }
  753. print STDERR "\n";
  754. }