encode.pl 25 KB

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