Thursday, May 21, 2020

path - environment variable

NB: This post is related to a prior one this month regarding 3rd party package managers.


There are two types of environment variables, global (system) level, and local (user) level. Paths are just another environment variable. The tricky part: even though paths are a terminal environment file (see ~.bashrc or ~.profile), applications launched in an X session are presumed to come via the terminal, and so use terminal variables interact with the kernel. Users can also do this directly by exporting variables to the kernel. If we want to see them all

$ printenv

Environment Variables (7:55) Maloco, 2017. Goes over each, notes that they are kept in the

Times when paths are extremely important...
  • installing applications without using the package manager
  • making some change in an application's libraries because updates killed the link to its dependencies

package manager case (LaTeX)

I get a lot of use out of LaTeX and occasionally add special stylesheets or other packages. Accordingly, I install TexLive (4GB) directly into a home directory folder (typically "latex") and oversee it separately from Arch's package manager. Oversight is with tlmgr. During install, options appear to change the install path to a local directory if wanted. Once completed, the install will give the following message to update PATHs...

Accordingly...
$ nano .bashrc export PATH=/home/foo/latex/texlive/2020/bin/x86_64-linux/:$PATH export INFOPATH=/home/foo/latex/texlive/2020/texmf-dist/doc/info:INFOPATH export MANPATH=/home/foo/latex/texlive/2020/texmf-dist/doc/man:MANPATH
Then one can also add pdf-latex into their completion on Geany or whatever.

package manager case (Python)

Before going further, Colab is the easy Python coding solution through one's browser, and is generously hosted by Google. But we still might have occasion to code Python while offline, on our own system. In 2020, that's probably...
# pacman -S python-pipenv
... still how did we get here? It used to be complicated. Our goal was to cleanly install Python in a user directory, so that it didn't contaminate our distribution if we used pip to add any non-Arch Python modules. We wanted it a solution that:
  • allowed interaction with all Arch installed apps
  • allowed updating or enhancements using pip, but without contaminating the Arch install.
  • allowed libs whether inside our user directory or the larger Arch distro.
This was not an easy prospect, as succinctly described here. The thread overall advises us that we should use our distribution as much as we can and limit pip use to our "user setup" (local directory), and virtual environments. Anaconda is probably the most well known virtual environment/sandbox for Python, but the newer option of Pipenv (# pacman -S python-pipenv)looks even better.

Pipenv (20:48) Corey Schafer, 2018. Schafer now prefers this VE over Anaconda. Arch repository for the pipenv updates, but use pip inside the VE .
Anaconda use (20:48) Corey Schafer, 2017. This fellow uses both Anaconda and pip.

Sunday, May 17, 2020

PiP pt 2 -- more ffmpeg

contents
blur: somewhat complexglossary
structure/workflowkeyframes also my full post
color balancerotation simple in ffmpeg
crossfadeslideshow complex! use a GUI app
de-interlacewatermark
gif

NB: 1) try to make all cuts on keyframes, 2) "overlay" filter operations are unreal time lost


Links: 1) PiP Pt I   2) hardware for a system that will render

Impossibly, the simple crossfade is one of the most elusive video effects in Linux. You'd think simple transitions would be managed by any of the 10 GUI's out there, but the 10 GUI's are only intermittently usable whenver QT upgrades, or GTK upgrades, etc. So the only totally reliable way to do video is through a CLI, eg ffmpeg or melt. It's a complete pain in the ass, of course, so I use GUI's when they're actually running. Ex: Pitivi (and Shotcut subsequently - QT5), Flowblade, or Olive, are OK for crossfades -- not perfect but OK. One month, GTK got an upgrade, and thus we learn that GTK is not backwards compatible... poof! PiTiVi gone...

$ pitivi
ERROR - The following hard dependencies are unmet:
==================================================
- gtk not found on the system
# pacman -S gtk
error: target not found: gtk
# pacman -S gtk2
warning: gtk2-2.24.32-2 is up to date -- reinstalling

... WTF?!! So there's little choice but to go CLI for one's mental health -- it's our lives we're giving up to edit.

You can pick any GUI application. Like, there's final edit color balancing in Blender (Blender is so complex it's practically an OS itself), but even color balancing can be done inside ffmpeg (see 0612 TV w/NERDfirst around 6:00).

Besides impossible crossfades, the challenge within ffmpeg is keeping the number of renders to a minimum. We can use ffplay to preview or, since ffmpeg is non-destructive (non-linear), we can do a test render and check it. And don't forget ffprobe to get information out of the files. Also recall that, if we just add an audio track, we can copy the video codec and add audio without degrading the video whatsoever.

other options

And of course, one should also not overlook the MLT framework, eg "melt", for command line transitions, if it's still being developed, not sure. In 2020, there's bleeding-edge on the AUR (mlt-git), and in "extra" (mlt). With MLT you will need a frame counting tool, not just a second counting tool to make edits.

MLT Melt Transitions (13:48) Kris Occhipinti, 2012.

structure and workflow

See graphics below. Each edit requires several files (see my typical file structure)The grouping below is typical but of course can't include hand-drawn items: 1) storyboard 2)timing notes for audio sync with narration and so forth. How to pause and linger on a frame? The best storyboard may be a video describing the drawings while doing a UMlet workflow.



If you imagine the workflow graphic above as 3-D, one can see that each item is not equal. In the 3rd column, there's a place to get started on code and that's because the most flexible TTS is via Python, but Python itself is a deep subject requiring thoughtful installation. So just to make the TTS possible is likely a 2 week project.

blur (+1 render)

This is a complex ffmpeg filter. Three processes are accomplished, a box region is cropped out, it's blurred, and it's re-overlaid onto the original video. Added difficulty is determining an x:y dimension for the region.

$ ffmpeg -i foo-in.mp4 -filter_complex \
"[0:V]crop=100:100, boxblur=20[fg]; \
[0:V][fg]overlay=(main_w-200):30" foo-out.mp4

Ffmpeg blur box (6:45) Cool IT Help, 2019. A bit of a strong accent, but no BS.

concatenate (+1 render)

The +1 render is when getting one's clips ready: rotating, accomplishing any dissolve edits ahead of time. There's no render during the actual concatenation. Try different orderings of your clips in a simple M3U, playing the M3U with vlc or xplayer. You can keep filenames simple, avoiding full absolute paths, if you place the M3U in the same directory with the clips. The format...

# This is a comment
somevideo.mp4
anothervideo.mp4
  • finalize the mix order in the m3u
  • open vlc and be sure "repeat" is disabled (else it will go into infinite loop). close vlc.
  • $ vlc playlist.m3u --sout "#gather:std{access=file,dst=vlcmerged.mp4}" --sout-keep
...in 5-6 seconds, this command concatenated 31 clips into a 7 minute 720P h264 video with sound, no tearing, and so on. It's production quality. The process is described here, albeit with Windows conventions.

Using ffmpeg can also be without rendering (-c copy), but will likely lead to DTS timestamp errors and tearing in playback. Even if one renders, the quality has not yet been as high as the vlc method above. Additionally, it doesn't work with an M3U. One has to make a text file with a special syntax on each line (viz, file 'foo.mp4') and one file per line, repeats also OK however.

$ ffmpeg -f concat -i playlist.txt -c:v libx264 -an grouped.mp4
I find that playback with the resulting file is often jerky or paused, even when all files are the same encoder and there is discussion (render, tbr) about how to manage this, but I've never found anything to prevent it. If I had time, I would troubleshoot until a fix.

colorbalance (+1 render)

Not sure if we could chain filters and do this with a single render

$ ffmpeg -i foo.mp4 -vf "colorbalance=rs=-0.25,colorbalance=bm=-0.25" evencolor.mp4

How to use FFMpeg - Advanced Pt1 (19:37) 0612 TV w/NERDfirst, 2015. Color balance at the 7:30 mark.
Another great site, and he also has a video attached.

crossfade (+2 render)

Typically, crossfades (aka "dissolves") are the most complex thing in Linux video editing and a separate post will likely be forthcoming. Some progress has ocurred however. This recent article is a must-read on the subject.

$ ffmpeg -i invid1.mp4 -i invid2.mp4 -filter_complex xfade=transition=fade:duration=2:offset=24 outputvid.mp4

... where the duration of the crossfade is 2 seconds, and it begins at the 24 second mark. Note that this effect renders with extremely high (hot) CPU cycling, even for a short clip.

Pan and Zoom Slideshow (26:50) Chipper Videos, 2019. Blender 2.8. Crossfade is shown in approximately last 5 minutes, but acccurate. Most is concerned with Ken Burns.
Crossfade (0:20) doufuwang, 2016. Shows the crossfade or dissolve effect perfectly.
Tech Notes: FFmpeg Multi Fades In Out (37:09) Steve AB4EL, 2017. Hilarious. Drones on and on. Takes 3 pictures and makes slide show. (8:30)fade transitions
FFmpeg Cross fades (2:25) A Forum, 2020. One of the best out there. Command given above is taken from here.

de-interlace (+1 render)

De-interlacing increases the frame rate. It could take you from 30 to 60, for example.

Sample Video Editing Workflow using FFmpeg (19:33) Rick Makes, 2019. Covers de-interlacing (2:00) to get rid of lines,cropping, audio library(13:30), and so on.

$ ffmpeg -i foo.mp4 -vf "bwdif=1" -c:a copy defoo.mp4

glossary

  • frame rate vs. fps: these appear identical, and its unfortunate. It's nuanced like iframe and keyframe. Framerate (-r) is an input parameter used for setting fps. Fps is the stream speed. Ex: I want a 6 second video of 3 photos - I set fps to 2, and framerate to 12.
  • ripple-cut: cut per usual, but then it magnets over to previous clip to fill the space

scripts

There are two types we might want to consider

  • bash: easiest for ffmpeg sequence, not sure for tts
  • python: using pip we can get some tts modules, send to WAV

We want to make bash scripts for the ffmpeg actions.

timing

If I want to add sound effects or narrate, how do we at once watch the film and secondly enter sounds? The best way is to watch the film and take timing notes. Perhaps you want to pause on a frame for a few seconds while you discuss something.While you're watching the soundless video, just note how long you hold down the pause key to do your talking, say 5 seconds, and then using a loop filter

reverse

This one just for video.
$ ffmpeg -i foo -vf reverse reversed.mp4

rotation (+1 render)

Few do it better than NERDfirst. The reason for the division is ffmpeg determines the angle in radians. Furthermore the angle of rotation is clockwise. The most common is righting an upside down video.

$ ffmpeg -i foo.mp4 -filter:v "rotate=PI" fout.mp4

How to use FFMpeg (12:48) 0612 TV w/NERDfirst, 2015. At the 11:00 mark, he describes rotation, and scaling just before it.

slideshow (+1 or 2 render)

The simplest slideshow just cuts from one to the next at a set time, say 10 seconds. This is pretty easy to do on an entire directory of numbered pix, say foo01.png, foo02.png, foo03.png, etc. The "2d" indicates how many digits in the numbering system.

$ ffmpeg -framerate 1/10 -i foo%02d.png -c:v libx264 -r 30 -pix_fmt yuv420p slideshow.mp4

Similar to the Bash above is a slideshow. Run a batch file on a set of pictures and to make short 5 second video clips of them all, first render. At that point, we can do Ken Burns on some videos, and on others just overlap one to the next, the second render. Here, I have 3 x 5 second clips, and first accomplished $ yay ffmeg-concat so that I didn't have to use the complicated overlay filter.

$ shotcut
This fades up and down from black for each one and is not a dissolve between them. For those using Windows, a caret "^" breaks-up the command in a batch instead of a backslash.
$ffmpeg -i foo1.mp4 -i foo2.mp4 \
-i foo3.mp4 -filter_complex \
"fade=in:st=0:d=1,fade=out:st=4:d=1[f0]; \
fade=in:st=0:d=1,fade=out:st=4:d=1[f1]; \
fade=in:st=0:d=1,fade=out:st=4:d=1[f2]; \
[f0][f1][f2]concat=n=3[123]" \
-map [f123] foocombine.mp4

Pan and Zoom Slideshow (26:50) Chipper Videos, 2019. Blender 2.8. Most is concerned with Ken Burns, but crossfade at the end.
Basic Slideshow (8:09) Luke Smith, 2017. Easy to put all of these together, but nothing here about ken burns
Tech Notes: FFmpeg Multi Fades In Out (37:09) Steve AB4EL, 2017. Hilarious. Drones on and on. Takes 3 pictures and makes slide show. (8:30)fade transitions

watermarking (+1 render)

Accomplished with the "overlay" filter, and also possible in a batch (2019, Cool IT Help, seek to 5:00min), the bash equivalent being

#!/bin/bash
for file in *.mp4 do
ffmpeg -i "$file" -i watermark.jpg -filter_complex "overlay = 20:20" "${file%.*}_wm".mp4
done

keyframes

Keyframing is a large topic, thus a separate post will be developed, but why is this a challenging topic?

  • keyframes are not physically part of a video. They are placemarks temporarily created and indexed inside whatever video application is being used to edit the video. Being application-specific, they must be learned for each application
  • Nomenclature issues abound. Keyframes and I-frames are similar and related, so that some use them interchangeably. There is the further confusion that iframes in HTML are different from iframes in video editing, but are again, related.
  • ffmpeg refers to keyframes as "GOP" or Group of Pictures. It's set with the "-g" switch but requires re-encoding.
  • keyframes are used differently in animation and video, so that learning basic video keyframes means sifting through many Google results for animation keyframing, ambiguously labeled. This is so common that it's hard to avoid (wastefully) learning animation usage while attempting to learn video usage.
  • Blender, which is so vast and complex that it's like learning another programming language even before one considers keyframes, is probably the only GUI for which it's worth taking the time to learn keyframes. This means learning Blender just to get to the keyframe level.

Keyframes in Blender 2.8 (7:40) Blender, 2019. Animation-centric video, but significant application to video, since keyframes apply to both. 1:30 Keyframes can be managed in the Dopesheet, Graph editor, and Timeline.
Keyframes (and other) in 2.8 (9:48) Code, Tech, and Tutorials, 2019. Solid inadvertent tour around the VSE via a simple edit. Shows how to do transitions simply without inserting them, pressing "i" for keyframe.

gifs

Definitely an important concept for texting, however a person must go online to get this done: an unknown site has your vids and any related IP. On one's own machine, you'd think it would be quick, as 3rd party apps such as gifify appear to make it so, but these almost never work. This means we're dealing with f**king seeking syntax once again

Beginning at the 2:30 mark, create 10 seconds of sequential PNGs using a 2 digit format. I resized them down to a 640x360 size, by just determining the clip native resolution with ffprobe. Eg, I resize GoPro footage is 1280x720 natively, so I drop it to 640x360 or 320x180. Zoom is natively 640x360, so I leave it, or resize it to 320x180.

ffmpeg -ss 00:02:30 -i foo.mp4 -t 0:10 -s 240x135 %02d.png

Concatenate the PNG's (or use JPG's) into a GIF

ffmpeg -i %02d.png output.gif

These tend to be made at 25 fps, so I slow it down sometimes for slo-mo, eg 12 frames per second...

ffmpeg -framerate 12/1 -i %02d.png output.gif

Saturday, May 2, 2020

non-standard application managers -- wine, python, git, latex (pacman conflicts)

In most Linux distributions, there's a package manager ("PM") application we use to update our OS and any installed applications. The Arch PM is pacman, and full updates require an internet connection for its use. It's a relatively simple process:

# pacman -Syu

The problems begin with applications that have built-in package managers specific to that application. There's only a few, but they are often called upon and u. For example:

  1. LaTeX package manager =tlmgr (TeXLive)
  2. Git package manager = complicated unless at user level. If at user level, install git with pacman and run it as a user, it will just make a directory of source. Otherwise, git apparently downloads "clones" (versions) into /opt, but then generally you want to chmod the clone to foo:foo and move it to a ~/ directory for building, then pacman to install it.
  3. Python package manager = pip
  4. Wine package manager = complicated. Each dll installing in Wine attempts to update itself and will prompt for it. None should be authorized. Also, building a version of Wine that is custom configured for the MSoft app is critical, but the underlying Arch version of wine tends to wipe them out any time it is called.

Using any of these application-specific updaters within Arch leads to failures during the next "pacman". Don't use them at all except when knowing the workarounds (see below). Essentially, there are zero problems for users who install and update the Arch Linux OS and applications using only pacman. Again, the most reliable complete update command:

# pacman -Syu

...or for application removal...

# pacman -Rs

There's also one workaround in Arch that doesn't f*ck up the index: if I download source into some directory and run...

$ makepkg -si [somepkg]

... it will make the package, and then prompt me for the password for install ("-i" flag) at the end and perform a pacman -U [package] at the end of the make. This # pacman -U properly updates the pacman index. As far as I know, # pacman -U is the only way to install outside packages without farking an install. This also means we can reliably use # pacman -Rs to uninstall packages put in through this method.

1. LaTeX - tlmgr 5Gb

2022 edit: I now use pacman, until work on thesis or something, then can do a -Rsn uninstall and do it here.

Don't install any version of LaTex with pacman. It doesn't have enough templates.

Install Tex-Live (LaTeX) directly into a user subdirectory (eg. "/home/foo/latex") and update it through the TexLive PM (tlmgr), but only at the user level, so that no admin level changes, or files used by pacman are affected.

$ cd /home/foo/latex/bin/x86_64-linux
$ tlmgr update --self
$ tlmgr update --all

UNLESS, it's the next year and haven't updated. This is called a "cross-release" update. I had to download that year's update-tlmgr.sh and run it. Described further down in post and here.

2. Git - pacman + manually configure

This took me the longest to learn, as this site agrees. Configuring for upstreaming -- if using as VCS -- is time consuming, but it's different if downloading some source. Update the git app with pacman, update the sources using git commands. Here's the Arch page.

  1. install the foundational Git application using # pacman -S git.

3.Python - pip 2Gb

Nearly every program uses Python, so we want to be sure not to break our Python installation.

The solution required three independent solutions, all three of which I install. I select one of the solutions depending on what the application requires/expects.This solution takes up several gigabytes.

  • initialize a Colab account in Google. See my post here, because there's a few steps to it. Colab handles Jupyter-type operations online. I do this development online (and save files .PY to Drive). I used to do Jupyter environment on the desktop, and this was the heaviest pip user, disrupting pacman almost entirely. IMO, Colab is practically a godsend from Google.
  • when an application requires it, a pacman install of Python. Other applications installed using pacman, may also call for additional Python modules which they add to the basic Python, and/or they may also require an older version of Python to be installed.
  • using pacman install a virtual environment for the
For Python, we can use pip, and for LaTex we can use tlmgr, to upgrade or add features to each app. The overall OS also has a package manager. For Arch, this is pacman. We can use pacman to upgrade or add packages to the Arch OS, including adding Arch versions of Python and LaTeX. The problem is, any actions accomplished with pip or tlmgr are not recorded in the pacman application index. Discrepancies between pacman's index and pip and tlmgr operations lead to significant application and OS problems. Prevention requires decisions during installation.
Contents

problems

The Python case is more complicated to *solve* than the LaTeX situation, because a variety of applications depend on Python, unlike LaTeX. However, both situations equally *cause* pacman update fails for the same, indexing, reason, so that both the Python and the LaTeX cases must be solved.

Python

Many applications rely upon Python. More technically, Python is a dependency for for many applications.

Imagine some application with a Python dependency, say youtube-dl. Imagine that both Python and youtube-dl were installed by pacman. They both work fine. Now suppose the user decides to add a Python module using pip instead of pacman. Everything might be fine with some applications that depend on Python, but youtube-dl is an example of an application sensitive to Python changes. The youtube-dl app looks for versions of Python installed by Arch, but will instead detect versions updated by pip. This discrepancy in turn leads youtube-dl to spawn errors, and errors in turn lead to the application exiting. How can this be solved?

$ youtube-dl https://www.youtube.com/watch?v=QLpz7PtiP2k
Traceback (most recent call last):
File "/usr/bin/youtube-dl", line 6, in
from pkg_resources import load_entry_point
File "/usr/lib/python3.8/site-packages/pkg_resources/__init__.py", line 3259, in
def _initialize_master_working_set():
File "/usr/lib/python3.8/site-packages/pkg_resources/__init__.py", line 3242, in _call_aside
f(*args, **kwargs)
File "/usr/lib/python3.8/site-packages/pkg_resources/__init__.py", line 3271, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File "/usr/lib/python3.8/site-packages/pkg_resources/__init__.py", line 584, in _build_master
ws.require(__requires__)
File "/usr/lib/python3.8/site-packages/pkg_resources/__init__.py", line 901, in require
needed = self.resolve(parse_requirements(requirements))

More drastically, this can happen with an entire OS. Say the user keeps his OS up to date with pacman, and decides to install Python using pacman. Later, he upgrades Python using Python's pip manager. Still later, the user attempts to update the entire OS, which is a pacman action. As part of its upgrade procedure, pacman verifies the integrity of all installed applications against its index. Since the changes made to Python via pip were not registered into pacman's version index, pacman cannot resolve the pip installed modules against the pacman index. These discrepancies cause the pacman update to exit with errors. No update will be accomplished. How can this be solved?

LaTeX

If having any problems with LaTeX updates, even the tug.org website recommends just replacing with latest edition. However, there is one workaround if things aren't more than a year or two old.

$ tlmgr update --self
tlmgr: Local TeX Live (2020) is older than remote repository (2021).
Cross release updates are only supported with
update-tlmgr-latest(.sh/.exe) -- --upgrade
See https://tug.org/texlive/upgrade.html for details.

For the problem above, download update-tlmgr-latest.sh, make it executable (chmod +x or file manager), and put it in /home/foo/latex or wherever your latex user-level top directory is at. Go into that directory and:

$ sh update-tlmgr-latest.sh -- --upgrade
$ tlmgr update --self
$ tlmgr update --all
.

Wine

Wine also can pull-in specific packages, when we try to make wine bottles. However, any time there's an OS update, pacman will write a new wine directory in ~/.wine. After it's overwritten, it will use that vanilla version instead of the wine bottle we built for the app. How can this be solved?

solutions

In the case of an app like youtube-dl, it's easy to uninstall the entire app (# pacman -Rns) and reinstall. Or to play with uninstalling its pieces until one has a hit

The levels of involvement vary, but the strategy is the same for both Python and for LaTeX: install these independently of Arch from the start, in /home/user directory, and then update any path statements necessary for the Arch installed apps to find the program. Once these are in at the user level, there's no problem updating them with pip and tlmgr, because the updates are strictly within one's home directory, not the larger Arch installation. Accordingly, one can add features at will, which is often desirable when running the latest Spyder or what have you. For LaTeX, it's even less of a hassle, because there are no dependencies: one just needs to update $PATH statements following install. One can create an install in either case using, eg. $ mkdir /home/foo/latex and similarly with Python, though perhaps using a new folder for any version changes.


In the case of the OS update failure, one has no pleasant choices :uninstall then reinstall all of Python (immense time drain), or update the OS using an override (# pacman -SyuI), which then leaves a potentially unstable Python install for its dependencies. This is true with LaTeX also, but nearly zero apps depend on LaTeX.

install notes

I've decided to use the 3rd party updaters to both install (Python - pip, LaTeX - tlmgr for TexLive), There are a couple of considerations.
  • Install in user-level directory
  • update path statements afterward, so the installation can find them. Path statements can be complex, because there are various Path statements to consider.

prevention

Sometimes one doesn't have a choice but to install packages via pip, but then what happens downstream with a pacman upgrade is ugly. It will look like this, and there's a couple of workarounds.
  • uninstall the pip upgrades, upgrade the system via pacman, then go back to pip and install whatever necessary pip packages.
  • add the --overwrite=* flag to the standard "Syu". This causes pacman to simply overwrite any python files that seem inaccurate. This places pacman in the boss position over pip, but it also farks-up the pip version of the installation which, downstream, is a b*tch.