encode.pl 25 KB

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